text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FoscamCleanup { abstract class FileGrouper { public string Source { get; set; } public string Destination { get; set; } public string Name { get; private set; } public bool IsDecimatable { get; set; } public FileGrouper() { } public FileGrouper(string name) { Name = name; } public bool AppliesTo(string name) => name == Name; public abstract DateTime GetDateFromFileName(string fileName); public virtual bool IsRelevantFile(string fileName) => true; } }
using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace XF40Demo.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class FramedTextView : StackLayout { #region Border public static BindableProperty BorderColourProperty = BindableProperty.Create(nameof(BorderColour), typeof(Color), typeof(FramedTextView), Color.Black); public Color BorderColour { get { return (Color)GetValue(BorderColourProperty); } set { SetValue(BorderColourProperty, value); } } public static BindableProperty BorderRadiusProperty = BindableProperty.Create(nameof(BorderRadius), typeof(float), typeof(FramedTextView)); public float BorderRadius { get { return (float)GetValue(BorderRadiusProperty); } set { SetValue(BorderRadiusProperty, value); } } #endregion #region Title public static BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(FramedTextView)); public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } public static BindableProperty TitleColourProperty = BindableProperty.Create(nameof(TitleColour), typeof(Color), typeof(FramedTextView), Color.Default); public Color TitleColour { get { return (Color)GetValue(TitleColourProperty); } set { SetValue(TitleColourProperty, value); } } public static BindableProperty TitleAttributesProperty = BindableProperty.Create(nameof(TitleAttributes), typeof(FontAttributes), typeof(FramedTextView), FontAttributes.None); public FontAttributes TitleAttributes { get { return (FontAttributes)GetValue(TitleAttributesProperty); } set { SetValue(TitleAttributesProperty, value); } } #endregion #region Text public static BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(FramedTextView)); public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static BindableProperty TextColourProperty = BindableProperty.Create(nameof(TextColour), typeof(Color), typeof(FramedTextView), Color.Default); public Color TextColour { get { return (Color)GetValue(TextColourProperty); } set { SetValue(TextColourProperty, value); } } public static BindableProperty TextAttributesProperty = BindableProperty.Create(nameof(TextAttributes), typeof(FontAttributes), typeof(FramedTextView), FontAttributes.None); public FontAttributes TextAttributes { get { return (FontAttributes)GetValue(TextAttributesProperty); } set { SetValue(TextAttributesProperty, value); } } public static BindableProperty TextTypeProperty = BindableProperty.Create(nameof(TextType), typeof(TextType), typeof(FramedTextView), TextType.Text); public TextType TextType { get { return (TextType)GetValue(TextTypeProperty); } set { SetValue(TextTypeProperty, value); } } #endregion public FramedTextView() { InitializeComponent(); } } }
// <copyright file="DataPayload.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2019 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /** * @author Alireza Ghodrati */ using System; using System.Text; using FiroozehGameService.Utils.Serializer.Utils.IO; namespace FiroozehGameService.Models.GSLive.RT { [Serializable] internal class DataPayload : Payload { private int _extraLen; private int _payloadLen; private int _receiverLen; private int _senderLen; internal byte[] ExtraData; internal byte[] Payload; internal string ReceiverId; internal string SenderId; public DataPayload(string senderId = null, string receiverId = null, byte[] payload = null, byte[] extraData = null) { ExtraData = extraData; SenderId = senderId; ReceiverId = receiverId; Payload = payload; } public DataPayload(byte[] buffer) { Deserialize(buffer); } internal void Deserialize(byte[] buff) { using (var packetWriter = ByteArrayReaderWriter.Get(buff)) { var haveSender = packetWriter.ReadByte(); var haveReceiver = packetWriter.ReadByte(); var havePayload = packetWriter.ReadByte(); var haveExtra = packetWriter.ReadByte(); if (haveSender == 0x1) _senderLen = packetWriter.ReadByte(); if (haveReceiver == 0x1) _receiverLen = packetWriter.ReadByte(); if (havePayload == 0x1) _payloadLen = packetWriter.ReadUInt16(); if (haveExtra == 0x1) _extraLen = packetWriter.ReadUInt16(); if (haveSender == 0x1) SenderId = ConvertToString(packetWriter.ReadBytes(_senderLen)); if (haveReceiver == 0x1) ReceiverId = ConvertToString(packetWriter.ReadBytes(_receiverLen)); if (havePayload == 0x1) Payload = packetWriter.ReadBytes(_payloadLen); if (haveExtra == 0x1) ExtraData = packetWriter.ReadBytes(_extraLen); } } internal byte[] Serialize() { byte havePayload = 0x0, haveExtra = 0x0, haveSender = 0x0, haveReceiver = 0x0; short prefixLen = 4 * sizeof(byte); if (Payload != null) { havePayload = 0x1; _payloadLen = Payload.Length; prefixLen += sizeof(ushort); } if (ExtraData != null) { haveExtra = 0x1; _extraLen = ExtraData.Length; prefixLen += sizeof(ushort); } if (SenderId != null) { haveSender = 0x1; _senderLen = SenderId.Length; prefixLen += sizeof(byte); } if (ReceiverId != null) { haveReceiver = 0x1; _receiverLen = ReceiverId.Length; prefixLen += sizeof(byte); } var packetBuffer = BufferPool.GetBuffer(BufferSize(prefixLen)); using (var packetWriter = ByteArrayReaderWriter.Get(packetBuffer)) { // header Segment packetWriter.Write(haveSender); packetWriter.Write(haveReceiver); packetWriter.Write(havePayload); packetWriter.Write(haveExtra); if (haveSender == 0x1) packetWriter.Write((byte) _senderLen); if (haveReceiver == 0x1) packetWriter.Write((byte) _receiverLen); if (havePayload == 0x1) packetWriter.Write((ushort) _payloadLen); if (haveExtra == 0x1) packetWriter.Write((ushort) _extraLen); // data Segment if (haveSender == 0x1) packetWriter.Write(ConvertToBytes(SenderId)); if (haveReceiver == 0x1) packetWriter.Write(ConvertToBytes(ReceiverId)); if (havePayload == 0x1) packetWriter.Write(Payload); if (haveExtra == 0x1) packetWriter.Write(ExtraData); } return packetBuffer; } internal int BufferSize(short prefixLen) { return prefixLen + _senderLen + _receiverLen + _payloadLen + _extraLen; } public override string ToString() { return "DataPayload{ReceiverID='" + ReceiverId + '\'' + ", SenderID='" + SenderId + '\'' + ", Payload='" + Payload?.Length + '\'' + '}'; } internal string ConvertToString(byte[] data) { return Encoding.UTF8.GetString(data); } internal byte[] ConvertToBytes(string data) { return Encoding.UTF8.GetBytes(data); } } }
using Entitas; using Entitas.CodeGeneration.Attributes; [GameState] [Unique] [Event(false)] public sealed class ScoreComponent : IComponent { public int value; }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BookshelfProject1.Models { public class Book { //Private fields are created //when your are building a model in c# you will always want an ID //The ID is the key identification //giving each object an identifier //ForeignKey how to establish relationship with another class or table //[key] key is only relevant to whats underneath it. //Primary key //The keys that are gernerated for users is a string primary key doesn't have to be an int [Key] public int ID { get; set; } public string Title { get; set; } public DateTime PublishedDate { get; set; } public string Description { get; set; } public string ISBN { get; set; } //ForeignKey [ForeignKey("Category")] public int CategoryID { get; set; } //object name + object name again = navigation property //nav prop=allows to connect classes public virtual Category category { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BanSupport { public class UIExtensionManager : MonoBehaviour { private static UIExtensionManager Instance; private List<ExBase> updateDatas; private void Awake() { this.gameObject.hideFlags = HideFlags.HideInHierarchy; DontDestroyOnLoad(this.gameObject); updateDatas = ListPool<ExBase>.Get(); } private void OnDestroy() { ListPool<ExBase>.Release(updateDatas); updateDatas = null; } private void LateUpdate() { for (int i = updateDatas.Count - 1; i >= 0; i--) { var curBase = updateDatas[i]; if (curBase == null) { updateDatas.RemoveAt(i); continue; } if (!curBase.DoUpdate()) { updateDatas.RemoveAt(i); } } } public static void Add(ExBase exBase) { if (Instance != null) { if (!Instance.updateDatas.Contains(exBase)) { Instance.updateDatas.Add(exBase); } } } public static void Remove(ExBase exBase) { if (Instance != null) { if (Instance.updateDatas.Contains(exBase)) { Instance.updateDatas.Remove(exBase); } } } public static void Init() { if (Instance == null) { Instance = new GameObject("UIExtensionManager").AddComponent<UIExtensionManager>(); } } } }
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 Lab_2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } void Roots(double a, double b, double c) { double D = b * b - 4 * a * c; if (D > 0) { try { double x1_res = Math.Round((-b + Math.Sqrt(D)) / (2 * a), 5); double x2_res = Math.Round((-b - Math.Sqrt(D)) / (2 * a), 5); X1.Text = x1_res.ToString(); X2.Text = x2_res.ToString(); } catch { } } if (D == 0) { try { double x1_res = Math.Round(-b / (2 * a), 5); X1.Text = x1_res.ToString(); } catch { } X2.Text = ""; } if (D < 0) { X1.Text = "D = 0!!"; } } private void CheckInput(TextBox textBox, object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back) { if (e.KeyChar == '-') { if (textBox.Text.Length > 0 || textBox.Text.Contains('-')) e.KeyChar = (char)Keys.None; } if (e.KeyChar == '+') if (textBox.Text.Length > 0 || textBox.Text.Contains('+')) e.KeyChar = (char)Keys.None; if (e.KeyChar == ',') { if (textBox.Text.Contains(',') || textBox.Text.Length == 0) e.KeyChar = (char)Keys.None; } if (e.KeyChar != '-' && e.KeyChar != '+' && e.KeyChar != ',') e.KeyChar = (char)Keys.None; } } private void A_KeyPress(object sender, KeyPressEventArgs e) { CheckInput(A, sender, e); } private void B_KeyPress(object sender, KeyPressEventArgs e) { CheckInput(B, sender, e); } private void C_KeyPress(object sender, KeyPressEventArgs e) { CheckInput(C, sender, e); } private void Solution_Click(object sender, EventArgs e) { if (Method_1.Checked) { try { double a = Convert.ToDouble(A.Text); double b = Convert.ToDouble(B.Text); double c = Convert.ToDouble(C.Text); double D = b * b - 4 * a * c; if (D > 0) { double x1_res = Math.Round((-b + Math.Sqrt(D)) / (2 * a), 5); double x2_res = Math.Round((-b - Math.Sqrt(D)) / (2 * a), 5); X1.Text = x1_res.ToString(); X2.Text = x2_res.ToString(); } if (D == 0) { double x1_res = Math.Round(-b / (2 * a), 5); X1.Text = x1_res.ToString(); X2.Text = ""; } if (D < 0) { X1.Text = "D = 0!!"; } } catch (OverflowException of) { } } if (Method_2.Checked) { try { double a = Convert.ToDouble(A.Text); double b = Convert.ToDouble(B.Text); double c = Convert.ToDouble(C.Text); Roots(a, b, c); } catch { } } if (Method_3.Checked) { try { double a = Convert.ToDouble(A.Text); double b = Convert.ToDouble(B.Text); double c = Convert.ToDouble(C.Text); Solution s = new Solution(); double?[] res = s.ShowRoots(a, b, c); if (res[0] != null && res[1] != null) { X1.Text = res[0].ToString(); X2.Text = res[1].ToString(); } if (res[0] != null && res[1] == null) { X1.Text = res[0].ToString(); X2.Text = ""; } if (res[0] == null && res[1] == null) { X1.Text = "D = 0!!"; } } catch { } } } private void Clear_Click(object sender, EventArgs e) { A.Text = ""; B.Text = ""; C.Text = ""; X1.Text = ""; X2.Text = ""; } private void End_Click(object sender, EventArgs e) { this.Close(); } public class Solution { public double?[] ShowRoots(double a, double b, double c) { double?[] results = new double?[2]; double D = b * b - 4 * a * c; if (D > 0) { try { double x1_res = Math.Round((-b + Math.Sqrt(D)) / (2 * a), 5); double x2_res = Math.Round((-b - Math.Sqrt(D)) / (2 * a), 5); results[0] = x1_res; results[1] = x2_res; } catch { } } if (D == 0) { try { double x1_res = Math.Round(-b / (2 * a), 5); results[0] = x1_res; } catch { } results[1] = null; } if (D < 0) { results[0] = null; results[1] = null; } return results; } } } }
using System; using System.Collections.Generic; using Company.Interface; namespace Company.Models { class Manager : Employee, IManager { // private IList<Employee> emplList = new List<Employee>(); public Manager(string id, string firsName, string lastName, decimal salary, Department department) : base(id, firsName, lastName, salary, department) { this.EmplList = new List<RegularEmployee>(); } public IList<RegularEmployee> EmplList { get; set; } public void AddEmployees(List<RegularEmployee> empl) { foreach (var employee in empl) { this.EmplList.Add(employee); } } public override string ToString() { string retStr = String.Format("ID - {0}, Name - {1} {2}, Salary - {3}, Department - {4}" , this.Id, this.FirstName, this.LastName, this.Salary, this.Depart); return retStr; } } }
/******************************************* * * This class should only control Modules that involves Player Air Controls * NO CALCULATIONS SHOULD BE DONE HERE * *******************************************/ using DChild.Gameplay.Objects; using DChild.Gameplay.Objects.Characters; namespace DChild.Gameplay.Player.Controllers { [System.Serializable] public class AirMovementController : PlayerControllerManager.Controller { private IAirMove m_move; public override void Initialize() => m_move = m_player.GetComponentInChildren<IAirMove>(); public void UpdateVelocity() => m_move.UpdateVelocity(); public void HandleMovement() { var moveInput = m_input.direction.horizontalInput; m_move.Move(moveInput); HandleOrientation(moveInput); } private void HandleOrientation(float moveInput) { if (moveInput > 0) { m_player.SetFacing(Direction.Right); } else if (moveInput < 0) { m_player.SetFacing(Direction.Left); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Otiport.API.Data.Entities.AddressInformations; namespace Otiport.API.Contract.Response.Common { public class GetDistrictsResponse : ResponseBase { public IEnumerable<DistrictEntity> Districts; } }
using System; namespace FunctionalProgramming.Monad.Transformer { public sealed class IoEither<TLeft, TRight> { public readonly Io<IEither<TLeft, TRight>> Out; public IoEither(Io<IEither<TLeft, TRight>> io) { Out = io; } public IoEither(IEither<TLeft, TRight> either) : this(Io.Apply(() => either)) { } public IoEither(TRight rightVal) : this(rightVal.AsRight<TLeft, TRight>()) { } public IoEither(TLeft leftVal) : this(leftVal.AsLeft<TLeft, TRight>()) { } public IoEither<TLeft, TResult> FMap<TResult>(Func<TRight, TResult> f) { return new IoEither<TLeft, TResult>(Out.Select(either => either.Select(f))); } public IoEither<TLeft, TResult> Bind<TResult>(Func<TRight, IoEither<TLeft, TResult>> f) { return new IoEither<TLeft, TResult>(Out.SelectMany(either => either.Match( left: l => Io.Apply(() => l.AsLeft<TLeft, TResult>()), right: r => f(r).Out))); } } public static class IoEither { public static IoEither<TLeft, TRight> ToIoEither<TLeft, TRight>(this Io<IEither<TLeft, TRight>> io) { return new IoEither<TLeft, TRight>(io); } public static IoEither<TLeft, TRight> ToIoEither<TLeft, TRight>(this Io<TRight> io) { return new IoEither<TLeft, TRight>(io.Select(right => right.AsRight<TLeft, TRight>())); } public static IoEither<TLeft, TRight> ToIoEither<TLeft, TRight>(this IEither<TLeft, TRight> either) { return new IoEither<TLeft, TRight>(either); } public static IoEither<TLeft, TRight> AsLeftIo<TLeft, TRight>(this TLeft t) { return new IoEither<TLeft, TRight>(t); } public static IoEither<TLeft, TRight> AsRightIo<TLeft, TRight>(this TRight t) { return new IoEither<TLeft, TRight>(t); } public static IoEither<TLeft, TResult> Select<TLeft, TRight, TResult>(this IoEither<TLeft, TRight> ioT, Func<TRight, TResult> f) { return ioT.FMap(f); } public static IoEither<TLeft, TResult> SelectMany<TLeft, TRight, TResult>( this IoEither<TLeft, TRight> ioT, Func<TRight, IoEither<TLeft, TResult>> f) { return ioT.Bind(f); } public static IoEither<TLeft, TSelect> SelectMany<TLeft, TRight, TResult, TSelect>( this IoEither<TLeft, TRight> ioT, Func<TRight, IoEither<TLeft, TResult>> f, Func<TRight, TResult, TSelect> selector) { return ioT.SelectMany(a => f(a).SelectMany(b => selector(a, b).AsRightIo<TLeft, TSelect>())); } } }
namespace A4CoreBlog.Data.ViewModels { public class PostDetailsViewModel : PostListBasicViewModel { public string Description { get; set; } } }
using System.Text.RegularExpressions; namespace Hz.Infrastructure.Common { public static class Validate { /// <summary> /// 判断输入的字符串是否是一个合法的手机号 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IsMobilePhone(string input) { Regex regex = new Regex("^1[34578]\\d{9}$"); return regex.IsMatch(input); } } }
using System; namespace ppedv.Planner.Model { public class Urlaub : Entity { public virtual Mitarbeiter Mitarbeiter { get; set; } public DateTime Von { get; set; } public DateTime Bis { get; set; } public UrlaubsStatus Status { get; set; } } public enum UrlaubsStatus { Geplant, Beantragt, Abgelehnt, Genehmigt } }
using Pe.Stracon.SGC.Infraestructura.CommandModel.Base; using System; namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual { /// <summary> /// Clase que representa la entidad Flujo Aprobacion Participante /// </summary> /// <remarks> /// Creación: GMD 20150508 <br /> /// Modificación: <br /> /// </remarks> public class FlujoAprobacionParticipanteEntity : Entity { /// <summary> /// Codigo Flujo Aprobacion Participante /// </summary> public Guid CodigoFlujoAprobacionParticipante { get; set; } /// <summary> /// Codigo Flujo Aprobacion Estadio /// </summary> public Guid CodigoFlujoAprobacionEstadio { get; set; } /// <summary> /// Codigo Trabajador /// </summary> public Guid CodigoTrabajador { get; set; } /// <summary> /// Codigo Tipo Participante /// </summary> public string CodigoTipoParticipante { get; set; } /// <summary> /// Codigo Participante Original /// </summary> public Guid CodigoTrabajadorOriginal { get; set; } } }
using System; using System.IO; using System.Windows.Forms; namespace GeneratorApp { public class GenerateController { public void CreateController(string fileName,string modelName) { try { if (File.Exists(fileName)) { MessageBox.Show("Check file already exists"); return; } // Create a new file using (var sw = File.CreateText(fileName)) { sw.WriteLine("using System;"); sw.WriteLine("using System.Linq;"); sw.WriteLine("using HRIS.Controllers;"); sw.WriteLine("using Microsoft.AspNetCore.Http;"); sw.WriteLine("using Microsoft.AspNetCore.Mvc;"); sw.WriteLine("using System.Threading.Tasks;"); sw.WriteLine("using HRIS.WebQueryModel;"); sw.WriteLine(""); sw.WriteLine("namespace HRIS.Web.Host.Controllers"); sw.WriteLine("{"); sw.WriteLine("public class " + modelName + "Controller : HRISControllerBase"); sw.WriteLine("{"); sw.WriteLine(""); sw.WriteLine("private readonly I" + modelName + "AppService _" +modelName.ToLower()+"AppService;"); sw.WriteLine(""); sw.WriteLine("public " + modelName + "Controller(I" +modelName+"AppService "+modelName.ToLower()+"AppService)"); sw.WriteLine("{"); sw.WriteLine("_"+modelName.ToLower()+"AppService = "+modelName.ToLower()+"AppService;"); sw.WriteLine("}");//end constructor sw.WriteLine("[HttpGet]"); sw.WriteLine("public async Task<IActionResult> Get(int id)"); sw.WriteLine("{"); sw.WriteLine("if (id<0)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: BadRequest: Id is null or empty\");"); sw.WriteLine("return BadRequest(\"Id is null or empty\");"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("try"); sw.WriteLine("{"); sw.WriteLine("var result = await _"+modelName.ToLower()+"AppService.GetById(id);"); sw.WriteLine(""); sw.WriteLine("return result == null ? StatusCode(StatusCodes.Status204NoContent, result) : Ok(result);"); sw.WriteLine("}"); sw.WriteLine("catch (Exception ex)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: [" + modelName + "Controller] -[Get]: ExceptionMessage: \" + ex.Message +"); sw.WriteLine("\", InnerException: \" + ex.InnerException +"); sw.WriteLine("\", StackTrace: \" + ex.StackTrace);"); sw.WriteLine(""); sw.WriteLine("return StatusCode(StatusCodes.Status500InternalServerError, ex.InnerException);"); sw.WriteLine("}"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("[HttpGet]"); sw.WriteLine("public async Task<IActionResult> GetAll(ModelQuery queryObject)"); sw.WriteLine("{"); sw.WriteLine("try"); sw.WriteLine("{"); sw.WriteLine("var result = await _"+modelName.ToLower()+ "AppService.GetAll(queryObject);"); sw.WriteLine("return result.TotalItems > 0 ? Ok(result) : StatusCode(StatusCodes.Status204NoContent, result);"); sw.WriteLine("}"); sw.WriteLine("catch (Exception ex)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: [" + modelName + "Controller] -[GetAll]: ExceptionMessage: \" + ex.Message +"); sw.WriteLine("\", InnerException: \" + ex.InnerException +"); sw.WriteLine("\", StackTrace: \" + ex.StackTrace);"); sw.WriteLine(""); sw.WriteLine("return StatusCode(StatusCodes.Status500InternalServerError, ex.InnerException);"); sw.WriteLine("}"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("[HttpPost]"); sw.WriteLine("public async Task<IActionResult> Create([FromBody] " + modelName + "Dto " + modelName.ToLower() + ")"); sw.WriteLine("{"); sw.WriteLine("if (" + modelName.ToLower() + " == null)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: BadRequest: " + modelName + " is empty or null\");"); sw.WriteLine("return BadRequest(\"" + modelName + " is empty or null\");"); sw.WriteLine("}"); sw.WriteLine("try"); sw.WriteLine("{"); sw.WriteLine("var result = await _"+modelName.ToLower()+"AppService.Create(" + modelName.ToLower() + ");"); sw.WriteLine("return result != null ? Ok(result) : StatusCode(StatusCodes.Status204NoContent, result);"); sw.WriteLine("}"); sw.WriteLine("catch (Exception ex)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: [" + modelName + "Controller] -[Create]: ExceptionMessage: \" + ex.Message +"); sw.WriteLine("\", InnerException: \" + ex.InnerException +"); sw.WriteLine("\", StackTrace: \" + ex.StackTrace);"); sw.WriteLine(""); sw.WriteLine("return StatusCode(StatusCodes.Status500InternalServerError);"); sw.WriteLine("}"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("[HttpPut]"); sw.WriteLine("public async Task<IActionResult> Update([FromBody] " + modelName + "Dto " + modelName.ToLower() + ")"); sw.WriteLine("{"); sw.WriteLine("if (" + modelName.ToLower() + " == null)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: BadRequest: " + modelName + " is empty or null\");"); sw.WriteLine("return BadRequest(\"" + modelName + " is empty or null\");"); sw.WriteLine("}"); sw.WriteLine("try"); sw.WriteLine("{"); sw.WriteLine("var result = await _"+modelName.ToLower()+"AppService.Update(" + modelName.ToLower() + ");"); sw.WriteLine("return result != null ? Ok(result) : StatusCode(StatusCodes.Status204NoContent, result);"); sw.WriteLine("}"); sw.WriteLine("catch (Exception ex)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: [" + modelName + "Controller] -[Update]: ExceptionMessage: \" + ex.Message +"); sw.WriteLine("\", InnerException: \" + ex.InnerException +"); sw.WriteLine("\", StackTrace: \" + ex.StackTrace);"); sw.WriteLine("return StatusCode(StatusCodes.Status500InternalServerError);"); sw.WriteLine("}"); sw.WriteLine("}"); sw.WriteLine(""); //sw.WriteLine("[HttpDelete]"); //sw.WriteLine("public async Task<IActionResult> Delete([FromBody] " + modelName + "Dto " + modelName.ToLower() + ")"); //sw.WriteLine("{"); //sw.WriteLine("if (" + modelName.ToLower() + " == null)"); //sw.WriteLine("{"); //sw.WriteLine("Logger.Error(\"ERROR: BadRequest: " + modelName + " is empty or null\");"); //sw.WriteLine("return BadRequest(\"" + modelName + " is empty or null\");"); //sw.WriteLine("}"); //sw.WriteLine(""); //sw.WriteLine("try"); //sw.WriteLine("{"); //sw.WriteLine("await _"+modelName.ToLower()+"AppService.Delete(" + modelName.ToLower() + ");"); //sw.WriteLine("return Ok(true);"); //sw.WriteLine("}"); //sw.WriteLine("catch (Exception ex)"); //sw.WriteLine("{"); //sw.WriteLine("Logger.Error(\"ERROR: [" + modelName + "Controller] -[Delete]: ExceptionMessage: \" + ex.Message +"); //sw.WriteLine("\", InnerException: \" + ex.InnerException +"); //sw.WriteLine("\", StackTrace:\" + ex.StackTrace);"); //sw.WriteLine(""); //sw.WriteLine("return StatusCode(StatusCodes.Status500InternalServerError);"); //sw.WriteLine("}"); //sw.WriteLine("}"); sw.WriteLine("[HttpDelete]"); sw.WriteLine("public async Task<IActionResult> Delete(int? id)"); sw.WriteLine("{"); sw.WriteLine("if (!id.HasValue)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: BadRequest: Id is empty or null\");"); sw.WriteLine("return BadRequest(\"Id is empty or null\");"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("try"); sw.WriteLine("{"); sw.WriteLine("await _" + modelName.ToLower() + "AppService.DeleteById(id.Value);"); sw.WriteLine("return Ok(true);"); sw.WriteLine("}"); sw.WriteLine("catch (Exception ex)"); sw.WriteLine("{"); sw.WriteLine("Logger.Error(\"ERROR: [" + modelName + "Controller] -[Delete_ID]: ExceptionMessage: \" + ex.Message +"); sw.WriteLine("\", InnerException: \" + ex.InnerException +"); sw.WriteLine("\", StackTrace:\" + ex.StackTrace);"); sw.WriteLine(""); sw.WriteLine("return StatusCode(StatusCodes.Status500InternalServerError);"); sw.WriteLine("}"); sw.WriteLine("}"); sw.WriteLine(""); sw.WriteLine("}");//end class sw.WriteLine("}");//end namespace } } catch (Exception Ex) { Console.WriteLine(Ex.ToString()); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoostPadScript : MonoBehaviour { public enum AngularVelocityMode { None, // skip setting angular velocity Zero, // set angular velocity to 0 TowardsFacing, // set angular velocity relative to world, but with world forward rotated in projected direction of boost pad World,// set angular velocity relative to world Local // set angular velocity relative to car direction } [Tooltip("Speed to either set or add")] public float Speed = 1f; [Tooltip("If the speed should be added instead of set")] public bool AddSpeed = false; [Tooltip("If the car should be rotated to face the direction of the boost pad")] public bool SetDirection = false; [Tooltip("If the speed is added in the direction of the boost pad instead of the car")] public bool SetSpeedInDirection = false; public ForceMode SetSpeedInDirectionForceMode = ForceMode.VelocityChange; [Space] [Tooltip("If the angular velocity of the car should be set when touching the boost pad. Has multiple modes of applying angular velocity")] public AngularVelocityMode SetAngularVelocity = AngularVelocityMode.None; [Tooltip("What angular velocity the car should be set to when touching the boost pad. Value is used differently depending on mode")] public Vector3 AngularVelocity; [Space] public bool IgnoreNextJumpZeroing = false; [Space] [Tooltip("Assign an object here to use its forward direction instead of the forward direction of this object. The object position can be anywhere")] public Transform OptionalDirectionOverride; // TODO: option to either ignore or allow setting or adding speed values that would result in a lower speed // IDEA: if not allowed, interpret value as inverting direction // public bool AllowRemovingSpeed = false; private void OnTriggerEnter(Collider other) { var rb = other.attachedRigidbody; if (!rb) return; Transform directionTransform = transform; if (OptionalDirectionOverride) directionTransform = OptionalDirectionOverride; if (SetDirection) { rb.MoveRotation(directionTransform.rotation); // rb.velocity = transform.forward * rb.velocity.magnitude; } // if (AddSpeed && Speed == 0) // return; if (SetSpeedInDirection) { if (!AddSpeed) rb.velocity = Vector3.zero; rb.AddForce(directionTransform.forward * Speed, SetSpeedInDirectionForceMode); } else { if (AddSpeed) rb.velocity += Vector3.Normalize(rb.velocity) * Speed; else //if (rb.velocity.sqrMagnitude < Speed * Speed) rb.velocity = Vector3.Normalize(rb.velocity) * Speed; } // if (SetAngularVelocity) // rb.angularVelocity = (directionTransform.forward - rb.transform.forward) * AngularVelocity; switch (SetAngularVelocity) { case AngularVelocityMode.None: break; case AngularVelocityMode.Zero: rb.angularVelocity = Vector3.zero; break; case AngularVelocityMode.TowardsFacing: var dir = Vector3.Project(directionTransform.forward, Vector3.up).normalized; var quat = Quaternion.FromToRotation(Vector3.forward, dir); rb.angularVelocity = quat * AngularVelocity; // rb.angularVelocity = AngularVelocity;// * (directionTransform.forward - rb.transform.forward); break; case AngularVelocityMode.World: rb.angularVelocity = AngularVelocity; break; case AngularVelocityMode.Local: rb.angularVelocity = rb.transform.localToWorldMatrix * AngularVelocity; break; } if(IgnoreNextJumpZeroing){ other.GetComponent<SteeringScript>()?.DontZeroNextOnAir(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ReactData.Models; using ReactData.Repositories; namespace ReactData.Services { public class UserService : IUserService { private readonly IRepository _userRepository; private readonly ILogger _logger; public UserService(IRepository userRepository, ILogger<UserService> Logger) { _userRepository = userRepository; _logger = Logger; } public async Task<bool> AddUser(User user) { try { await _userRepository.AddUser(user); return true; } catch (Exception e) { _logger.LogError(e.Message); return false; } } public async Task<bool> AddUsers(List<User> users) { try { var nUser = users.Select(user => user.ID = 0); await _userRepository.AddUsers(users); return true; } catch (Exception e) { _logger.LogError(e.Message); return false; } } public async Task<List<User>> GetUsers() { return await _userRepository.GetUserList(); } } }
using System.Reflection; using BDTest.Test; namespace BDTest.Extensions; internal static class BuildableTestExtensions { internal static MethodInfo GetTestMethod(this BuildableTest buildableTest) => buildableTest?.BdTestBase?.GetType()?.GetMethods()?.FirstOrDefault(x => x.Name == buildableTest.CallerMember); internal static Type GetTestClass(this BuildableTest buildableTest) => buildableTest?.BdTestBase?.GetType(); }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace MSt.Data.Entity { /// <summary> /// User used to identify a authenticated user /// </summary> public class User { /// <summary> /// ID User /// </summary> [Key] public Guid Guid { get; set; } /// <summary> /// User Login /// </summary> [Required] [MaxLength(50)] public string Login { get; set; } /// <summary> /// Password for login /// </summary> [Required] [MaxLength(50)] public string Password { get; set; } /// <summary> /// User email /// </summary> [Required] [MaxLength(50)] public string Email { get; set; } /// <summary> /// Collection of claims of the user /// </summary> public ICollection<UserClaim> UserClaims { get; set; } /// <summary> /// Collection of the roles of the user /// </summary> public ICollection<UserRole> UserRoles { get; set; } /// <summary> /// If the user is deleted /// </summary> public bool IsDeleted { get; set; } } }
using System.ComponentModel; namespace ProgressBar_test { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : System.Windows.Window { public MainWindow() { InitializeComponent(); } BackgroundWorker worker = new BackgroundWorker(); private void Window_ContentRendered(object sender, System.EventArgs e) { worker.WorkerReportsProgress = true; worker.DoWork += worker_DoWork; worker.ProgressChanged += worker_ProgressChanged; worker.WorkerSupportsCancellation = true; } void worker_DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i < 100; i++) { if ((worker.CancellationPending == true)) { e.Cancel = true; break; } else { (sender as BackgroundWorker).ReportProgress(i); System.Threading.Thread.Sleep(100); } } } void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { pbStatus.Value = e.ProgressPercentage; } private void button1_Click(object sender, System.Windows.RoutedEventArgs e) { worker.RunWorkerAsync(); } private void button2_Click(object sender, System.Windows.RoutedEventArgs e) { worker.CancelAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using ApartmentApps.Api; using ApartmentApps.API.Service.Models; using Microsoft.Owin; using Owin; using Microsoft.Owin.Security.OAuth; [assembly: OwinStartup(typeof(ApartmentApps.API.Service.Startup))] namespace ApartmentApps.API.Service { public partial class Startup { public void Configuration(IAppBuilder app) { //var a = new UnityContainer(); //a.RegisterType<ApplicationDbContext>() //UnityConfig.RegisterComponents(); ConfigureAuth(app); app.MapSignalR(); //app. } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entities.Helpers { public class HelperEnums { public enum DataType { Number = 1, Checkbox = 2, Time = 3, Text = 4, DropDown = 5 } } }
using AutoMapper; using Communicator.Core.Domain; using Communicator.Infrastructure.Dto; namespace Communicator.Infrastructure.Mappers { public static class AutoMapperConfig { public static IMapper RegisterMapper() { return new MapperConfiguration(config => { config.CreateMap<User, UserDto>().ForMember(e => e.UserStatus, e => e.MapFrom(w => w.UserStatus)); config.CreateMap<Message, MessageDto>(); config.CreateMap<UserStatus, UserStatusDto>(); config.CreateMap<UserWorkTime, UserWorkTimeDto>(); }).CreateMapper(); } } }
using System; namespace MultTable { class Program { static void Main(string[] args) { int[,] multArray = new int[10, 10]; for (int row = 0; row < 10; row++) { for (int col = 0; col < 10; col++) { multArray[row, col] = (row + 1) * (col + 1); } } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { Console.Write(multArray[i, j] + "\t"); } Console.WriteLine(); } Console.ReadLine(); } } }
using System; namespace SFA.DAS.ProviderCommitments.Web.Extensions { public static class DateTimeExtensions { public static DateTime? GetFirstDayOfMonth(this DateTime? dateValue) { if (!dateValue.HasValue) return null; return new DateTime(dateValue.Value.Year, dateValue.Value.Month, 1).Date; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TimeSheet { class TestTimeSheet { static public void testOfTimeSheet() { var win = App.Current.MainWindow as MainWindow; var ts = win.m_animator.m_timesheet; ts.reset(); ts.addTimeLine("abc"); ts.addTimeLine("cde"); ts.addTimeLine("cdeasdfasfd"); ts.addTimeLine("asdfasdfasdfasfd"); } } }
 namespace Mim.V3109 { public enum SchemaNames { COCT_MT050012UK04, MCAI_MT040101UK03, MCCI_IN010000UK13, MCCI_MT010101UK12, MCCI_MT020101UK12, POII_IN040101UK01, POII_IN050101UK01, POII_MT040101UK01, PORX_IN020101UK05, PORX_IN020102UK05, PORX_IN030101UK05, PORX_IN050101UK05, PORX_IN060102UK05, PORX_IN070101UK05, PORX_IN070103UK05, PORX_IN080101UK05, PORX_IN090101UK05, PORX_IN090102UK05, PORX_IN100101UK05, PORX_IN110101UK05, PORX_IN132004UK05, PORX_IN150101UK05, PORX_IN170101UK05, PORX_IN180101UK05, PORX_IN180102UK05, PORX_IN200101UK05, PORX_IN220102UK05, PORX_IN240101UK05, PORX_IN250101UK05, PORX_IN260101UK05, PORX_IN270101UK05, PORX_IN290101UK05, PORX_IN300102UK05, PORX_IN310101UK05, PORX_IN320101UK05, PORX_IN330101UK05, PORX_IN340101UK05, PORX_IN340102UK05, PORX_IN370101UK05, PORX_IN380101UK05, PORX_IN390101UK05, PORX_IN400101UK05, PORX_IN410101UK05, PORX_IN420101UK05, PORX_IN430101UK05, PORX_IN440101UK05, PORX_IN450101UK05, PORX_IN460101UK05, PORX_IN470101UK05, PORX_IN480101UK05, PORX_MT014001UK06, PORX_MT014002UK05, PORX_MT024001UK05, PORX_MT024003UK06, PORX_MT024201UK05, PORX_MT114001UK06, PORX_MT114002UK06, PORX_MT114003UK06, PORX_MT121001UK05, PORX_MT121002UK05, PORX_MT121201UK06, PORX_MT121301UK05, PORX_MT121302UK05, PORX_MT122002UK06, PORX_MT132004UK06, PORX_MT132204UK05, PORX_MT135001UK06, PORX_MT135201UK06, PORX_MT142001UK06, PORX_MT142002UK06, PORX_MT142003UK06, PORX_MT142004UK06, PORX_MT142005UK06, PORX_MT142006UK06, PORX_MT142201UK05, PORX_MT142202UK05, PRPA_IN010000UK07, PRPA_IN020000UK06, PRPA_IN030000UK08, PRPA_IN040000UK15, PRPA_IN060000UK14, PRPA_IN100000UK14, PRPA_IN110000UK15, PRPA_IN120000UK14, PRPA_IN150000UK14, PRPA_MT010101UK04, PRPA_MT020101UK01, PRPA_MT030101UK05, PRPA_MT040101UK13, PRPA_MT090101UK13, PRPA_MT100101UK13, PRPA_MT110101UK12, PRPA_MT150101UK12, PRPA_MT160101UK13, PRPA_MT180101UK12, PRPA_MT190101UK12, PRPA_MT230101UK12, PRSC_IN040000UK08, PRSC_IN050000UK06, PRSC_IN060000UK06, PRSC_IN070000UK08, PRSC_IN080000UK07, PRSC_IN090000UK09, PRSC_IN100000UK06, PRSC_IN110000UK08, PRSC_IN130000UK07, PRSC_IN140000UK06, PRSC_IN150000UK06, PRSC_MT040101UK08, PRSC_MT050101UK03, PRSC_MT070101UK05, PRSC_MT080101UK04, PRSC_MT090101UK08, PRSC_MT100101UK02, PRSC_MT110101UK06, PRSC_MT130101UK03, PRSC_MT140101UK02, queryResponseEvent, queryResponseEventList, queryResponsePatient, queryResponseStatement, queryResponseSummary, QUPA_IN010000UK13, QUPA_IN020000UK14, QUPA_IN030000UK14, QUPA_IN040000UK14, QUPA_IN050000UK15, QUPA_IN060000UK13, QUPA_IN070000UK15, QUPA_MT010101UK13, QUPA_MT020101UK14, QUPA_MT030101UK14, QUPA_MT040101UK13, QUPC_IN010000UK15, QUPC_IN020000UK14, QUPC_IN030000UK14, QUPC_IN040000UK14, QUPC_IN060000UK15, QUPC_IN070000UK15, QUPC_IN100000UK05, QUPC_IN110000UK04, QUPC_IN120000UK05, QUPC_IN140000UK05, QUPC_IN150000UK05, QUPC_IN160000UK05, QUPC_IN180000UK03, QUPC_IN190000UK03, QUPC_IN200000UK03, QUPC_IN210000UK03, QUPC_MT010101UK15, QUPC_MT020101UK14, QUPC_MT100101UK06, QUPC_MT110101UK05, QUPC_MT120101UK05, QUPC_MT130101UK03, QUPC_MT140101UK03, QUQI_IN010000UK14, QUQI_MT030101UK03, RCCT_MT120101UK01, RCMR_IN010000UK04, RCMR_IN020000UK04, RCMR_IN030000UK05, RCMR_MT010101UK02, RCMR_MT020101UK03, RCMR_MT030101UK03, REPC_IN010000UK15, REPC_IN020000UK13, REPC_IN040000UK15, REPC_IN050000UK13, REPC_IN410000UK07, REPC_IN420000UK07, REPC_IN430000UK05, REPC_IN440000UK05, REPC_IN450000UK02, REPC_IN460000UK02, REPC_IN470000UK02, REPC_IN480000UK02, REPC_MT010101UK15, REPC_MT020101UK11, REPC_MT040101UK14, REPC_MT050101UK11, REPC_MT070101UK13, REPC_MT080101UK13, REPC_MT090101UK15, REPC_MT100101UK15, REPC_MT400101UK07, REPC_MT410101UK07, UKCI_MT010101UK02, UKCT_MT120101UK02, UKCT_MT120101UK03, UKCT_MT120101UK04, UKCT_MT120201UK02, UKCT_MT120201UK03, UKCT_MT120301UK02, UKCT_MT120401UK02, UKCT_MT120401UK03, UKCT_MT120501UK02, UKCT_MT120501UK03, UKCT_MT120601UK02, UKCT_MT120701UK02, UKCT_MT120801UK01, UKCT_MT120901UK01, UKCT_MT121001UK01, UKCT_MT130101UK03, UKCT_MT130201UK02, UKCT_MT130301UK03, UKCT_MT130401UK03, UKCT_MT130501UK03, UKCT_MT130601UK03, UKCT_MT130701UK03, UKCT_MT130801UK03, UKCT_MT130901UK03, UKCT_MT131001UK03, UKCT_MT140101UK01, UKCT_MT140201UK01, UKCT_MT140301UK01, UKCT_MT140401UK01, UKCT_MT140501UK01, UKCT_MT140601UK01, UKCT_MT140701UK01, UKCT_MT140801UK01, UKCT_MT140901UK01, UKCT_MT141001UK01 } }
using System; using System.Linq; using MyLoadTest.LoadRunnerSvnAddin.Gui; namespace MyLoadTest.LoadRunnerSvnAddin.Commands { public class AddCommand : SubversionCommand { protected override void Run(string fileName) { SvnGuiWrapper.Add(fileName, WatchProjects().Callback); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using needle.EditorPatching; using Unity.Profiling; using UnityEditor; using UnityEngine; namespace Needle.Demystify { public static class UnityDemystify { [InitializeOnLoadMethod] [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)] private static async void Init() { var settings = DemystifySettings.instance; var projectSettings = DemystifyProjectSettings.instance; if (projectSettings.FirstInstall) { async void InstalledLog() { await Task.Delay(100); Enable(true); projectSettings.FirstInstall = false; projectSettings.Save(); Debug.Log("Thanks for installing Demystify. You can find Settings under Edit/Preferences Needle/Demystify"); } InstalledLog(); } if (settings.CurrentTheme != null) { settings.CurrentTheme.EnsureEntries(); settings.CurrentTheme.SetActive(); } while (!PatchManager.IsInitialized) await Task.Delay(1); Enable(false); if (!Patches().All(PatchManager.IsPersistentEnabled) && Patches().Any(PatchManager.IsPersistentEnabled)) { Debug.LogWarning("Not all Demystify patches are enabled. Go to " + DemystifySettingsProvider.SettingsPath + " to enable or disable Demystify.\n" + "Patches:\n" + string.Join("\n", Patches().Select(p => p + ": " + (PatchManager.IsPersistentEnabled(p) ? "enabled" : "<b>disabled</b>"))) + "\n" ); } } internal static IEnumerable<string> Patches() { yield return typeof(Patch_Exception).FullName; yield return typeof(Patch_StacktraceUtility).FullName; yield return typeof(Patch_Console).FullName; yield return typeof(Patch_EditorGUI).FullName; yield return typeof(Patch_AutomaticLogMessage).FullName; var settings = DemystifySettings.instance; if (settings.ShowFileName) { yield return "Needle.Demystify.Patch_ConsoleWindowListView"; yield return "Needle.Demystify.Patch_ConsoleWindowMenuItem"; } } public static void Enable(bool force = false) { foreach (var p in Patches()) { if(force || !PatchManager.HasPersistentSetting(p)) PatchManager.EnablePatch(p); } } public static void Disable() { foreach (var p in Patches()) PatchManager.DisablePatch(p, false); } private static readonly StringBuilder builder = new StringBuilder(); public static void Apply(ref string stacktrace) { try { using (new ProfilerMarker("Demystify.Apply").Auto()) { string[] lines = null; using(new ProfilerMarker("Split Lines").Auto()) lines = stacktrace.Split('\n'); var settings = DemystifySettings.instance; var foundPrefix = false; foreach (var t in lines) { var line = t; using (new ProfilerMarker("Remove Markers").Auto()) { if (StacktraceMarkerUtil.IsPrefix(line)) { StacktraceMarkerUtil.RemoveMarkers(ref line); if(!string.IsNullOrEmpty(settings.Separator)) builder.AppendLine(settings.Separator); foundPrefix = true; } } if (foundPrefix && settings.UseSyntaxHighlighting) SyntaxHighlighting.AddSyntaxHighlighting(ref line); var l = line.Trim(); if (!string.IsNullOrEmpty(l)) { if (!l.EndsWith("\n")) builder.AppendLine(l); else builder.Append(l); } } var res = builder.ToString(); if (!string.IsNullOrWhiteSpace(res)) { stacktrace = res; } builder.Clear(); } } catch // (Exception e) { // ignore } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Target : MonoBehaviour { //object health public float maxHealth = 5f; public float health; void Start() { health = maxHealth; } //When damage is taken, decrease health public bool TakeDamage(float amount) { health -= amount; if (health <= 0f) { return true; //Die(); } return false; } //Die void Die() { gameObject.SetActive(false); } }
using Database; using Microsoft.AspNetCore.Components; using Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FitnessTrack.Pages { public partial class MainTracker : ComponentBase { [Inject] DataReader DataReader { get; set; } private int repetitionCount = 0; private int setCount = 0; private bool disableCustomRepitionCount = true; private bool disableCustomSetCount = true; public List<Exercise> Exercises = new List<Exercise>(); private void EnableCustomRepetitionCount(int repCount) { this.repetitionCount = repCount; disableCustomRepitionCount = false; } private void DisableCustomRepetitionCount(int repCount) { this.repetitionCount = repCount; disableCustomRepitionCount = true; } private void EnableCustomSetCount(int setCount) { this.setCount = setCount; this.disableCustomSetCount = false; this.AddSetsToExercise(); } private void DisableCustomSetCount(int setCount) { this.setCount = setCount; this.disableCustomSetCount = true; this.AddSetsToExercise(); } private void AddSetsToExercise() { foreach (var exercise in Exercises) { exercise.SetInformation.Clear(); for (int i = 0; i < setCount; i++) { exercise.SetInformation.Add(new SetInformation()); } } } private void DecrementRepCount(SetInformation setInformation) { setInformation.RepCount = setInformation.RepCount == 0 ? this.repetitionCount : setInformation.RepCount - 1; } protected override async Task OnInitializedAsync() { this.Exercises = (await DataReader.GetExercises()).ToList(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PrefabReplacer : MonoBehaviour { [SerializeField] private List<GameObject> prefabs = new List<GameObject> (); public enum View { List, Grid, Details } public View view { get; set; } = View.Details; public List<GameObject> Prefabs { get => prefabs; set => prefabs = value; } }
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using SQLite.CodeFirst; using Taggart.Data.Models; namespace Taggart.Data { public class TrackLibraryContext : DbContext { public TrackLibraryContext() : base("TrackLibraryContext") { } public TrackLibraryContext(string nameOrConnectionString) : base(nameOrConnectionString) { } public TrackLibraryContext(DbConnection connection, bool contextsOwnsConnection) : base(connection, contextsOwnsConnection) { } public DbSet<Library> Libraries { get; set; } public DbSet<Track> Tracks { get; set; } public DbSet<Playlist> PlayLists { get; set; } public DbSet<TrackMetaData> MetaData { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); var sqliteConnectionInitializer = new SqliteDropCreateDatabaseWhenModelChanges<TrackLibraryContext>(modelBuilder); Database.SetInitializer(sqliteConnectionInitializer); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Configurations.Add(new LibraryConfiguration()); modelBuilder.Configurations.Add(new TrackConfiguration()); modelBuilder.Configurations.Add(new PlaylistConfiguration()); modelBuilder.Configurations.Add(new TrackMetaDataConfiguration()); modelBuilder.Configurations.Add(new PlaylistTrackConfiguration()); modelBuilder.Configurations.Add(new CuePointConfiguration()); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using System.Threading; namespace Aquamonix.Mobile.Lib.Domain { public interface IDetailsApiRequest { RequestResponseHeader Header { get; set; } CancellationToken CancellationToken { get; set; } } public abstract class ApiRequestForDetail<T> : ApiRequestBase { [DataMember(Name = PropertyNames.RequestResponseBody, Order = 2)] public T Body { get; set; } public ApiRequestForDetail(string type, string sessionId = null) { this.Header = new RequestResponseHeader(type, ChannelIdGenerator.GetNext(), sessionId); } private static class ChannelIdGenerator { private static long _channelId =37; public static long GetNext() { return System.Threading.Interlocked.Increment(ref _channelId); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ModeDialog : BaseDialog { }
using JetBrains.Annotations; using SpeedSlidingTrainer.Core.Model.State; namespace SpeedSlidingTrainer.Desktop.BoardFormatting { public interface IBoardFormatter { /// <exception cref="ArgumentNullException">If <see cref="boardState"/> is <c>null</c>.</exception> [NotNull] string ToString([NotNull] BoardStateBase boardState); /// <exception cref="ArgumentNullException">If <see cref="boardDescription"/> is <c>null</c>.</exception> /// <exception cref="InvalidBoardDescriptionException">If the format of <see cref="boardDescription"/> is invalid and couldn't be parsed.</exception> [NotNull] BoardDescription ParseBoardDescription([NotNull] string boardDescription); } }
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.Data.OleDb; namespace WindowsFormsApp1 { public partial class Reg : Form { private OleDbConnection con = new OleDbConnection(); public Reg() { con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\bharg\Desktop\test.accdb;Persist Security Info=False;"; InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { try { con.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = con; if (textBox3.Text == textBox4.Text && textBox1.Text != null && textBox2.Text != null && textBox3.Text != null) { cmd.CommandText = "insert into Login (Name,Pass,Num) values( '" + textBox1.Text + "','" + textBox4.Text + "'," + textBox2.Text + " ) "; cmd.ExecuteNonQuery(); con.Close(); MessageBox.Show("reg thai gyu"); Form1 f = new Form1(); this.Hide(); f.ShowDialog(); this.Close(); } else { MessageBox.Show("pass was not same"); } con.Close(); } catch (Exception ef) { MessageBox.Show(" " + ef); } } private void Reg_Load(object sender, EventArgs e) { } } }
using System; using Newtonsoft.Json; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.ComponentModel; using System.Collections.Specialized; using SQLite; namespace iPadPos { public class Invoice : BaseModel { int localId; [PrimaryKey, AutoIncrement] public int LocalId { get { return localId; } set { localId = value; if (Items != null) Items.ForEach (x => x.LocalParentId = LocalId); } } public bool CreditCardProccessed { get; set; } public Invoice () { customer = new Customer (); Payments = new ObservableCollection<Payment> (); Items = new ObservableCollection<InvoiceLine> (); RegisterId = Settings.Shared.RegisterId.ToString(); } public int RecordId { get; set; } //[JsonProperty ("InvoiceID")] public string Id { get; set; } public string CustomerId { get; set; } Customer customer; [SQLite.Ignore] public Customer Customer { get { return customer; } set { ProcPropertyChanged (ref customer, value); CustomerId = customer == null ? "" : customer.CustomerId; // if (Items != null && Items.Count >= 0) // Save (); } } public string CustomerName { get; set; } [JsonProperty ("InvDate")] public DateTime Date { get; set; } public string RegisterId { get; set; } ObservableCollection<Payment> payments; [SQLite.Ignore] public ObservableCollection<Payment> Payments { get { return payments; } set { unbindAllPayments (); payments = value; payments.CollectionChanged += HandlePaymentsCollectionChanged; bindAllPayments (); } } void HandlePaymentsCollectionChanged (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { UpdateTotals (); if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) e.OldItems.Cast<Payment> ().ToList ().ForEach (x => x.PropertyChanged -= HandlePropertyChanged); else if (e.Action == NotifyCollectionChangedAction.Add) { e.NewItems.Cast<Payment> ().ToList ().ForEach (x => x.PropertyChanged += HandlePropertyChanged); } } void bindAllPayments () { if (Payments == null) return; foreach (var item in Payments.OfType<INotifyPropertyChanged>().ToList()) { item.PropertyChanged += HandlePropertyChanged; } } void unbindAllPayments () { if (Payments == null) return; payments.CollectionChanged -= HandlePaymentsCollectionChanged; foreach (var item in Payments.OfType<INotifyPropertyChanged>().ToList()) { item.PropertyChanged -= HandlePropertyChanged; } } void HandlePropertyChanged (object sender, PropertyChangedEventArgs e) { if (sender is InvoiceLine) Database.Main.Update (sender); switch (e.PropertyName) { case "FinalPrice": case "Amount": case "Selected": UpdateTotals (); return; } } /// <summary> /// The items. /// </summary> ObservableCollection<InvoiceLine> items; [JsonProperty ("Lines"), SQLite.Ignore] public ObservableCollection<InvoiceLine> Items { get { return items; } set { unbindAllItems (); items = value; UpdateTotals (); Items.CollectionChanged += HandleItemsCollectionChanged; bindAllItems (); } } ChargeDetails chargeDetail; [SQLite.Ignore] public ChargeDetails ChargeDetail { get { return chargeDetail; } set { chargeDetail = value; if (value != null) value.LocalInvoiceId = LocalId; } } public void AddItem (Item item) { var i = new InvoiceLine (item); i.LocalParentId = LocalId; i.PropertyChanged += HandlePropertyChanged; Items.Add (i); Database.Main.Insert (i); } void HandleItemsCollectionChanged (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { UpdateTotals (); if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) { e.OldItems.Cast<InvoiceLine> ().ToList ().ForEach (x => { x.PropertyChanged -= HandlePropertyChanged; if (x is InvoiceLine) Database.Main.Delete (x); }); } } void bindAllItems () { if (Items == null) return; foreach (var item in Items.OfType<INotifyPropertyChanged>().ToList()) { item.PropertyChanged += HandlePropertyChanged; } } void unbindAllItems () { if (Items == null) return; Items.CollectionChanged -= HandleItemsCollectionChanged; foreach (var item in Items.OfType<INotifyPropertyChanged>().ToList()) { item.PropertyChanged -= HandlePropertyChanged; } } double discountAmount; public double DiscountAmount { get { return discountAmount; } set { if (ProcPropertyChanged (ref discountAmount, Math.Round (value, 2))) ProcPropertyChanged ("DiscountString"); } } public double TaxAmount { get; set; } double subTotal; public double SubTotal { get { return subTotal; } set { ProcPropertyChanged (ref subTotal, Math.Round (value, 2)); } } double total; public double Total { get { return total; } set { if (ProcPropertyChanged (ref total, Math.Round (value, 2))) ProcPropertyChanged ("TotalString"); } } public string TotalString { get{ return Total.ToString ("C"); } } public string ItemsSubtotalString { get{ return ItemsSubtotal.ToString ("C"); } } public string DiscountString { get { return (DiscountAmount * -1).ToString ("C"); } } public double TotalDiscount { get{ return discountAmount + couponDiscount; } } public string TotalDiscountString { get { return TotalDiscount.ToString ("C"); } } double couponDiscount = 0; [JsonIgnore,Ignore] public List<InvoiceLine> Coupons { get { return Items.Where (x => x.ItemType == ItemType.Coupon).ToList (); } } void updateCoupons () { Coupons.Where (x => x.DiscountPercent > 0 && x.CouponIsValid).ForEach (x => { x.Price = (x.CouponSelectedOnly ? selectedItemsSubtotal : SubTotal) * x.DiscountPercent * -1f; }); couponDiscount = Coupons.Sum (x => x.Price); ProcPropertyChanged ("TotalDiscountString"); } double itemSubtotal; public double ItemsSubtotal { get{ return itemSubtotal; } set { if (ProcPropertyChanged (ref itemSubtotal, Math.Round (value, 2))) ProcPropertyChanged ("ItemsSubtotalString"); } } double selectedItemsSubtotal = 0; void UpdateTotals () { ItemsSubtotal = Math.Round (Items.Where (x => x.ItemType != ItemType.Coupon).Sum (x => x.SubTotal), 2); selectedItemsSubtotal = Math.Round (Items.Where (x => x.ItemType != ItemType.Coupon && x.Selected).Sum (x => x.FinalPrice), 2); //First get the total amount for coupon calculation SubTotal = Math.Round (Items.Where(x=> x.ItemType != ItemType.Coupon).Sum (x => x.FinalPrice), 2); updateCoupons (); //Update with the coupon prices SubTotal = Math.Round (Items.Sum (x => x.FinalPrice), 2); Total = SubTotal - DiscountAmount; ProcPropertyChanged ("DiscountString"); ProcPropertyChanged ("Discount"); AppliedPayment = Math.Round (Payments.Sum (x => x.Amount), 2); Remaining = Math.Round (AppliedPayment >= Total && Total > 0 ? 0 : Total - AppliedPayment, 2); if (CashPayment != null && CashPayment.Amount < 0) Change = Math.Abs (CashPayment.Amount); else Change = Math.Round (AppliedPayment <= Total ? 0 : AppliedPayment - Total, 2); if (Items.Count > 0) Save (); } double appliedPayment; public double AppliedPayment { get { return appliedPayment; } set { if (ProcPropertyChanged (ref appliedPayment, Math.Round (value, 2))) ProcPropertyChanged ("AppliedPaymentString"); } } double remaining; public double Remaining { get { return remaining; } set { if (ProcPropertyChanged (ref remaining, Math.Round (value, 2))) ProcPropertyChanged ("RemainingString"); } } double change; public double Change { get { return change; } set { if (ProcPropertyChanged (ref change, Math.Round (value, 2))) ProcPropertyChanged ("ChangeString"); if (CashPayment != null) CashPayment.Change = value; } } public string SalesPersonId { get; set; } public string AppliedPaymentString { get{ return AppliedPayment.ToString ("C"); } } public string ChangeString { get{ return Change.ToString ("C"); } } public string RemainingString { get{ return Remaining.ToString ("C"); } } [Newtonsoft.Json.JsonIgnore] public Payment CashPayment { get { return Payments.Where (x => x.PaymentType.Id == "Cash").FirstOrDefault (); } } [Newtonsoft.Json.JsonIgnore] public Payment OnAccountPayment { get { return Payments.Where (x => x.PaymentType.Id == "Acct").FirstOrDefault (); } } [Newtonsoft.Json.JsonIgnore] public Payment CardPayment { get { return Payments.Where (x => x.PaymentType.Id == "Visa").FirstOrDefault (); } } public Tuple<bool,string> IsReadyForPayment () { if (Customer == null || string.IsNullOrEmpty (Customer.CustomerId)) return new Tuple<bool, string> (false, "Invoice requires a customer"); if (!HasItems ()) return new Tuple<bool,string> (false, "There are no items on this invoice"); return new Tuple<bool, string> (true, "Ready to go"); } public bool HasItems () { return items.Any (); } public Tuple<bool,string> Validate () { var result = IsReadyForPayment (); if (!result.Item1) return result; if (remaining != 0) return new Tuple<bool,string> (false, "There is still a remaining balance"); return new Tuple<bool, string> (true, "Ready to go"); } public void PaymentSelected (Payment payment) { if (payment.PaymentType.Id == "Acct") { payment.Amount = Math.Min (Remaining, Customer.OnAccount); return; } payment.Amount = Remaining; } bool hasSaved = false; public void Save () { if (LocalId == 0) Database.Main.Insert (this); else Database.Main.Update (this); Settings.Shared.CurrentInvoice = LocalId; if (hasSaved) return; Items.ForEach (x =>{ x.LocalParentId = localId; if(x.LocalId == 0) Database.Main.Insert(x); else Database.Main.Update(x); }); hasSaved = true; } public void Save (bool force) { if (force) hasSaved = false; UpdateTotals (); } public void DeleteLocal () { Items.ForEach (x => Database.Main.Delete (x)); Database.Main.Delete (this); Settings.Shared.CurrentInvoice = 0; } public static Invoice FromLocalId (int id) { var invoice = Database.Main.Table<Invoice> ().Where (x => x.LocalId == id).FirstOrDefault () ?? new Invoice (); if (invoice.LocalId != 0) { var items = Database.Main.Table<InvoiceLine> ().Where (x => x.LocalParentId == id).ToList (); invoice.Items = new ObservableCollection<InvoiceLine> (items); } return invoice; } } }
// Copyright (C) 2008 Jesse Jones // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using NUnit.Framework; using MObjc; using System; using System.Runtime.InteropServices; [Register] public partial class NSDocument : NSObject { public NSDocument(IntPtr instance) : base(instance) { } } [Register] public partial class NSAffineTransform : NSObject { public NSAffineTransform(IntPtr instance) : base(instance) { } } // Make sure we can use AppKit and Foundation without any magic mcocoa goo. [TestFixture] public class RegistrationTests { [TestFixtureSetUp] public void Init() { Registrar.CanInit = true; m_pool = new NSObject(NSObject.AllocAndInitInstance("NSAutoreleasePool")); } [TestFixtureTearDown] public void DeInit() { if (m_pool != null) { m_pool.release(); m_pool = null; } } [Test] public void AppKit() { new Class("NSDocument").Call("alloc"); } [Test] public void Foundation() { new Class("NSAffineTransform").Call("alloc"); } private NSObject m_pool; }
using UnityEditor; using UnityAtoms.Editor; using UnityAtoms.SceneMgmt; namespace UnityAtoms.SceneMgmt.Editor { /// <summary> /// Variable Inspector of type `SceneField`. Inherits from `AtomVariableEditor` /// </summary> [CustomEditor(typeof(SceneFieldVariable))] public sealed class SceneFieldVariableEditor : AtomVariableEditor<SceneField, SceneFieldPair> { } }
using System; using System.Collections.Generic; namespace PizzeriaApi.Models { public partial class Administrator { public int IdAdmin { get; set; } public string Imie { get; set; } public string Nazwisko { get; set; } public string Login { get; set; } public string Haslo { get; set; } public string AdresEmail { get; set; } } }
using System.Threading.Tasks; using CryptoLab.Infrastructure.Commands; using CryptoLab.Infrastructure.Commands.User; using CryptoLab.Infrastructure.IServices; namespace CryptoLab.Infrastructure.Handlers.User { public class RegisterHandler : ICommandHandler<Register> { private readonly IUserService _userService; public RegisterHandler(IUserService userService) { _userService = userService; } public async Task HandlerAsync(Register command) { await _userService.RegisterAsync(command.Email, command.Username, command.Password); } } }
using System; using AutoMapper; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Sfa.Poc.ResultsAndCertification.Dfe.Api.Extensions; using Sfa.Poc.ResultsAndCertification.Dfe.Api.Infrastructure; using Sfa.Poc.ResultsAndCertification.Dfe.Application.Configuration; using Sfa.Poc.ResultsAndCertification.Dfe.Application.Interfaces; using Sfa.Poc.ResultsAndCertification.Dfe.Application.Services; using Sfa.Poc.ResultsAndCertification.Dfe.Data; using Sfa.Poc.ResultsAndCertification.Dfe.Data.Interfaces; using Sfa.Poc.ResultsAndCertification.Dfe.Data.Repositories; using Sfa.Poc.ResultsAndCertification.Dfe.Domain.Models; using Sfa.Poc.ResultsAndCertification.Dfe.Models.Configuration; using Microsoft.OpenApi.Models; using Microsoft.IdentityModel.Logging; namespace Sfa.Poc.ResultsAndCertification.Dfe.Api { public class Startup { protected ResultsAndCertificationConfiguration ResultsAndCertificationConfiguration; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ResultsAndCertificationConfiguration = ConfigurationLoader.Load( Configuration[Constants.EnvironmentNameConfigKey], Configuration[Constants.ConfigurationStorageConnectionStringConfigKey], Configuration[Constants.VersionConfigKey], Configuration[Constants.ServiceNameConfigKey]); services.AddControllers(); services.AddMvc(config => { //config.Filters.Add<ValidateModelAttribute>(); }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .ConfigureApiBehaviorOptions(options => { //options.SuppressConsumesConstraintForFormFileParameters = true; //options.SuppressInferBindingSourcesForParameters = true; //options.SuppressModelStateInvalidFilter = true; //options.SuppressMapClientErrors = true; }); services.Configure<ApiBehaviorOptions>(options => { //options.SuppressModelStateInvalidFilter = true; options.InvalidModelStateResponseFactory = actionContext => { return new BadRequestObjectResult(new BadRequestResponse(actionContext.ModelState)); }; }); RegisterDependencies(services); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ResultsAndCertification WebAPI", Version = "v1" }); //c.OperationFilter<SwaggerFileOperationFilter>(); //c.OperationFilter<FormFileSwaggerFilter>(); //// Set the comments path for the Swagger JSON and UI. //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); //c.IncludeXmlComments(xmlPath); }); IdentityModelEventSource.ShowPII = true; services.AddApiAuthentication(ResultsAndCertificationConfiguration).AddApiAuthorization(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseXContentTypeOptions(); app.UseExceptionHandler("/errors/500"); app.UseStatusCodePagesWithReExecute("/errors/{0}"); //Accept All HTTP Request Methods from all origins //app.UseCors(builder => // builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod()); //app.UseMiddleware(typeof(ExceptionHandlerMiddleware)); app.ConfigureExceptionHandlerMiddleware(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ResultsAndCertification WebApi"); c.RoutePrefix = string.Empty; }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } private void RegisterDependencies(IServiceCollection services) { //Inject AutoMapper services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //Inject DbContext services.AddDbContext<ResultsAndCertificationDbContext>(options => options.UseSqlServer(ResultsAndCertificationConfiguration.SqlConnectionString, builder => builder.UseNetTopologySuite() .EnableRetryOnFailure())); services.AddSingleton(ResultsAndCertificationConfiguration); RegisterRepositories(services); RegisterApplicationServices(services); } private static void RegisterRepositories(IServiceCollection services) { services.AddTransient<IRepository<TqAwardingOrganisation>, GenericRepository<TqAwardingOrganisation>>(); services.AddTransient<IRepository<Provider>, GenericRepository<Provider>>(); services.AddTransient<IRepository<TqProvider>, GenericRepository<TqProvider>>(); services.AddTransient<IRepository<TqRoute>, GenericRepository<TqRoute>>(); services.AddTransient<IRepository<TqPathway>, GenericRepository<TqPathway>>(); services.AddTransient<IRepository<TqSpecialism>, GenericRepository<TqSpecialism>>(); } private static void RegisterApplicationServices(IServiceCollection services) { services.AddTransient<ITqAwardingOrganisationService, TqAwardingOrganisationService>(); services.AddTransient<IProviderService, ProviderService>(); services.AddTransient<ITqProviderService, TqProviderService>(); services.AddTransient<ITqRouteService, TqRouteService>(); services.AddTransient<ITqPathwayService, TqPathwayService>(); services.AddTransient<ITqSpecialismService, TqSpecialismService>(); } } }
using Motherload.Factories; using Motherload.Interfaces; using Newtonsoft.Json; using System.Linq; using System.Collections.Generic; using Motherload.Models; using Motherload.Interfaces.Unity; namespace Motherload.Services { /// <summary> /// Classe que implementa <see cref="IInventory"/> /// </summary> public class Inventory : IInventory { #region Constants /// <summary> /// Constante usada para obter e salvar informações no PlayerPrefs /// </summary> private static readonly string INVENTORY_KEY = "INVENTORY_KEY_PREFS"; /// <summary> /// Constante usada para setar capacidade máxima de itens no inventário /// </summary> private static readonly int INVENTORY_CAPACITY = 15; #endregion #region Services /// <summary> /// Instância de PlayerPrefs /// </summary> private IPlayerPrefs PlayerPrefs; /// <summary> /// Instância de GameService /// </summary> private IGameService GameService; /// <summary> /// Instância de GameUI /// </summary> private IGameUI GameUI; #endregion #region Public Properties /// <summary> /// Implementação de <see cref="IInventory.InventoryItems"/> /// </summary> public List<Item> InventoryItems { get; set; } /// <summary> /// Peso atual dos itens no inventário /// </summary> public float Weight => InventoryItems.Sum(o => o.GetAttributeValue<float>(Attribute.WEIGHT) * o.GetAttributeValue<int>(Attribute.AMOUNT)); public float MaxWeight = 100f; #endregion #region Constructors /// <summary> /// Implementação de <see cref="IInventory.Initialize"/> /// </summary> public void Initialize() { PlayerPrefs = DependencyInjector.Retrieve<IPlayerPrefs>(); GameService = DependencyInjector.Retrieve<IGameService>(); GameUI = DependencyInjector.Retrieve<IGameUI>(); LoadInventory(); } #endregion #region Public Methods /// <summary> /// Implementação de <see cref="IInventory.SaveInventory"/> /// </summary> public void SaveInventory() { PlayerPrefs.SetString(INVENTORY_KEY, JsonConvert.SerializeObject(InventoryItems)); } /// <summary> /// Implementação de <see cref="IInventory.LoadInventory"/> /// </summary> public void LoadInventory() { if (PlayerPrefs.HasKey(INVENTORY_KEY)) InventoryItems = JsonConvert.DeserializeObject<List<Item>>(PlayerPrefs.GetString(INVENTORY_KEY)); else InventoryItems = new List<Item>(); } #endregion #region Public Methods /// <summary> /// Implementação de <see cref="IInventory.Add(int, int)"/> /// </summary> public void Add(int uid, int amount) { var item = GameService.Items.FirstOrDefault(o => o.UniqueID == uid); // TODO: Pensar em uma forma melhor de lidar com esses casos if (item == null) return; if (item.GetAttributeValue<bool>(Attribute.STACKABLE)) { var itemInventory = InventoryItems.FirstOrDefault(o => o.UniqueID == uid); if(itemInventory == null) { item = AddAmount(item, amount); if (item.GetAttributeValue<int>(Attribute.AMOUNT) == 0) return; InventoryItems.Add(item); GameUI.RefreshInventory(); return; } var itemInventoryIndex = InventoryItems.IndexOf(itemInventory); InventoryItems[itemInventoryIndex] = AddAmount(itemInventory, amount); GameUI.RefreshInventory(); return; } if (!CanPick(uid, amount)) return; for (var i = 0; i < amount; i++) { if (!CanPick(uid, 1)) continue; var nonStack = AddAmount(item, 1); if (nonStack.GetAttributeValue<int>(Attribute.AMOUNT) == 0) continue; InventoryItems.Add(nonStack); } GameUI.RefreshInventory(); } /// <summary> /// Adiciona uma quantidade <see cref="amount"/> no item verificando também se é possível carregar eles. /// Se não for possível, ele dropa o item. /// </summary> /// <param name="item">Item usado de referência</param> /// <param name="amount">Quantidade do item a ser adicionada</param> /// <returns></returns> private Item AddAmount(Item item, int amount) { if(!item.HasKey(Attribute.AMOUNT)) item.Attributes.Add(new Attribute() { Key = Attribute.AMOUNT, Value = "0" }); var newWeight = Weight; for (var i = 0; i < amount; i++) { var itemWeight = item.GetAttributeValue<float>(Attribute.WEIGHT); if ((newWeight + itemWeight) > MaxWeight) { DropItem(item.UniqueID, amount - i); break; } var newAmount = item.GetAttributeValue<int>(Attribute.AMOUNT) + 1; item.SetAttributeValue(Attribute.AMOUNT, newAmount.ToString()); newWeight += itemWeight; } return item; } /// <summary> /// Implementação de <see cref="IInventory.Remove(int, int)"/> /// </summary> public void Remove(int uid, int amount) { InventoryItems.ForEach(o => { if (o.UniqueID == uid) { var newAmount = o.GetAttributeValue<int>(Attribute.AMOUNT) - 1; o.SetAttributeValue(Attribute.AMOUNT, newAmount.ToString()); } }); GameUI.RefreshInventory(); } /// <summary> /// Implementação de <see cref="IInventory.CanPick(int, int)"/> /// </summary> public bool CanPick(int uid, int amount) { if (InventoryItems.Count < INVENTORY_CAPACITY) return true; DropItem(uid, amount); return false; } /// <summary> /// Implementação de <see cref="IInventory.DropItem(int, int)"/> /// </summary> public void DropItem(int uid, int amount) { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EBS.Application; using Dapper.DBContext; using EBS.Domain.Service; using EBS.Domain.Entity; using EBS.Domain.ValueObject; using EBS.Application.DTO; using Newtonsoft.Json; using EBS.Application.Facade.Mapping; namespace EBS.Application.Facade { public class AdjustSalePriceFacade:IAdjustSalePriceFacade { IDBContext _db; AdjustSalePriceService _service; ProcessHistoryService _processHistoryService; BillSequenceService _sequenceService; ProductService _productService; public AdjustSalePriceFacade(IDBContext dbContext) { _db = dbContext; _service = new AdjustSalePriceService(this._db); _processHistoryService = new ProcessHistoryService(this._db); _sequenceService = new BillSequenceService(this._db); _productService = new ProductService(this._db); } /// <summary> /// 创建调价单就立即生效 /// </summary> /// <param name="model"></param> public void Create(AdjustSalePriceModel model) { // 创建调价单 var entity = new AdjustSalePrice(); entity = model.MapTo<AdjustSalePrice>(); var items = model.ConvertJsonToItem(); entity.AddItems(items); entity.CreatedBy = model.UpdatedBy; entity.Code = _sequenceService.GenerateNewCode(BillIdentity.AdjustSalePrice); _service.Create(entity); // 修改商品价格 Dictionary<int, decimal> productSalePriceDic = new Dictionary<int, decimal>(); items.ToList().ForEach(n => productSalePriceDic.Add(n.ProductId, n.AdjustPrice)); _productService.UpdateSalePrice(productSalePriceDic); // 修改单据状态 entity.Submit(); _db.SaveChange(); var reason = "创建商品调价单"; entity = _db.Table.Find<AdjustSalePrice>(n => n.Code == entity.Code); _processHistoryService.Track(model.UpdatedBy, model.UpdatedByName, (int)entity.Status, entity.Id, BillIdentity.AdjustSalePrice.ToString(), reason); _db.SaveChange(); } public void Edit(AdjustSalePriceModel model) { var entity = _db.Table.Find<AdjustSalePrice>(model.Id); entity = model.MapTo<AdjustSalePrice>(entity); entity.AddItems(model.ConvertJsonToItem()); entity.UpdatedOn = DateTime.Now; _service.Update(entity); var reason = "修改商品调价单"; _processHistoryService.Track(model.UpdatedBy, model.UpdatedByName, (int)entity.Status, entity.Id, BillIdentity.AdjustSalePrice.ToString(), reason); _db.SaveChange(); } public void Delete(int id, int editBy, string editor, string reason) { var entity = _db.Table.Find<AdjustSalePrice>(id); entity.Cancel(); entity.EditBy(editBy); _db.Update(entity); _processHistoryService.Track(editBy, editor, (int)entity.Status, entity.Id, BillIdentity.AdjustSalePrice.ToString(), reason); _db.SaveChange(); } public void Submit(int id, int editBy, string editor) { var entity = _db.Table.Find<AdjustSalePrice>(id); if (entity == null) { throw new Exception("单据不存在"); } // 根据明细修改商品价格 var items = _db.Table.FindAll<AdjustSalePriceItem>(n => n.AdjustSalePriceId == entity.Id); Dictionary<int, decimal> productSalePriceDic = new Dictionary<int, decimal>(); items.ToList().ForEach(n => productSalePriceDic.Add(n.ProductId, n.AdjustPrice)); _productService.UpdateSalePrice(productSalePriceDic); // 修改单据状态 entity.Submit(); entity.EditBy(editBy); _db.Update(entity); var reason = "商品价格修改生效"; _processHistoryService.Track(editBy, editor, (int)entity.Status, entity.Id, BillIdentity.AdjustSalePrice.ToString(), reason); _db.SaveChange(); } public void Audit(int id, int editBy, string editor) { var entity = _db.Table.Find<AdjustSalePrice>(id); entity.Audit(); entity.EditBy(editBy); _db.Update(entity); var reason = "审核通过"; _processHistoryService.Track(editBy, editor, (int)entity.Status, entity.Id, BillIdentity.AdjustSalePrice.ToString(), reason); _db.SaveChange(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace InstituteOfFineArts.Models { public class StaffSubmitList { public string StaffId { get; set; } public int Point { get; set; } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using static CryptoReaper.Simulation.Player.Direction; namespace CryptoReaper.Simulation { class Player : GameToken { private readonly Crypt _crypt; private Crypt.Coords _cryptCoords; private Direction _facing; private Crypt.Coords _selectCoords; public Player(Crypt crypt, Crypt.Coords cryptCoords) : base("Sprites/Player") { _crypt = crypt; _cryptCoords = cryptCoords; Face(Up); } public Crypt.Coords CryptCoords => _cryptCoords; public Crypt.Coords CryptSelectCoords => _selectCoords; public void Update(GameTime gameTime, InputState input) { if (input.KeyPress(Keys.W, Keys.Up)) { if (IsFacing(Up)) Move(Negative, Static); else Face(Up); } if (input.KeyPress(Keys.A, Keys.Left)) { if (IsFacing(Left)) Move(Static, Negative); else Face(Left); } if (input.KeyPress(Keys.S, Keys.Down)) { if (IsFacing(Down)) Move(Positive, Static); else Face(Down); } if (input.KeyPress(Keys.D, Keys.Right)) { if (IsFacing(Right)) Move(Static, Positive); else Face(Right); } } private bool IsFacing(Direction direction) => _facing == direction; private void Face(Direction direction) { _facing = direction; Select(); } private void Move(Func<int, int> changeRow, Func<int, int> changeCol) { var coords = GetNewCoords(changeRow, changeCol); var feature = _crypt[coords]; if (feature.CanPlaceToken(this)) { _crypt.RemoveGameToken(_cryptCoords); _cryptCoords = coords; _crypt.PlaceGameToken(_cryptCoords, this); Select(); } } private void Select() { _selectCoords = _facing == Up ? GetNewCoords(Negative, Static) : _facing == Right ? GetNewCoords(Static, Positive) : _facing == Down ? GetNewCoords(Positive, Static) : GetNewCoords(Static, Negative); } private Crypt.Coords GetNewCoords(Func<int, int> changeRow, Func<int, int> changeCol) { return new Crypt.Coords(changeRow(_cryptCoords.Row), changeCol(_cryptCoords.Col)); } public enum Direction { Up, Right, Down, Left, } private int Static(int value) => value; private int Negative(int value) => value - 1; private int Positive(int value) => value + 1; } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.Data.Sqlite; using Windows.Storage; namespace Pane { public static class DataAccess { const string DBTEMPLATE = "(\"Key\" INTEGER NOT NULL UNIQUE," + "\"Name\" TEXT NOT NULL UNIQUE," + "\"TotalWeight\" REAL," + "\"FlourWeight\" REAL," + "\"WaterWeight\" REAL," + "\"SaltWeight\" REAL," + "\"OtherDryWeight\" REAL," + "\"OtherWetWeight\" REAL," + "\"Ratio\" REAL," + "\"SaltPercent\" REAL," + "\"OtherDryPercent\" REAL," + "\"TotalDryWeight\" REAL," + "\"TotalWetWeight\" REAL," + "\"Notes\" TEXT," + "PRIMARY KEY(\"key\" AUTOINCREMENT));"; public async static void InitializeDatabase() { await ApplicationData.Current.LocalFolder.CreateFileAsync("BreadRecipes.db", CreationCollisionOption.OpenIfExists); string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "BreadRecipes.db"); using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}")) { db.Open(); String tableCommandOne = "CREATE TABLE IF NOT EXISTS \"recipeTable\"" + DBTEMPLATE; SqliteCommand createTableOne = new SqliteCommand(tableCommandOne, db); createTableOne.ExecuteReader(); String tableCommandTwo = "CREATE TABLE IF NOT EXISTS \"persistenceTable\"" + DBTEMPLATE; SqliteCommand createTableTwo = new SqliteCommand(tableCommandTwo, db); createTableTwo.ExecuteReader(); } } public static Loaf GetPreviousState() { // Called when loaded after Initializing database to load previous state // To keep persistence List<string> lastEntry = GetRecipeListFromDatabase("persistenceTable"); if (lastEntry.Count != 1) { //Nothing to load Loaf newLoaf = new Loaf(); return newLoaf; } else { Loaf previousLoaf = GetRecipeFromDatabaseByName(lastEntry[0], "persistenceTable"); return previousLoaf; } } public static void SaveCurrentState(Loaf saveLoaf = null) { if (saveLoaf != null) { // Saves the current state as the only entry in persistenceTable ClearAllDataFromPersistenceTable(); AddEntryToDatabase(saveLoaf, "persistenceTable"); } else { ClearAllDataFromPersistenceTable(); Loaf currentLoaf = new Loaf(); AddEntryToDatabase(currentLoaf, "persistenceTable"); } } public static void DeleteEntryFromDatabaseByName(Loaf currentLoaf, string table) { // Deletes the database entry of the selected item in ListView if (currentLoaf == null || currentLoaf.RecipeName == "") { //No loaf to delete display error dialogue throw new SqliteException("Error", 1); } else { string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "BreadRecipes.db"); using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}")) { db.Open(); SqliteCommand deleteCommand = new SqliteCommand(); deleteCommand.Connection = db; // Use parameterized query to prevent SQL injection attacks deleteCommand.CommandText = "DELETE FROM " + table + " WHERE Name = @Name;"; deleteCommand.Parameters.AddWithValue("@Name", currentLoaf.RecipeName); deleteCommand.ExecuteReader(); db.Close(); } } } public static void OverwriteData(Loaf currentLoaf, string table) { DeleteEntryFromDatabaseByName(currentLoaf, table); AddEntryToDatabase(currentLoaf, table); } public static void AddEntryToDatabase(Loaf currentLoaf, string table) { string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "BreadRecipes.db"); using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}")) { db.Open(); // Use parameterized query to prevent SQL injection attacks SqliteCommand insertCommand = new SqliteCommand(); insertCommand.Connection = db; insertCommand.CommandText = "INSERT INTO " + table + " VALUES (NULL,@Name,"+ "@TotalWeight, @FlourWeight, @WaterWeight, @SaltWeight, " + "@OtherDryWeight, @OtherWetWeight, @Ratio, @SaltPercent, " + "@OtherDryPercent, @TotalDryWeight, @TotalWetWeight, @Notes);"; insertCommand.Parameters.AddWithValue("@Name",currentLoaf.RecipeName); insertCommand.Parameters.AddWithValue("@TotalWeight", currentLoaf.TotalWeight); insertCommand.Parameters.AddWithValue("@FlourWeight", currentLoaf.FlourWeight); insertCommand.Parameters.AddWithValue("@WaterWeight", currentLoaf.WaterWeight); insertCommand.Parameters.AddWithValue("@SaltWeight", currentLoaf.SaltWeight); insertCommand.Parameters.AddWithValue("@OtherDryWeight", currentLoaf.OtherDryWeight); insertCommand.Parameters.AddWithValue("@OtherWetWeight", currentLoaf.OtherWetWeight); insertCommand.Parameters.AddWithValue("@Ratio", currentLoaf.Ratio); insertCommand.Parameters.AddWithValue("@SaltPercent", currentLoaf.SaltPercent); insertCommand.Parameters.AddWithValue("@OtherDryPercent", currentLoaf.OtherDryPercent); insertCommand.Parameters.AddWithValue("@TotalDryWeight", currentLoaf.TotalDryWeight); insertCommand.Parameters.AddWithValue("@TotalWetWeight", currentLoaf.TotalWetWeight); insertCommand.Parameters.AddWithValue("@Notes", currentLoaf.Notes); try { insertCommand.ExecuteReader(); } //Sqlite ErrorCode 19 - (Name) value is not unique but should be. catch(SqliteException ex) when (ex.SqliteErrorCode == 19) { // Alert overwrite is done in view controller. // So go ahead and overwrite OverwriteData(currentLoaf, table); } db.Close(); } } private static void ClearAllDataFromPersistenceTable() { // Deletes all databaseNames from a specified table in the database // BE CAREFUL! . string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "BreadRecipes.db"); using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}")) { db.Open(); SqliteCommand deleteCommand = new SqliteCommand(); deleteCommand.Connection = db; // Use parameterized query to prevent SQL injection attacks deleteCommand.CommandText = "DELETE FROM persistenceTable;"; deleteCommand.ExecuteReader(); db.Close(); } } public static List<string> GetRecipeListFromDatabase(string table = "recipeTable") { List<String> databaseNames = new List<string>(); string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "BreadRecipes.db"); using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}")) { db.Open(); SqliteCommand selectCommand = new SqliteCommand(); selectCommand.Connection = db; // SQL command get the Name value of all databaseNames in the database selectCommand.CommandText = "SELECT Name from " + table +" ;"; SqliteDataReader query = selectCommand.ExecuteReader(); while (query.Read()) { //Add each Name to the databaseNames list databaseNames.Add(query.GetString(0)); } db.Close(); } return databaseNames; } public static Loaf GetRecipeFromDatabaseByName(string recipeName, string table = "recipeTable") { Loaf currentLoaf = new Loaf(); string dbpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "BreadRecipes.db"); using (SqliteConnection db = new SqliteConnection($"Filename={dbpath}")) { db.Open(); SqliteCommand selectCommand = new SqliteCommand(); selectCommand.Connection = db; // Use parameterized query to prevent SQL injection attacks selectCommand.CommandText = "SELECT * from " + table + " WHERE name = @Name;"; selectCommand.Parameters.AddWithValue("@Name", recipeName); SqliteDataReader query = selectCommand.ExecuteReader(); if (query != null) { while (query.Read()) { currentLoaf.Key = query.GetInt32(0); currentLoaf.RecipeName = query.GetString(1); currentLoaf.TotalWeight = query.GetFloat(2); currentLoaf.FlourWeight = query.GetFloat(3); currentLoaf.WaterWeight = query.GetFloat(4); currentLoaf.SaltWeight = query.GetFloat(5); currentLoaf.OtherDryWeight = query.GetFloat(6); currentLoaf.OtherWetWeight = query.GetFloat(7); currentLoaf.Ratio = query.GetFloat(8); currentLoaf.SaltPercent = query.GetFloat(9); currentLoaf.OtherDryPercent = query.GetFloat(10); currentLoaf.TotalDryWeight = query.GetFloat(11); currentLoaf.TotalWetWeight = query.GetFloat(12); currentLoaf.Notes = query.GetString(13); } } else throw new SqliteException("query = NULL! Could not populate currentLoaf", 1); db.Close(); } return currentLoaf; } } }
using System; using System.ComponentModel; using ApartmentApps.Data; namespace ApartmentApps.Api.Modules { [Persistant] public class MessagingConfig : PropertyModuleConfig { public string SendGridApiToken { get; set; } [DisplayName("Send From Email")] public string SendFromEmail { get; set; } = "noreply@apartmentapps.com"; public bool FullLogging { get; set; } public string Template { get; set; } public string LogoImageUrl { get; set; } } }
using System; using Apv.AV.Services.Data.Models.FC; using Apv.AV.Services.DTO.FC; using Apv.AV.Services.DTO; using System.Collections.Generic; namespace Apv.AV.Services.FC { public interface IApvFCServices { ICollection<AppVersion> getAllAppVersions(); ApvAPIResponse<AppVersion> getAppVersion(string platform); ICollection<CarModelDto> getCarModels(string countryCode, string companyId, string modelClassId, string carModelId); } }
using System; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; //実験用で作ったコントローラだけど、完全にお遊び用 namespace WebAPI_Connection_ReExam.Controllers { public class MikuController : ApiController { [ActionName("get")] public HttpResponseMessage getString(int id) { var jsonString = "愛が足りない!"; var res = Request.CreateResponse(HttpStatusCode.OK); //コード200:通信成功 if((id == 39)||(id == 3939)){ jsonString = "☆ミクさんマジ天使!!!☆"; } //StringBuilderクラスのインスタンス//Content-Typeを指定する res.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); //Content-Typeを指定 return res; } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference Listener of type `DoublePair`. Inherits from `AtomEventReferenceListener&lt;DoublePair, DoublePairEvent, DoublePairEventReference, DoublePairUnityEvent&gt;`. /// </summary> [EditorIcon("atom-icon-orange")] [AddComponentMenu("Unity Atoms/Listeners/DoublePair Event Reference Listener")] public sealed class DoublePairEventReferenceListener : AtomEventReferenceListener< DoublePair, DoublePairEvent, DoublePairEventReference, DoublePairUnityEvent> { } }
using System; using System.Collections.Generic; using System.Text; namespace BenefitDeduction.Employees.FamilyMembers { interface IEmployeeChild: IFamilyMember { } }
using System; using System.Diagnostics; using System.Net.Sockets; using System.Xml; using pjank.BossaAPI.Fixml; namespace pjank.BossaAPI.DemoConsole.Modules { class NolCustomFixml : IDemoModule { public char MenuKey { get { return '4'; } } public string Description { get { return "NolClient usage, custom login and message handling"; } } /// <summary> /// Bardziej zaawansowany przykład użycia "NolClient": zalogowanie dopiero na żądanie, /// bez uruchamiania wątku odbierającego komunikaty asynchroniczne (można go obsłużyć samemu). /// Samodzielne przygotowanie, wysyłka i odbiór przykładowego message'a. /// </summary> public void Execute() { using (var nol = new NolClient(false, false)) { // zalogowanie użytkownika Console.WriteLine("\nPress any key... to log in [Esc - cancel]\n"); if (Console.ReadKey(true).Key == ConsoleKey.Escape) return; nol.Login(); // otwarcie kanału asynchronicznego // (na razie nic tu z niego nie odbieramy, bo do tego przydałby się oddzielny wątek) Console.WriteLine("\nPress any key... to open async socket [Esc - skip]\n"); Socket asyncSocket = null; if (Console.ReadKey(true).Key != ConsoleKey.Escape) asyncSocket = NolClient.GetAsyncSocket(); // wysyłka przykładowego komunikatu // (można skorzystać z gotowych klas zdefiniowanych w pjank.BossaAPI.Fixml, // ale można też spreparować coś zupełnie własnego w oparciu o klasę CustomMsg) Console.WriteLine("\nPress any key... to send a custom message [Esc - cancel]\n"); if (Console.ReadKey(true).Key == ConsoleKey.Escape) return; var tmp = FixmlMsg.DebugOriginalXml.Enabled; try { FixmlMsg.DebugOriginalXml.Enabled = true; // otwarcie nowego połączenia (kanał synchroniczny za każdym razem nowy!) using (var syncSocket = NolClient.GetSyncSocket()) { // przygotowanie komunikatu var request = new UserRequestMsg() { Username = "BOS", Type = UserRequestType.GetStatus, }; // wysyłka komunikatu request.Send(syncSocket); // odbiór odpowiedzi Console.WriteLine("\nPress any key... to read the response\n"); Console.ReadKey(true); var response = new FixmlMsg(syncSocket); Trace.WriteLine("\nResponse XML:\n" + response.Xml.FormattedXml() + "\n"); // dokładniejsza analiza odpowiedzi (w klasie konkretnego rodzaju komunikatu) Console.WriteLine("Press any key... to parse the response message\n"); Console.ReadKey(true); UserResponseMsg parsedResponse = new UserResponseMsg(response); Trace.WriteLine(String.Format("\nResponse parsed:\n Status = {0}, StatusText = '{1}'\n", parsedResponse.Status, parsedResponse.StatusText)); } Console.WriteLine("\nPress any key... to send another custom message [Esc - cancel]\n"); if (Console.ReadKey(true).Key == ConsoleKey.Escape) return; // otwarcie nowego połączenia (kanał synchroniczny za każdym razem nowy!) using (var syncSocket = NolClient.GetSyncSocket()) { // tak można spreparować dowolny komunikat, również taki jeszcze nieistniejący ;-> var request = new CustomMsg("MyCustomRequest"); var xmlElement = request.AddElement("Test"); xmlElement.SetAttribute("attr1", "1"); xmlElement.SetAttribute("attr2", "2"); // wysyłka tak samodzielnie spreparowanego komunikatu request.Send(syncSocket); // odbiór odpowiedzi - tutaj powinniśmy otrzymać błąd... "BizMessageRejectException" // niestety aktualna wersja NOL3 zwraca nieprawidłowy XML, którego nie da się parsować Console.WriteLine("\nPress any key... to read the response\n"); Console.ReadKey(true); var response = new FixmlMsg(syncSocket); } } catch (Exception e) { MyUtil.PrintError(e); } FixmlMsg.DebugOriginalXml.Enabled = tmp; Console.ReadKey(true); if (asyncSocket != null) asyncSocket.Close(); } // tu następuje automatyczne wylogowanie } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KartObjects { /// <summary> /// Страны /// </summary> [Serializable] public class Country:SimpleDbEntity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Страна"; } } /// <summary> /// Код /// </summary> public string Code { get; set; } /// <summary> /// Наименование /// </summary> public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using RWCustom; namespace Rainbow.CreatureAddition { public class WolfPaw : Limb { public WolfPaw(GraphicsModule owner, BodyChunk connection, int num, float rad, float sfFric, float aFric) : base(owner, connection, num, rad, sfFric, aFric, 5f, 0.3f) //7f, 0.5f { this.reachingForObject = false; this.grap = owner as WolfGraphics; this.wolf = this.grap.wolf; } public Wolf wolf; public WolfGraphics grap; public override void Update() { base.Update(); base.ConnectToPoint(this.connection.pos, 20f, false, 0f, this.connection.vel, 0f, 0f); bool flag; if (this.reachingForObject) { base.mode = Limb.Mode.HuntAbsolutePosition; flag = false; this.reachingForObject = false; } else { flag = this.EngageInMovement(); } if (this.limbNumber == 0 && this.wolf.grasps[0] != null && this.wolf.HeavyCarry(this.wolf.grasps[0].grabbed)) { flag = true; } if (flag) { if (this.wolf.grasps[0] != null && this.wolf.HeavyCarry(this.wolf.grasps[0].grabbed)) { base.mode = Limb.Mode.HuntAbsolutePosition; BodyChunk grabbedChunk = this.wolf.grasps[0].grabbedChunk; this.absoluteHuntPos = grabbedChunk.pos + Custom.PerpendicularVector((this.connection.pos - grabbedChunk.pos).normalized) * grabbedChunk.rad * 0.8f * ((this.limbNumber != 0) ? 1f : -1f); this.huntSpeed = 20f; this.quickness = 1f; flag = false; } else if (this.wolf.grasps[this.limbNumber] != null) { base.mode = Limb.Mode.HuntRelativePosition; this.relativeHuntPos.x = -20f + 40f * (float)this.limbNumber; this.relativeHuntPos.y = -12f; /* if (this.wolf.eatCounter < 40) { int num = -1; int num2 = 0; while (num < 0 && num2 < 2) { if (this.wolf.grasps[num2] != null && this.wolf.grasps[num2].grabbed is IPlayerEdible && (this.wolf.grasps[num2].grabbed as IPlayerEdible).Edible) { num = num2; } num2++; } if (num == this.limbNumber) { this.relativeHuntPos *= Custom.LerpMap((float)this.wolf.eatCounter, 40f, 20f, 0.9f, 0.7f); this.relativeHuntPos.y = this.relativeHuntPos.y + Custom.LerpMap((float)this.wolf.eatCounter, 40f, 20f, 2f, 4f); this.relativeHuntPos.x = this.relativeHuntPos.x * Custom.LerpMap((float)this.wolf.eatCounter, 40f, 20f, 1f, 1.2f); } }*/ //this.relativeHuntPos.x = this.relativeHuntPos.x * (1f - Mathf.Sin(this.wolf.switchHandsProcess * 3.14159274f)); if (this.grap.spearDir != 0f && this.wolf.bodyMode == Wolf.BodyModeIndex.Stand) { Vector2 to = Custom.DegToVec(180f + ((this.limbNumber != 0) ? 1f : -1f) * 8f) * 12f; // + (float)this.wolf.input[0].x * 4f to.y += Mathf.Sin((float)this.wolf.animation.animationFrame / 6f * 2f * 3.14159274f) * 2f; to.x -= Mathf.Cos((float)(this.wolf.animation.animationFrame + ((!this.wolf.leftFoot) ? 6 : 0)) / 12f * 2f * 3.14159274f) * 4f; // * (float)this.wolf.input[0].x //to.x += (float)this.wolf.input[0].x * 2f; this.relativeHuntPos = Vector2.Lerp(this.relativeHuntPos, to, Mathf.Abs(this.grap.spearDir)); if (this.wolf.grasps[this.limbNumber].grabbed is Weapon) { (this.wolf.grasps[this.limbNumber].grabbed as Weapon).ChangeOverlap((this.grap.spearDir > -0.4f && this.limbNumber == 0) || (this.grap.spearDir < 0.4f && this.limbNumber == 1)); } } flag = false; if (this.wolf.grasps[this.limbNumber].grabbed is Fly && !(this.wolf.grasps[this.limbNumber].grabbed as Fly).dead) { this.huntSpeed = UnityEngine.Random.value * 5f; this.quickness = UnityEngine.Random.value * 0.3f; this.vel += Custom.DegToVec(UnityEngine.Random.value * 360f) * UnityEngine.Random.value * UnityEngine.Random.value * ((!Custom.DistLess(this.absoluteHuntPos, this.pos, 7f)) ? 1.5f : 4f); this.pos += Custom.DegToVec(UnityEngine.Random.value * 360f) * UnityEngine.Random.value * 4f; this.grap.NudgeDrawPosition(0, Custom.DirVec((this.owner.owner as Creature).mainBodyChunk.pos, this.pos) * 3f * UnityEngine.Random.value); this.grap.head.vel += Custom.DirVec((this.owner.owner as Creature).mainBodyChunk.pos, this.pos) * 2f * UnityEngine.Random.value; } else if ((this.owner.owner as Creature).grasps[this.limbNumber].grabbed is VultureMask) { this.relativeHuntPos *= 1f - ((this.owner.owner as Creature).grasps[this.limbNumber].grabbed as VultureMask).donned; } } } if (flag && base.mode != Limb.Mode.Retracted) { this.retractCounter++; if ((float)this.retractCounter > 5f) { base.mode = Limb.Mode.HuntAbsolutePosition; this.pos = Vector2.Lerp(this.pos, this.owner.owner.bodyChunks[0].pos, Mathf.Clamp(((float)this.retractCounter - 5f) * 0.05f, 0f, 1f)); if (Custom.DistLess(this.pos, this.owner.owner.bodyChunks[0].pos, 2f) && this.reachedSnapPosition) { base.mode = Limb.Mode.Retracted; } this.absoluteHuntPos = this.owner.owner.bodyChunks[0].pos; this.huntSpeed = 1f + (float)this.retractCounter * 0.2f; this.quickness = 1f; } } else { this.retractCounter -= 10; if (this.retractCounter < 0) { this.retractCounter = 0; } } } public bool EngageInMovement() { bool flag = true; Wolf.WolfAnimation.AnimationIndex animation; switch (this.wolf.bodyMode) { case Wolf.BodyModeIndex.Default: if (this.grap.airborneCounter > 180f && !Custom.DistLess(new Vector2(0f, 0f), this.owner.owner.bodyChunks[0].vel, 4f)) { flag = false; this.retractCounter = 0; Vector2 b = Custom.DegToVec(UnityEngine.Random.value * 360f) * 40f * UnityEngine.Random.value; if (this.owner.owner.room.GetTile(this.owner.owner.bodyChunks[0].pos + this.owner.owner.bodyChunks[0].vel * 4f + b).Terrain != Room.Tile.TerrainType.Air) { base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = this.owner.owner.bodyChunks[0].pos + this.owner.owner.bodyChunks[0].vel * 4f + b; this.huntSpeed = 18f; this.quickness = 1f; } else { base.mode = Limb.Mode.HuntRelativePosition; this.relativeHuntPos.x = (Mathf.Abs(this.owner.owner.bodyChunks[0].vel.x * ((this.owner.owner.bodyChunks[0].pos.y <= this.owner.owner.bodyChunks[1].pos.y + 5f) ? 1f : 2.1f)) + 4f) * (-1f + 2f * (float)this.limbNumber); this.relativeHuntPos.y = this.owner.owner.bodyChunks[0].vel.y * ((this.owner.owner.bodyChunks[0].pos.y <= this.owner.owner.bodyChunks[1].pos.y + 5f) ? -0.9f : -3f) + Mathf.Abs(this.owner.owner.bodyChunks[0].vel.x * 0.6f) + 1f; if (this.owner.owner.bodyChunks[0].vel.magnitude > 10f) { this.relativeHuntPos += Custom.DegToVec(UnityEngine.Random.value * 360f) * UnityEngine.Random.value * UnityEngine.Random.value * this.owner.owner.bodyChunks[0].vel.magnitude; } this.huntSpeed = 8f; this.quickness = 0.6f; } } break; case Wolf.BodyModeIndex.Crawl: flag = false; base.mode = Limb.Mode.HuntAbsolutePosition; this.huntSpeed = 12f; this.quickness = 0.7f; if ((this.limbNumber == 0 || (Mathf.Abs(this.grap.hands[0].pos.x - this.owner.owner.bodyChunks[0].pos.x) < 10f && this.grap.hands[0].reachedSnapPosition)) && !Custom.DistLess(this.owner.owner.bodyChunks[0].pos, this.absoluteHuntPos, 29f)) { Vector2 absoluteHuntPos = this.absoluteHuntPos; base.FindGrip(this.owner.owner.room, this.connection.pos + new Vector2((float)this.wolf.flipDirection * 20f, 0f), this.connection.pos + new Vector2((float)this.wolf.flipDirection * 20f, 0f), 100f, new Vector2(this.owner.owner.bodyChunks[0].pos.x + (float)this.wolf.flipDirection * 28f, this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).y - 10f), 2, 1, false); if (this.absoluteHuntPos != absoluteHuntPos) { } } break; case Wolf.BodyModeIndex.CorridorClimb: flag = false; base.mode = Limb.Mode.HuntAbsolutePosition; if (!Custom.DistLess(this.pos, this.connection.pos, 20f)) { Vector2 vector = Custom.DirVec(this.owner.owner.bodyChunks[1].pos, this.owner.owner.bodyChunks[0].pos); Room room = this.owner.owner.room; Vector2 pos = this.connection.pos; Vector2 pos2 = this.connection.pos; float maximumRadiusFromAttachedPos = 100f; Vector2 pos3 = this.connection.pos; Vector2 a = vector; Vector2 vector2 = Vector2.zero;//new Vector2((float)this.wolf.input[0].x, (float)this.wolf.input[0].y); base.FindGrip(room, pos, pos2, maximumRadiusFromAttachedPos, pos3 + (a + vector2.normalized * 1.5f).normalized * 20f + Custom.PerpendicularVector(vector) * (6f - 12f * (float)this.limbNumber), 2, 2, false); } break; case Wolf.BodyModeIndex.WallClimb: flag = false; base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos.x = this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).x + (float)this.wolf.flipDirection * 10f; if (this.limbNumber == 0 == (this.wolf.flipDirection == -1)) { this.absoluteHuntPos.y = this.owner.owner.bodyChunks[0].pos.y - 7f; } else { this.absoluteHuntPos.y = this.owner.owner.bodyChunks[0].pos.y + 3f; } break; case Wolf.BodyModeIndex.ClimbingOnBeam: flag = false; if (this.wolf.animation == null) { base.mode = Limb.Mode.HuntRelativePosition; float num = Mathf.Sin(6.28318548f * this.grap.balanceCounter / 300f); this.relativeHuntPos.x = -20f + 40f * (float)this.limbNumber; this.relativeHuntPos.y = -4f - 6f * num * ((this.limbNumber != 0) ? 1f : -1f); base.FindGrip(this.owner.owner.room, this.connection.pos, this.connection.pos, 100f, this.connection.pos + new Vector2(-10f + 20f * (float)this.limbNumber, (this.limbNumber == 0 != (this.wolf.flipDirection == -1)) ? -5f : 0f), (this.limbNumber != 0) ? -1 : 1, -1, false); if (base.mode == Limb.Mode.HuntAbsolutePosition) { if (this.pos.y > this.owner.owner.bodyChunks[0].pos.y + 5f) { this.grap.head.vel.x += (2f - 4f * (float)this.limbNumber); } if (Mathf.Abs(this.owner.owner.bodyChunks[0].pos.x - this.owner.owner.bodyChunks[1].pos.x) < 10f) { this.grap.disbalanceAmount -= 8f; } } else if (this.grap.disbalanceAmount < 40f) { float num2 = (40f - this.grap.disbalanceAmount) / 40f; this.relativeHuntPos.y *= (1f - num2); this.relativeHuntPos.y -= num2 * 15f; this.relativeHuntPos.x *= (1f - num2); if (num2 >= 1f) { flag = true; } } this.huntSpeed = 5f; this.quickness = 0.2f; break; } switch (this.wolf.animation.idx) { case Wolf.WolfAnimation.AnimationIndex.HangFromBeam: case Wolf.WolfAnimation.AnimationIndex.GetUpOnBeam: base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = new Vector2(this.owner.owner.bodyChunks[0].pos.x, this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).y); this.absoluteHuntPos.y -= 1f; this.absoluteHuntPos.x += ((this.limbNumber != 0) ? 1f : -1f) * (10f + 3f * Mathf.Sin(6.28318548f * (float)this.wolf.animation.animationFrame / 20f)); if (this.owner.owner.room.GetTile(this.absoluteHuntPos).Terrain == Room.Tile.TerrainType.Solid || !this.owner.owner.room.GetTile(this.absoluteHuntPos).horizontalBeam) { this.absoluteHuntPos.x = this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).x + ((this.limbNumber != 0) ? 10f : -10f); } break; case Wolf.WolfAnimation.AnimationIndex.StandOnBeam: case Wolf.WolfAnimation.AnimationIndex.BeamTip: { base.mode = Limb.Mode.HuntRelativePosition; float num = Mathf.Sin(6.28318548f * this.grap.balanceCounter / 300f); this.relativeHuntPos.x = -20f + 40f * (float)this.limbNumber; this.relativeHuntPos.y = -4f - 6f * num * ((this.limbNumber != 0) ? 1f : -1f); base.FindGrip(this.owner.owner.room, this.connection.pos, this.connection.pos, 100f, this.connection.pos + new Vector2(-10f + 20f * (float)this.limbNumber, (this.limbNumber == 0 != (this.wolf.flipDirection == -1)) ? -5f : 0f), (this.limbNumber != 0) ? -1 : 1, -1, false); if (base.mode == Limb.Mode.HuntAbsolutePosition) { if (this.pos.y > this.owner.owner.bodyChunks[0].pos.y + 5f) { this.grap.head.vel.x += (2f - 4f * (float)this.limbNumber); } if (Mathf.Abs(this.owner.owner.bodyChunks[0].pos.x - this.owner.owner.bodyChunks[1].pos.x) < 10f) { this.grap.disbalanceAmount -= 8f; } } else if (this.grap.disbalanceAmount < 40f) { float num2 = (40f - this.grap.disbalanceAmount) / 40f; this.relativeHuntPos.y *= (1f - num2); this.relativeHuntPos.y -= num2 * 15f; this.relativeHuntPos.x = relativeHuntPos.x * (1f - num2); if (num2 >= 1f) { flag = true; } } this.huntSpeed = 5f; this.quickness = 0.2f; break; } case Wolf.WolfAnimation.AnimationIndex.ClimbOnBeam: { float num3 = (float)this.wolf.animation.animationFrame / 20f * 3.14159274f * 2f; if (this.limbNumber == 1 == (this.wolf.flipDirection == 1)) { num3 = Mathf.Sin(num3); } else { num3 = Mathf.Cos(num3); } base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = new Vector2(this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).x, this.owner.owner.bodyChunks[0].pos.y); this.absoluteHuntPos.y += (((this.limbNumber == 1 != (this.wolf.flipDirection == 1)) ? 3f : -3f) + 6f * num3); this.absoluteHuntPos.x += (float)((this.limbNumber == 1 != (this.wolf.flipDirection == 1)) ? this.wolf.flipDirection : (-(float)this.wolf.flipDirection)); this.retractCounter = 40; break; } case Wolf.WolfAnimation.AnimationIndex.HangUnderVerticalBeam: base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = this.owner.owner.room.MiddleOfTile(this.owner.owner.firstChunk.pos) + new Vector2((this.limbNumber != 0) ? 0.5f : -0.5f, (this.limbNumber != 0) ? 25f : 20f); this.huntSpeed = 10f; this.quickness = 1f; break; } break; case Wolf.BodyModeIndex.Swimming: { flag = false; float num4 = (this.wolf.swimCycle >= 3f) ? (1f - (this.wolf.swimCycle - 3f)) : (this.wolf.swimCycle / 3f); if (this.wolf.animation != null && this.wolf.animation.idx != Wolf.WolfAnimation.AnimationIndex.SurfaceSwim) { base.mode = Limb.Mode.HuntRelativePosition; float num5 = Mathf.Pow(1f - Mathf.InverseLerp(0.5f, 1f, num4), 1.5f); this.relativeHuntPos = Custom.DegToVec((20f + num5 * 140f) * ((this.limbNumber != 0) ? 1f : -1f)) * 20f; if (this.wolf.swimCycle < 3f) { this.relativeHuntPos.x *= 0.5f; } } else { base.mode = Limb.Mode.HuntAbsolutePosition; //this.absoluteHuntPos.x = this.owner.owner.bodyChunks[0].pos.x + Mathf.Lerp(((this.limbNumber != 0) ? 1f : -1f) * 30f, (float)this.wolf.input[0].x * 10f * -Mathf.Sin(num4 * 2f * 3.14159274f), 0.5f); this.absoluteHuntPos.y = this.owner.owner.room.FloatWaterLevel(this.absoluteHuntPos.x) - 7f; //this.absoluteHuntPos += Custom.DegToVec(360f * num4 * ((this.wolf.input[0].x != 0) ? (-(float)this.wolf.input[0].x) : 1f)) * ((this.limbNumber != 0) ? 1f : -1f) * ((this.wolf.input[0].x != 0) ? 10f : 5f); } this.huntSpeed = 5f; this.quickness = 0.5f; break; } case Wolf.BodyModeIndex.ZeroG: flag = false; animation = this.wolf.animation.idx; if (this.wolf.animation != null && animation != Wolf.WolfAnimation.AnimationIndex.ZeroGSwim) { /* if (animation == Wolf.WolfAnimation.AnimationIndex.ZeroGPoleGrab) { float num6 = (float)this.wolf.animation.animationFrame / 20f * 3.14159274f * 2f; bool flag2 = (this.wolf.standing && this.limbNumber == 1 == (this.wolf.zeroGPoleGrabDir.x == 1)) || (!this.wolf.standing && this.limbNumber == 1 == (this.wolf.zeroGPoleGrabDir.x == 1)); if (flag2) { num6 = Mathf.Sin(num6); } else { num6 = Mathf.Cos(num6); } base.mode = Limb.Mode.HuntAbsolutePosition; if (this.wolf.standing) { this.absoluteHuntPos = new Vector2(this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).x, this.owner.owner.bodyChunks[0].pos.y); this.absoluteHuntPos.y = this.absoluteHuntPos.y + (((!flag2) ? 3f : -3f) + 6f * num6) * Mathf.Sign(this.owner.owner.bodyChunks[1].pos.y - this.owner.owner.bodyChunks[0].pos.y); this.absoluteHuntPos.x = this.absoluteHuntPos.x + ((!flag2) ? 1f : -1f) * (float)this.wolf.zeroGPoleGrabDir.x; } else { this.absoluteHuntPos = new Vector2(this.owner.owner.bodyChunks[0].pos.x, this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos).y); this.absoluteHuntPos.x = this.absoluteHuntPos.x + (((!flag2) ? 3f : -3f) + 6f * num6) * Mathf.Sign(this.owner.owner.bodyChunks[1].pos.x - this.owner.owner.bodyChunks[0].pos.x); this.absoluteHuntPos.y = this.absoluteHuntPos.y + ((!flag2) ? 1f : -1f) * (float)this.wolf.zeroGPoleGrabDir.y; } this.retractCounter = 40; }*/ } else { flag = true; if (this.wolf.swimBits[this.limbNumber] != null && Custom.DistLess(this.owner.owner.firstChunk.pos, this.wolf.swimBits[this.limbNumber].pos, 30f)) { flag = false; base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = this.wolf.swimBits[this.limbNumber].pos; } if (flag && this.owner.owner.firstChunk.vel.magnitude < 5f) { base.mode = Limb.Mode.Dangle; base.FindGrip(this.owner.owner.room, this.connection.pos, this.connection.pos, 100f, this.connection.pos + new Vector2(-10f + 20f * (float)this.limbNumber, (this.limbNumber == 0 != (this.wolf.flipDirection == -1)) ? -5f : 0f), (this.limbNumber != 0) ? -1 : 1, -2, false); flag = (base.mode != Limb.Mode.HuntAbsolutePosition); } if (flag && this.owner.owner.firstChunk.vel.magnitude < 6f && Vector2.Distance(this.owner.owner.firstChunk.vel, this.owner.owner.bodyChunks[1].vel) > 2f && this.grap.flail > 0.1f)// && (this.wolf.input[0].x != 0 || this.wolf.input[0].y != 0) { flag = false; float num7 = 0.5f + 0.5f * Mathf.Sin(this.wolf.swimCycle / 4f * 3.14159274f * 2f); base.mode = Limb.Mode.HuntRelativePosition; this.relativeHuntPos = Custom.DegToVec((20f + num7 * 140f) * ((this.limbNumber != 0) ? 1f : -1f)) * 20f * Mathf.InverseLerp(0.1f, 0.3f, this.grap.flail); } if (flag && (this.owner.owner.firstChunk.vel.magnitude < 4f || Vector2.Dot(this.owner.owner.firstChunk.vel.normalized, Custom.DirVec(this.owner.owner.bodyChunks[1].pos, this.owner.owner.firstChunk.pos)) < 0.6f)) { flag = false; float num8 = this.wolf.swimCycle / 4f; float num9 = Mathf.Sin(this.grap.balanceCounter / 300f * 3.14159274f * 2f); num9 *= Mathf.InverseLerp(0f, 50f, this.grap.disbalanceAmount); base.mode = Limb.Mode.HuntRelativePosition; this.relativeHuntPos = new Vector2(((this.limbNumber != 0) ? 1f : -1f) * 17f + 5f * num9, -5f * num9) + Custom.DegToVec(num8 * ((this.limbNumber != 0) ? 1f : -1f) * 360f) * 5f; } } break; } if (this.wolf.animation == null) { return flag; } animation = this.wolf.animation.idx; switch (animation) { case Wolf.WolfAnimation.AnimationIndex.CrawlTurn: case Wolf.WolfAnimation.AnimationIndex.DownOnFours: flag = false; base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = this.connection.pos; this.absoluteHuntPos.x += (-6f + (float)(12 * this.limbNumber) + this.connection.vel.normalized.x * 20f); this.absoluteHuntPos.y += Mathf.Abs(this.connection.vel.normalized.y) * -20f; break; default: /* if (animation == Wolf.AnimationIndex.VineGrab) { if (this.owner.owner.room.climbableVines != null && this.wolf.vinePos != null) { flag = false; float num10 = 20f * ((this.limbNumber != 0) ? 1f : -1f) * Mathf.Sin((float)this.wolf.animation.animationFrame / 30f * 2f * 3.14159274f); num10 /= this.owner.owner.room.climbableVines.TotalLength(this.wolf.vinePos.vine); Vector2 vector3 = this.owner.owner.room.climbableVines.OnVinePos(new ClimbableVinesSystem.VinePosition(this.wolf.vinePos.vine, this.wolf.vinePos.floatPos + num10)); vector3 += Custom.PerpendicularVector(this.owner.owner.room.climbableVines.VineDir(this.wolf.vinePos)) * this.owner.owner.room.climbableVines.VineRad(this.wolf.vinePos) * ((this.limbNumber != 0) ? 1f : -1f); base.mode = Limb.Mode.HuntAbsolutePosition; this.absoluteHuntPos = vector3; } }*/ break; case Wolf.WolfAnimation.AnimationIndex.LedgeGrab: flag = false; this.absoluteHuntPos = this.owner.owner.room.MiddleOfTile(this.owner.owner.bodyChunks[0].pos); if (this.limbNumber == 0 == (this.wolf.flipDirection == -1)) { this.absoluteHuntPos.x += (float)this.wolf.flipDirection * 10f; this.absoluteHuntPos.y -= 10f; } else { this.absoluteHuntPos.x = absoluteHuntPos.x + (float)this.wolf.flipDirection * 15f; this.absoluteHuntPos.y = absoluteHuntPos.y + 10f; } break; } return flag; } public int retractCounter; public bool reachingForObject; } }
using Dapper.Contrib.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IconCreator.Core.Domain.Models { [Table ("Gebruikers")] public class Gebruiker { [Key] public string Code { get; set; } public string Voornaam { get; set; } public string TckNaam { get; set; } public int TaalNr { get; set; } public bool BO { get; set; } public bool GebrLock { get; set; } public string StdPagina { get; set; } public string StdIndeling { get; set; } public string Actief { get; set; } public string Default { get; set; } public double Commissie { get; set; } public bool Lade { get; set; } public string UserGroup { get; set; } public bool Tikklok { get; set; } public string ScreenColor { get; set; } public string ScreenColorFile { get; set; } public bool UpdateFlag { get; set; } public bool WisselBed { get; set; } public bool SuperUser { get; set; } public bool AutoUitklok { get; set; } public bool AutoUitKlokLastTicket { get; set; } public int MeldingId { get; set; } public bool Definitief { get; set; } public string LogOnCode { get; set; } public string INSZ { get; set; } public string BIS { get; set; } public string ManLogOnCode { get; set; } public bool Trainer { get; set; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SpaceBookTests { //[TestClass] //public class HomeControllerTest //{ // [TestMethod] // public void TestIndexView() // { // var controller = new SpaceBook.HomeController(); // var result = controller.Details(2) as ViewResult; // Assert.AreEqual("Details", result.ViewName); // } //} //[TestClass] //public class UnitTest1 //{ // [TestMethod] // public void TestMethod1() // { // } //} }
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class highScoreControls : MonoBehaviour { enum ViewMode { Preview, View }; ViewMode currentViewMode = ViewMode.Preview; [Header("Visualization")] [SerializeField] ScrollRect scrollRect; [SerializeField] Sprite[] spriteCollection; [SerializeField] RectTransform content; [SerializeField] GameObject imageItemPrefab; [Header("Element Size")] [SerializeField] float elementX; [SerializeField] float elementY; [SerializeField] float focusX; [SerializeField] float focusY; int focus = 0; List<LayoutElement> generatedSprites; //Generate all score and text into the highscore menus void Start() { generatedSprites = new List<LayoutElement>(); for (int i = 0; i < spriteCollection.Length; i++) { GameObject currentItem = Instantiate(imageItemPrefab); currentItem.transform.SetParent(content, false); HighScore.Instance.highestScoreText[i] = currentItem.transform.GetChild(0).GetComponent<Text>(); LayoutElement element = currentItem.GetComponent<LayoutElement>(); generatedSprites.Add(element); element.preferredWidth = elementX; element.preferredHeight = elementY; Image currentImage = currentItem.GetComponent<Image>(); currentImage.sprite = spriteCollection[i]; } HighScore.Instance.OnHighScore(); content.sizeDelta = new Vector2(content.rect.width, (elementY + 25) * 10 + 900); NuitrackManager.onNewGesture += NuitrackManager_onNewGesture; } private void OnDestroy() { NuitrackManager.onNewGesture -= NuitrackManager_onNewGesture; } //Swipe Gesture to move up and down private void NuitrackManager_onNewGesture(nuitrack.Gesture gesture) { if (gesture.Type == nuitrack.GestureType.GestureSwipeUp) { scrollRect.velocity = new Vector2(0, 1000); } if (gesture.Type == nuitrack.GestureType.GestureSwipeDown) { scrollRect.velocity = new Vector2(0, -1000); } } //Pin point to the middle of the target of score public void ChangeFocus() { focus = Mathf.FloorToInt(( 1 - scrollRect.verticalScrollbar.value ) * 10); if (focus == 10) focus = 9; for (int i = 0; i < generatedSprites.Count; i++) { if (i == focus) { generatedSprites[i].preferredWidth = focusX * 1.25f; generatedSprites[i].preferredHeight = focusY * 1.25f; } else { generatedSprites[i].preferredWidth = elementX; generatedSprites[i].preferredHeight = elementY; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace consumer { public class Program { static string routingKeyDiv2 = "div2"; static string routingKeyDiv3 = "div3"; static string routingKeyDiv5 = "div5"; static HashSet<ulong> controls; public static void Main(string[] args) { controls = new HashSet<ulong>(); var factory = new ConnectionFactory() { HostName = "localhost", UserName = "rabbitmq", Password = "rabbitmq", VirtualHost = "/" }; using var connection = factory.CreateConnection(); using var channel = connection.CreateModel(); channel.QueueDeclare(queue: "hello", durable: true, exclusive: false, autoDelete: false, arguments: null); //define limit to unack messages channel.BasicQos(0, 5, false); var logs = BuildExchange(connection); var result = BuildExchangeDirect(connection); BuildConsumer(channel, logs, result, $"Consumer A", 10000); BuildConsumer(channel, logs, result, $"Consumer B", 5000); BuildConsumer(channel, logs, result, $"Consumer C", 3000); BuildConsumer(channel, logs, result, $"Consumer D", 1000); BuildConsumer(channel, logs, result, $"Consumer E", 1000); BuildConsumer(channel, logs, result, $"Consumer F", 1000); BuildConsumer(channel, logs, result, $"Consumer G", 1000); CreateHostBuilder(args).Build().Run(); } public static IModel BuildExchangeDirect(IConnection connection) { var channel = connection.CreateModel(); channel.ExchangeDeclare(exchange:"result", type: ExchangeType.Direct); return channel; } public static IModel BuildExchange(IConnection connection) { var channel = connection.CreateModel(); channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout); return channel; } public static void BuildConsumer(IModel channel, IModel logs, IModel result, string consumerName, int sleepSeconds) { var consumer = new EventingBasicConsumer(channel); consumer.Received += async (model, ea) => { var body = ea.Body.ToArray(); Operation operation = JsonSerializer.Deserialize<Operation>(Encoding.UTF8.GetString(body)); try { if (ea.DeliveryTag % 5 == 0 && controls.Add(ea.DeliveryTag)) { throw new ArgumentException(); } System.Console.WriteLine($"{consumerName}.{ea.DeliveryTag} = {operation.Execute()}"); string routingKey = string.Empty; if(operation.Execute() % 5 == 0) routingKey = routingKeyDiv5; else if(operation.Execute() % 3 == 0) routingKey = routingKeyDiv3; else if(operation.Execute() % 2 == 0) routingKey = routingKeyDiv2; else routingKey = "not-match"; var valueCalculated = operation.Execute(); result.BasicPublish( exchange: "result", routingKey: routingKey, basicProperties: null, body: Encoding.UTF8.GetBytes(valueCalculated.ToString())); await Task.Delay(sleepSeconds); //Thread.Sleep(sleepSeconds); channel.BasicAck(ea.DeliveryTag, false); } catch (Exception ex) { body = Encoding.UTF8.GetBytes(string.Concat(operation.Origin,ex.Message)); logs.BasicPublish(exchange: "logs", routingKey: "", basicProperties: null, body); System.Console.WriteLine("Error"); channel.BasicNack(ea.DeliveryTag, false, true); } }; channel.BasicConsume(queue: "hello", autoAck: false, consumer: consumer); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerCamera : MonoBehaviour { // This is a reference to the player movement script. private PlayerMovement player; // This is used to keep track of the last known player position. private Vector3 lastPlayerPos; // This is used for tracking the amount of distance the player needs to move. private float distanceToMoveCamera; // Start is called before the first frame update void Start() { // Set the player movement reference to be that of the player movement script attached to the player. player = FindObjectOfType<PlayerMovement>(); // this value is the position the player was at the first frame. lastPlayerPos = player.transform.position; } // Update is called once per frame void Update() { // distanceToMoveCamera is now equal to the amount the player has moved in a frame. distanceToMoveCamera = player.transform.position.x - lastPlayerPos.x; // make the camera's position that of the current position of the player. transform.position = new Vector3(transform.position.x + distanceToMoveCamera, transform.position.y,transform.position.z); // set this position to be the last known player position. lastPlayerPos = player.transform.position; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using AxisEq; using AxisPosCore; using AxisPosCore.Common; using FastReport; using Formatter; using KartObjects; using KartObjects.Entities.Documents; namespace AxisPosCore.EnvironmentObjects { /// <summary> /// Класс управляющий печатью на принтерах /// </summary> public class PrinterEo:POSEnvironmentObject { /// <summary> /// Ширина ленты в символах /// </summary> public List<AbstractPrinter> Printers; public AbstractPrinter PrimaryPrinter { get; set; } public PrinterEo(AbstractPrinter primaryPrinter) { PrimaryPrinter = primaryPrinter; } public PrinterEo(List<POSDevice> printers) { var prn = printers[0]; if (this.GetType().ToString() != "AxisPosCore.EnvironmentObjects.MultyPrinterEo") { PrimaryPrinter = InitPrinter(prn); InitPosEnvironment(); } } public List<Receipt> MultyPrinterReceipts { get; set; } protected void InitPosEnvironment() { try { POSEnvironment.NumReceipt = PrimaryPrinter.LastReceiptNumber; POSEnvironment.NumShift = PrimaryPrinter.LastShiftNumber; if (POSEnvironment.NumShift == 0) throw new POSException("Ошибка запроса номера смены"); } catch (Exception) { throw new POSException("Ошибка запроса номера смены"); } } protected AbstractPrinter InitPrinter(POSDevice prn) { AbstractPrinter printer = null; if (prn == null) { printer = AbstractPrinter.GetInstance("Software", Settings.AppDir + @"\"); printer.Open("COM1", "9600", "Admin", "3", "Soft"); POSEnvironment.IdPOSDevice = 1; } else { printer = AbstractPrinter.GetInstance(prn.Mnemonic, Settings.AppDir + @"\", prn.Id); //Ширина ленты int width; if (prn.addParam != null) if (int.TryParse(prn.addParam, out width)) printer.RibbonWidth = width; printer.Open(prn.SerialPort, prn.BaudRate.ToString(), "Admin", "3", prn.Mnemonic+prn.Id); printer.IdOrganization = prn.IdOrganization; printer.IdPosDevice = prn.Id; POSEnvironment.IdPOSDevice = prn.Id; } return printer; } /// <summary> /// Закрытие чека /// </summary> /// <param name="receipt"></param> public virtual bool CloseReceipt(Receipt receipt) { return CloseReceiptInner(receipt,PrimaryPrinter); } protected bool CloseReceiptInner(Receipt receipt,AbstractPrinter printer) { result = false; Error = null; var ress = printer.GetState(); if ((ress == PrinterState.STATE_PAPEREND) || (ress == PrinterState.STATE_PAPERENDING)) { receipt.ReceiptState = ReceiptState.Hanged; Error = new Exception("Ошибка принтера,\nНет бумаги!"); } if (ress == PrinterState.STATE_NEEDSHIFTCLOSE) { receipt.ReceiptState = ReceiptState.Hanged; Error = new Exception("Ошибка принтера,\nНеобходимо закрыть смену!"); } else if (ress != 0) Error = new Exception("Ошибка принтера " + ress.ToString()); result = Error == null; if (result) { currReceipt = receipt; var printThread = new Thread(() => CloseReceiptMethod(printer)); printThread.SetApartmentState(ApartmentState.STA); printThread.IsBackground = true; printThread.Start(); if (NeedShowWaitForm != null) NeedShowWaitForm("", "Печать чека"); // closeReceiptMethod(); } if (Error != null) WriteLog("При закрытии чека произошла ошибка! " + Error.Message); return result; } protected void CloseWeightForm(Exception error) { if (NeedCloseWaitForm != null) NeedCloseWaitForm(error); } protected void ShowWaitForm(string label, string message) { if (NeedShowWaitForm != null) NeedShowWaitForm(label, message); } protected Receipt currReceipt; protected Exception Error; protected bool result; protected void CloseReceiptMethod(AbstractPrinter printer) { BaseReceiptFormatter r = null; try { if (currReceipt.HasCashPayment) printer.OpenCashDrawer(); WriteLog("Начало печати" ); r = Settings.POSNumber==0 ? ReceiptFormatter.InitInstance(currReceipt, printer.RibbonWidth, 1, "Format1",true) : ReceiptFormatter.InitInstance(currReceipt, printer.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat), DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); //r.SlipStrings.Add("Слип начало:"); //r.SlipStrings.Add("test line 1"); //r.SlipStrings.Add("test line 2"); //r.SlipStrings.Add("test line 3"); //r.SlipStrings.Add("Слип конец."); WriteLog("Формат создан ширина чека " + printer.RibbonWidth); var errorst=r.Init(); WriteLog("Формат инициализирован"); if (errorst != "") { WriteLog("Ошибка при формировании строк чека!\n" + Error); } printer.PrintStrings(r.ReceiptStrings); WriteLog("Строки напечатаны"); /* foreach (string st in r.ReceiptStrings) { printer.PrintString(st); } */ int res = printer.PrintFreeDoc(currReceipt); result = res == 0; if (!result) { WriteLog("При закрытии чека произошла ошибка "+res); var ress = printer.GetState(); if ((ress == PrinterState.STATE_PAPERENDING) || (ress == PrinterState.STATE_PAPEREND)) { currReceipt.ReceiptState = ReceiptState.Hanged; Error= new Exception("Ошибка принтера,\nНет бумаги!"); } else Error=new POSException("При закрытии чека произошла ошибка, повторите закрытие."); } else currReceipt.ReceiptState = ReceiptState.Printed; printer.CurrStatus = (PrinterStatus)printer.GetStatus(); //Печатаем слип if (r.SlipStrings!=null) if (r.SlipStrings.Count > 0) printer.PrintStrings(r.SlipStrings); } catch (Exception e) { Error = e; } Thread.Sleep(150); CheckKPK(printer); if (r != null && (result) && (DataDictionary.GetParamBoolValue(PosParameterType.CopyCheckToOfficePrinter))) { PrintReceipt(currReceipt, "receipt.frx", r.SlipStrings); if (r.SlipStrings != null && r.SlipStrings.Count > 0) { printer.CutOff(); PrintReceipt(currReceipt, "receipt.frx", r.SlipStrings); } } if (NeedCloseWaitForm != null) NeedCloseWaitForm(Error); } protected virtual void CheckKPK(AbstractPrinter printer) { int kpkNum = 0; try { if (DataDictionary.GetParamBoolValue(PosParameterType.UseKPKCheck)) //Трехразовый запрос кпк if (printer.GetLastKPK(out kpkNum) != 0) if (printer.GetLastKPK(out kpkNum) != 0) if (printer.GetLastKPK(out kpkNum) != 0) { Error = new Exception("Ошибка получения номера КПК"); currReceipt.ReceiptState = ReceiptState.KPKConfirmationUnknown; } if (currReceipt.ReceiptState != ReceiptState.KPKConfirmationUnknown) { if (DataDictionary.GetParamBoolValue(PosParameterType.UseKPKCheck) && POSEnvironment.CurrReport != null) { if ((POSEnvironment.CurrReport.CurrKpk + 1 == kpkNum)) { if (currReceipt.ReceiptState != ReceiptState.Printed) currReceipt.ReceiptState = ReceiptState.Printed; result = true; Error = null; } else if ((POSEnvironment.CurrReport.CurrKpk == kpkNum)) { WriteLog("Ошибка КПК! ожидается " + (POSEnvironment.CurrReport.CurrKpk + 1).ToString() + " фр " + kpkNum); if (Error == null) Error = new Exception("Ошибка КПК! ожидается " + (POSEnvironment.CurrReport.CurrKpk + 1).ToString() + " фр " + kpkNum); //Отменяем то что уже напечатали printer.CancelReceipt(); } else { WriteLog("Ошибка КПК! ожидается " + (POSEnvironment.CurrReport.CurrKpk + 1).ToString() + " фр " + kpkNum); if (Error == null) Error = new Exception("Ошибка КПК! ожидается " + (POSEnvironment.CurrReport.CurrKpk + 1).ToString() + " фр " + kpkNum); currReceipt.ReceiptState = ReceiptState.KPKConfirmationUnknown; } } } } catch (Exception e1) { if (Error == null) Error = e1; currReceipt.ReceiptState = ReceiptState.KPKConfirmationUnknown; } if (result) result = Error == null; if (result) { currReceipt.KpkNum = kpkNum; POSEnvironment.CurrReport.CurrKpk = kpkNum; } } public override event DlgShowWaitForm NeedShowWaitForm; public override event DlgCloseWaitForm NeedCloseWaitForm; public virtual bool Zreport(PosCore model) { int result = -1; if (PrimaryPrinter.CurrStatus == PrinterStatus.STATUS_SHIFTCLOSED) throw new POSException("Смена уже закрыта!"); else { Thread printThread = new Thread(new ThreadStart( delegate { Exception error = null; try { //обрабатываем ситуацию с чеками, неушедшими на сервер if (POSEnvironment.ReceiptSaver!=null) if (POSEnvironment.ReceiptSaver.IsOnline) //пробуем прибить поток выгрузки и запустить его заново POSEnvironment.ReceiptSaver.CheckSenderThreadFreeze(); ///Печатаем заголовок отчета ZReportFormatter f = null; if ((DataDictionary.GetPattern(PosParameterType.ReceiptFormat)=="Format1" )||(DataDictionary.GetPattern(PosParameterType.ReceiptFormat)=="Format3" )) f = new ZReportFormatter1(PrimaryPrinter.RibbonWidth,Settings.POSNumber,POSEnvironment.Cashier.Name,POSEnvironment.CurrReport); else f = new ZReportFormatter(PrimaryPrinter.RibbonWidth, Settings.POSNumber, POSEnvironment.Cashier.Name, POSEnvironment.CurrReport); PrimaryPrinter.PrintStrings(f.ReceiptStrings); /*foreach (string st in f.ReceiptStrings) { PrimaryPrinter.PrintString(st); }*/ ///Снимаем отчет result = PrimaryPrinter.ZReport(POSEnvironment.CurrReport); WriteLog("Снят фискальный отчет"); if (result == 0) { POSEnvironment.NumReceipt = PrimaryPrinter.LastReceiptNumber; int shiftnum = PrimaryPrinter.LastShiftNumber; if (shiftnum != 0) POSEnvironment.NumShift = shiftnum; else POSEnvironment.NumShift++; WriteLog("Номер новой смены " + shiftnum); } else { WriteLog("Ошибка снятия отчета " + result); PrimaryPrinter.PrintString("Ошибка снятия отчета " + result); } } catch (Exception e) { //todo обработка ошибки error = e; } if ((error == null)&&(result ==0)) { try { WriteLog("Сохранение данных "); model.Dictionary.SaveData(); } catch (Exception e2) { WriteLog("Ошибка сохранения данных " + e2.Message); } WriteLog("Отправка данных на сервер"); //Добавляем отчет на отправку POSEnvironment.CurrReport.ShiftTime = DateTime.Now; POSEnvironment.ReceiptSaver.Enqueue(POSEnvironment.CurrReport); //Ждем 100 мс Thread.Sleep(100); //Ждем пока все чеки уйдут на сервер максимум 50 сек int ShiftStatus = 0; for (int i = 0; i < 10; i++) { if ((POSEnvironment.IsOnline) && (model.PosEnvironment.UnsendReceiptsCount != 0)) { Thread.Sleep(5000); if (i == 9) WriteLog("Ошибка отправки данных на сервер "); } else { ShiftStatus = 1; WriteLog("Данные отправлены на сервер"); break; } } #region Проверка КПК int kpkNum = 0; if (PrimaryPrinter is AtolFR) Thread.Sleep(1000); //Трехразовый запрос кпк if (PrimaryPrinter.GetLastKPK(out kpkNum) != 0) if (PrimaryPrinter.GetLastKPK(out kpkNum) != 0) if (PrimaryPrinter.GetLastKPK(out kpkNum) != 0) { error = new Exception("Ошибка получения номера КПК"); POSEnvironment.CurrReport.Status = -1; } if (error == null) { POSEnvironment.CurrReport.CurrKpk = kpkNum; POSEnvironment.CurrReport.Status = ShiftStatus; } if ( (DataDictionary.GetParamBoolValue( PosParameterType.CopyCheckToOfficePrinter))) { List<string> slip = null; if (POSEnvironment.AcquiringEo != null) { WriteLog("Начало закрытия банковской смены."); slip=Helper.StringToList(POSEnvironment.AcquiringEo.Zreport()); } printReport(POSEnvironment.CurrReport,slip); } #endregion } if (NeedCloseWaitForm != null) NeedCloseWaitForm(error); } )); printThread.SetApartmentState(ApartmentState.STA); printThread.Start(); if (NeedShowWaitForm != null) NeedShowWaitForm("Закрытие смены ", "Пожалуйста, не выключайте кассу..."); if (result!=0) throw new POSException("Произошла ошибка при закрытии смены!"); } return result == 0; } public void CloseBankShift() { try { if (POSEnvironment.AcquiringEo != null) { WriteLog("Начало закрытия банковской смены."); PrimaryPrinter.PrintStrings(Helper.StringToList(POSEnvironment.AcquiringEo.Zreport())); } } catch { WriteLog("Ошибка закрытия смены по банку."); } } /// <summary> /// Печать копии чека /// </summary> /// <param name="r"></param> public void PrintReceiptCopy(Receipt receipt) { PrinterState ress=PrimaryPrinter.GetState(); if ((ress == PrinterState.STATE_PAPEREND)||(ress == PrinterState.STATE_PAPERENDING)) new Exception("Ошибка принтера,\nНет бумаги!"); Thread printThread = new Thread(new ThreadStart( delegate { Exception error = null; CopyReceiptFormatter r = null; try { r = new CopyReceiptFormatter(receipt, PrimaryPrinter.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat),DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); r.Init(receipt, PrimaryPrinter.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat),DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); PrimaryPrinter.PrintStrings(r.ReceiptStrings); /*foreach (string st in r.ReceiptStrings) { PrimaryPrinter.PrintString(st); }*/ //Печатаем слип if (r.SlipStrings!=null) PrimaryPrinter.PrintStrings(r.SlipStrings); /* foreach (string st in r.SlipStrings) { if (st != null) PrimaryPrinter.PrintString(st); } */ } catch (Exception e) { error = e; } if ((DataDictionary.GetParamBoolValue(PosParameterType.CopyCheckToOfficePrinter))) PrintReceipt(receipt, "receipt.frx",r.SlipStrings); else Thread.Sleep(1000); if (NeedCloseWaitForm != null) NeedCloseWaitForm(error); })); printThread.SetApartmentState(ApartmentState.STA); printThread.Start(); if (NeedShowWaitForm != null) NeedShowWaitForm("", "Печать копии чека"); } /// <summary> /// Печать отмененного чека /// </summary> /// <param name="r"></param> public void PrintDeletedReceipt(Receipt receipt) { Thread printThread = new Thread(new ThreadStart( delegate { Exception error = null; try { PrimaryPrinter.CancelReceipt(); DeleteReceiptFormatter r = new DeleteReceiptFormatter(receipt, PrimaryPrinter.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat),DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); r.Init(receipt, PrimaryPrinter.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat),DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); PrimaryPrinter.PrintStrings(r.ReceiptStrings); /*foreach (string st in r.ReceiptStrings) { PrimaryPrinter.PrintString(st); } */ //Печатаем слип PrimaryPrinter.PrintStrings(r.SlipStrings); /*foreach (string st in r.SlipStrings) { if (st != null) PrimaryPrinter.PrintString(st); } */ if ((DataDictionary.GetParamBoolValue(PosParameterType.CopyCheckToOfficePrinter))) PrintReceipt(receipt, "receipt.frx"); } catch (Exception e) { error = e; } Thread.Sleep(1000); if (NeedCloseWaitForm != null) NeedCloseWaitForm(error); })); printThread.SetApartmentState(ApartmentState.STA); printThread.Start(); if (NeedShowWaitForm != null) NeedShowWaitForm("", "Печать отмены чека"); } /// <summary> /// Печать товарного чека /// </summary> /// <param name="r"></param> public void PrintSalesReceipt(Receipt receipt) { Thread printThread = new Thread(new ThreadStart( delegate { Exception error = null; try { SalesReceiptFormatter r = new SalesReceiptFormatter(receipt, PrimaryPrinter.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat),DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); r.Init(receipt, PrimaryPrinter.RibbonWidth, Settings.POSNumber, DataDictionary.GetPattern(PosParameterType.ReceiptFormat), DataDictionary.GetParamBoolValue(PosParameterType.SlipInsideReceipt)); PrimaryPrinter.PrintStrings(r.ReceiptStrings); /*foreach (string st in r.ReceiptStrings) { PrimaryPrinter.PrintString(st); } */ if ((DataDictionary.GetParamBoolValue(PosParameterType.CopyCheckToOfficePrinter))) PrintReceipt(receipt, "salereceipt.frx"); } catch (Exception e) { error = e; } Thread.Sleep(1000); if (NeedCloseWaitForm != null) NeedCloseWaitForm(error); })); printThread.Start(); if (NeedShowWaitForm != null) NeedShowWaitForm("", "Печать товарного чека"); } public override void CloseEO() { PrimaryPrinter.Close(); } public virtual bool Xreport() { //для х отчета подготавливаем структуру отчета для передачи номер смены ZReport zr=null; if (POSEnvironment.CurrReport == null) zr = new ZReport() { ShiftNumber = POSEnvironment.NumShift }; else zr = POSEnvironment.CurrReport; ///Печатаем заголовок отчета XReportFormatter f = null; if ((DataDictionary.GetPattern(PosParameterType.ReceiptFormat) == "Format1") || (DataDictionary.GetPattern(PosParameterType.ReceiptFormat) == "Format3")) f = new XReportFormatter1(PrimaryPrinter.RibbonWidth, Settings.POSNumber, POSEnvironment.Cashier.Name, POSEnvironment.CurrReport); else f = new XReportFormatter(PrimaryPrinter.RibbonWidth, Settings.POSNumber, POSEnvironment.Cashier.Name, POSEnvironment.CurrReport); PrimaryPrinter.PrintStrings(f.ReceiptStrings); List<string> slip=null; if (POSEnvironment.AcquiringEo != null) slip = Helper.StringToList(POSEnvironment.AcquiringEo.Xreport()); if ((DataDictionary.GetParamBoolValue(PosParameterType.CopyCheckToOfficePrinter))) if (POSEnvironment.CurrReport!=null) printReport(POSEnvironment.CurrReport,slip); try { if (POSEnvironment.AcquiringEo != null) PrimaryPrinter.PrintStrings(slip); } catch { WriteLog("Ошибка запроса журнала операций"); } ///Снимаем отчет return PrimaryPrinter.XReport()==0; } public PrinterState prnState { get { return PrimaryPrinter.GetState(); } } public int prnStatus { get { return PrimaryPrinter.GetStatus(); } } public void FRReport(int ShiftNumber) { PrimaryPrinter.ShiftReport(ShiftNumber); } /// <summary> /// Получение суммы наличности в кассе /// </summary> /// <returns></returns> public decimal getCashSum() { return PrimaryPrinter.CashSum; } /// <summary> /// Открытие денежного ящика /// </summary> public void OpenCashDrawer() { PrimaryPrinter.OpenCashDrawer(); } /// <summary> /// Внесение денег /// </summary> /// <param name="Sum"></param> public int InCash(decimal Sum) { PrimaryPrinter.PrintString("Касса № " + Settings.POSNumber); int err = PrimaryPrinter.CashIn(Convert.ToInt64(Sum * 100)); return err; } /// <summary> /// Изъятие наличности /// </summary> /// <param name="Sum"></param> public int OutCash(decimal Sum) { PrimaryPrinter.PrintString("Касса № " + Settings.POSNumber); int err = PrimaryPrinter.CashOut(Convert.ToInt64(Sum * 100)); PrimaryPrinter.PrintString("Остаток денег " + getCashSum().ToString()); return err; } internal int getLastKpk() { int kpkNum=0; //Трехразовый запрос кпк if (PrimaryPrinter.GetLastKPK(out kpkNum) != 0) if (PrimaryPrinter.GetLastKPK(out kpkNum) != 0) if (PrimaryPrinter.GetLastKPK(out kpkNum) != 0) kpkNum = 0;//throw new Exception("Ошибка получения номера КПК.\nПопробуйте перезагрузить принтер или кассовый терминал!"); return kpkNum; } internal void ContinuePrint() { if (PrimaryPrinter is ShtrihFR) PrimaryPrinter.ContinuePrint(); } /// <summary> /// Печать отчета на офисном принтере /// </summary> /// <param name="receipt"></param> public void printReport(ZReport zReport,List<string> slip=null) { if (File.Exists("Reports" + @"\report.frx")) using (Report report = new Report()) { report.Load("Reports" + @"\report.frx"); if (zReport.ZReportSectionPayments.Count>0) report.RegisterData(zReport.ZReportSectionPayments.AsEnumerable(), "zReportPaymentBindingSource"); else report.RegisterData(zReport.ZReportPayments.AsEnumerable(), "zReportPaymentBindingSource"); report.GetDataSource("zReportPaymentBindingSource").Enabled = true; TextObject ShiftNum = (TextObject)report.FindObject("ShiftNum"); ShiftNum.Text = zReport.ShiftNumber.ToString() ; TextObject ShiftDateTime = (TextObject)report.FindObject("ShiftDateTime"); if (zReport.Status == 0) ShiftDateTime.Text = DateTime.Now.ToString("dd.MM.yy HH:mm"); else ShiftDateTime.Text = zReport.ShiftTime.ToString("dd.MM.yy HH:mm"); TextObject nameCashier = (TextObject)report.FindObject("nameCashier"); nameCashier.Text = POSEnvironment.Cashier.Name; TextObject ShiftStatus = (TextObject)report.FindObject("ShiftStatus"); if (zReport.Status == 0) ShiftStatus.Text = "Смена открыта"; else ShiftStatus.Text = "Смена закрыта"; TextObject POSNumber = (TextObject)report.FindObject("POSNumber"); POSNumber.Text = DataDictionary.SPos.Number.ToString(); //Дополнительные поля decimal CashSale = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.TotalSale).FirstOrDefault(); decimal SaleReturn = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.TotalReturn).FirstOrDefault(); decimal SaleDiscount = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.TotalSaleDiscount).FirstOrDefault(); decimal SaleReturnDiscount = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.TotalReturnDiscount).FirstOrDefault(); int SaleQuant = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.quantSaleReceipt).FirstOrDefault(); decimal CashlessSale = (from z in zReport.ZReportPayments where z.PayType.IsCashless == true select z.TotalSale).FirstOrDefault(); decimal CashlessReturn = (from z in zReport.ZReportPayments where z.PayType.IsCashless == true select z.TotalReturn).FirstOrDefault(); decimal CashlessDiscount = (from z in zReport.ZReportPayments where z.PayType.IsCashless == true select z.TotalSaleDiscount).FirstOrDefault(); decimal ReturnCashlessDiscount = (from z in zReport.ZReportPayments where z.PayType.IsCashless == true select z.TotalReturnDiscount).FirstOrDefault(); int QuantReceiptCash = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.quantSaleReceipt).FirstOrDefault(); int QuantReturnCash = (from z in zReport.ZReportPayments where z.PayType.IsCashless == false select z.quantSaleReturn).FirstOrDefault(); int QuantReceiptCashless = (from z in zReport.ZReportPayments where z.PayType.IsCashless == true select z.quantSaleReceipt).FirstOrDefault(); int QuantReturnCashless = (from z in zReport.ZReportPayments where z.PayType.IsCashless == true select z.quantSaleReturn).FirstOrDefault(); decimal TotalSale = CashSale + SaleDiscount + CashlessSale + CashlessDiscount; decimal TotalReturn = SaleReturn + SaleReturnDiscount + CashlessReturn + ReturnCashlessDiscount; decimal TotalDiscount = SaleDiscount + CashlessDiscount - SaleReturnDiscount - ReturnCashlessDiscount; decimal TotalSum = CashSale - SaleReturn + CashlessSale - CashlessReturn; TextObject toQuantReceiptCash = (TextObject)report.FindObject("QuantReceiptCash"); if (toQuantReceiptCash!=null) toQuantReceiptCash.Text = QuantReceiptCash.ToString(); ; TextObject toQuantReturnCash = (TextObject)report.FindObject("QuantReturnCash"); if (toQuantReturnCash != null) toQuantReturnCash.Text = QuantReturnCash.ToString(); TextObject toSaleTotalCash = (TextObject)report.FindObject("SaleTotalCash"); if (toSaleTotalCash != null) toSaleTotalCash.Text = (Math.Round(CashSale + SaleDiscount, 2)).ToString("0.00"); TextObject toSaleDiscount = (TextObject)report.FindObject("SaleDiscount"); if (toSaleDiscount != null) toSaleDiscount.Text = (Math.Round(SaleDiscount, 2)).ToString("0.00"); TextObject toCashSale = (TextObject)report.FindObject("CashSale"); if (toCashSale != null) toCashSale.Text = (Math.Round(CashSale, 2)).ToString("0.00"); TextObject toReturnTotalCash = (TextObject)report.FindObject("ReturnTotalCash"); if (toReturnTotalCash != null) toReturnTotalCash.Text = (Math.Round(SaleReturn + SaleReturnDiscount, 2)).ToString("0.00"); TextObject toSaleReturnDiscount = (TextObject)report.FindObject("SaleReturnDiscount"); if (toSaleReturnDiscount != null) toSaleReturnDiscount.Text = (Math.Round(SaleReturnDiscount, 2)).ToString("0.00"); TextObject toSaleReturn = (TextObject)report.FindObject("SaleReturn"); if (toSaleReturn != null) toSaleReturn.Text = (Math.Round(SaleReturn, 2)).ToString("0.00"); TextObject toDiscountTotal = (TextObject)report.FindObject("DiscountTotal"); if (toDiscountTotal != null) toDiscountTotal.Text = (Math.Round(SaleDiscount - SaleReturnDiscount, 2)).ToString("0.00"); TextObject toTurnOver = (TextObject)report.FindObject("TurnOver"); if (toTurnOver != null) toTurnOver.Text = (Math.Round(CashSale - SaleReturn, 2)).ToString("0.00"); /////// TextObject toQuantReceiptCashless = (TextObject)report.FindObject("QuantReceiptCashless"); if (toQuantReceiptCashless != null) toQuantReceiptCashless.Text = (QuantReceiptCashless).ToString("0.00"); TextObject toQuantReturnCashless = (TextObject)report.FindObject("QuantReturnCashless"); if (toQuantReturnCashless != null) toQuantReturnCashless.Text = (QuantReturnCashless).ToString("0.00"); TextObject toCashlessSaleTotal = (TextObject)report.FindObject("CashlessSaleTotal"); if (toCashlessSaleTotal != null) toCashlessSaleTotal.Text = (Math.Round(CashlessSale + CashlessDiscount, 2)).ToString("0.00"); TextObject toCashlessDiscount = (TextObject)report.FindObject("CashlessDiscount"); if (toCashlessDiscount != null) toCashlessDiscount.Text = (Math.Round(CashlessDiscount, 2)).ToString("0.00"); TextObject toCashlessSale = (TextObject)report.FindObject("CashlessSale"); if (toCashlessSale != null) toCashlessSale.Text = (Math.Round(CashlessSale, 2)).ToString("0.00"); TextObject toCashlessReturnTotal = (TextObject)report.FindObject("CashlessReturnTotal"); if (toCashlessReturnTotal != null) toCashlessReturnTotal.Text = (Math.Round(CashlessReturn + ReturnCashlessDiscount, 2)).ToString("0.00"); TextObject toReturnCashlessDiscount = (TextObject)report.FindObject("ReturnCashlessDiscount"); if (toReturnCashlessDiscount != null) toReturnCashlessDiscount.Text = (Math.Round(ReturnCashlessDiscount, 2)).ToString("0.00"); TextObject toCashlessReturn = (TextObject)report.FindObject("CashlessReturn"); if (toCashlessReturn != null) toCashlessReturn.Text = (Math.Round(CashlessReturn, 2)).ToString("0.00"); TextObject toTotalCashlessDiscount = (TextObject)report.FindObject("TotalCashlessDiscount"); if (toTotalCashlessDiscount != null) toTotalCashlessDiscount.Text = (Math.Round(CashlessDiscount - ReturnCashlessDiscount, 2)).ToString("0.00"); TextObject toCashlessTurnOver = (TextObject)report.FindObject("CashlessTurnOver"); if (toCashlessTurnOver != null) toCashlessTurnOver.Text = (Math.Round(CashlessSale - CashlessReturn, 2)).ToString("0.00"); ///// TextObject toquantCancelReceipt = (TextObject)report.FindObject("quantCancelReceipt"); if (toquantCancelReceipt != null) toquantCancelReceipt.Text = (zReport.QuantCancelReceipt).ToString("0.00"); TextObject tosumCancelReceipt = (TextObject)report.FindObject("sumCancelReceipt"); if (tosumCancelReceipt != null) tosumCancelReceipt.Text = (zReport.SumCancelReceipt).ToString("0.00"); //// "Итого"; TextObject toTotalSale = (TextObject)report.FindObject("TotalSale"); if (toTotalSale != null) toTotalSale.Text = (Math.Round(TotalSale, 2)).ToString("0.00"); TextObject toTotalReturn = (TextObject)report.FindObject("TotalReturn"); if (toTotalReturn != null) toTotalReturn.Text = (Math.Round(TotalReturn, 2)).ToString("0.00"); TextObject toTotalDiscount = (TextObject)report.FindObject("TotalDiscount"); if (toTotalDiscount != null) toTotalDiscount.Text = (Math.Round(TotalDiscount, 2)).ToString("0.00"); TextObject toTotalSum = (TextObject)report.FindObject("TotalSum"); if (toTotalSum != null) toTotalSum.Text = (Math.Round(TotalSum, 2)).ToString("0.00"); TextObject tosumInCash = (TextObject)report.FindObject("sumInCash"); if (tosumInCash != null) tosumInCash.Text = zReport.SumInCash.ToString("0.00"); TextObject tosumOutCash = (TextObject)report.FindObject("sumOutCash"); if (tosumOutCash != null) tosumOutCash.Text = zReport.SumOutCash.ToString("0.00"); TextObject toquantInCash = (TextObject)report.FindObject("quantInCash"); if (toquantInCash != null) toquantInCash.Text = zReport.QuantInCash.ToString("0.00"); var Slip = (TextObject)report.FindObject("Slip"); if ((Slip != null) && (slip!=null)) if (slip.Count>0) Slip.Text = slip.Aggregate((x, y) => x + "\r\n" + y); /* --Внесения/изъятия report.RegisterData(zReport.EncashmentRecords.AsEnumerable(), "zReportEncashmentBindingSource"); report.GetDataSource("zReportEncashmentBindingSource").Enabled = true; for (int i = 0; i < zReport.EncashmentRecords.Count; i++) { string directoperation = ""; switch (zReport.EncashmentRecords[i].DirectionOperation) { case 1: directoperation = "Внесение "; break; case -1: directoperation = "Изъятие "; break; } } */ report.PrintSettings.ShowDialog = false; if (report.Prepare()) report.PrintPrepared(); } } public void printZReportCopy(ZReport zreport) { ///Печатаем заголовок отчета ZReportFormatter f = null; if ((DataDictionary.GetPattern(PosParameterType.ReceiptFormat) == "Format1") || (DataDictionary.GetPattern(PosParameterType.ReceiptFormat) == "Format3")) f = new ZReportFormatter1(PrimaryPrinter.RibbonWidth, Settings.POSNumber, POSEnvironment.Cashier.Name, zreport); else f = new ZReportFormatter(PrimaryPrinter.RibbonWidth, Settings.POSNumber, POSEnvironment.Cashier.Name, zreport); f.ReceiptStrings[0] = f.ReceiptStrings[0].Replace("Z-ОТЧЕТ", "КОПИЯ-Z"); PrimaryPrinter.PrintStrings(f.ReceiptStrings); PrimaryPrinter.PrintHeader(); } /// <summary> /// Печать чека на офисном принтере /// </summary> /// <param name="receipt"></param> /// <param name="nameReport"></param> /// <param name="slip"></param> public void PrintReceipt(Receipt receipt, string nameReport, List<string> slip=null) { if (File.Exists("Reports" + @"\"+nameReport)) using (Report report = new Report()) { report.Load("Reports" + @"\" + nameReport); List<ReceiptSpecRecordEx> rseRecords = new List<ReceiptSpecRecordEx>(); foreach (var item in receipt.GetRecords()) { ReceiptSpecRecordEx rse = new ReceiptSpecRecordEx(item); if (item.Good == null) item.Good = DataDictionary.GetGoodsById(item.IdGood)[0]; if (item.Good.IdWhSection != null) rse.NameWhSection = DataDictionary.GetWhSectionName(item.Good.IdWhSection); rseRecords.Add(rse); } report.RegisterData(rseRecords.AsEnumerable(), "ReceiptSpecRecords"); report.GetDataSource("ReceiptSpecRecords").Enabled = true; TextObject date = (TextObject)report.FindObject("Date"); date.Text = receipt.DateReceipt.ToString(); TextObject Cashier = (TextObject)report.FindObject("Cashier"); Cashier.Text = string.Concat(receipt.Cashier.Name); TextObject DocNum = (TextObject)report.FindObject("DocNum"); DocNum.Text = receipt.FullNumber; TextObject SaleLabel = (TextObject)report.FindObject("SaleLabel"); if (SaleLabel!=null) SaleLabel.Text = (receipt.DirectOperation==1)?"Продажа":"Возврат"; TextObject TotalDiscount = (TextObject)report.FindObject("TotalDiscount"); if (TotalDiscount != null) TotalDiscount.Text = receipt.TotalDiscount.ToString("# ##0.00"); TextObject TotalWithDiscount = (TextObject)report.FindObject("TotalWithDiscount"); if (TotalWithDiscount != null) TotalWithDiscount.Text = receipt.TotalSum.ToString("# ##0.00"); TextObject BuyerSum = (TextObject)report.FindObject("BuyerSum"); if (BuyerSum != null) BuyerSum.Text = receipt.BuyerSum.ToString("# ##0.00"); TextObject Change = (TextObject)report.FindObject("Change"); if (Change != null) Change.Text = receipt.Change.ToString("# ##0.00"); if (slip != null) { var Slip = (TextObject)report.FindObject("Slip"); if ((Slip != null) && (slip.Count > 0)) Slip.Text = slip.Aggregate((x, y) => x + "\r\n" + y); } if (receipt.Payment.Count > 0) { PayType p = (from rp in receipt.Payment select rp.PayType).First(); TextObject PayTypeLabel = (TextObject)report.FindObject("PayTypeLabel"); if (PayTypeLabel != null) PayTypeLabel.Text = p.ToString(); } report.PrintSettings.ShowDialog = false; if (report.Prepare()) report.PrintPrepared(); } } public virtual void SetHeader(List<HeaderString> headerStrings) { if (headerStrings.Count == 0) { //Пробуем получить заголовок из фискальника PrimaryPrinter.InitHeaderStrings(); } else PrimaryPrinter.HeaderStrings = (from s in headerStrings select s.Name).ToArray(); } public void PrintStrings(List<string> list) { PrimaryPrinter.PrintStrings(list); } public virtual AbstractPrinter getPrinterByReceipt(Receipt receipt) { return PrimaryPrinter; } } }
using CEMAPI.DAL; using CEMAPI.Models; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace CEMAPI.Controllers { public class TEEmailTriggerEventsAPIController : ApiController { TETechuvaDBContext context = new TETechuvaDBContext(); GenericDAL genDAL = new GenericDAL(); FailInfo finfo = new FailInfo(); SuccessInfo sinfo = new SuccessInfo(); [HttpPost] public HttpResponseMessage Save(TEEmailTriggerEvent mailEvnt) { try { TEEmailTriggerEvent mailEvntChk = context.TEEmailTriggerEvents.Where(a => a.Event == mailEvnt.Event && a.IsDeleted == false).FirstOrDefault(); if (mailEvntChk != null) { finfo.errorcode = 1; finfo.errormessage = "Event Already Exists"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } mailEvnt.IsDeleted = false; mailEvnt.LastModifiedOn = DateTime.Now; mailEvnt.IsEmail = true; context.TEEmailTriggerEvents.Add(mailEvnt); context.SaveChanges(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Saved"; sinfo.listcount = 0; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to Save"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } [HttpPost] public HttpResponseMessage Update(TEEmailTriggerEvent mailEvnt) { try { TEEmailTriggerEvent mailEvntObj = context.TEEmailTriggerEvents.Where(a => a.UniqueID == mailEvnt.UniqueID && a.IsDeleted == false).FirstOrDefault(); if (mailEvntObj != null) { mailEvntObj.IsDeleted = false; mailEvntObj.LastModifiedOn = DateTime.Now; mailEvntObj.IsEmail = mailEvnt.IsEmail; //mailEvntObj.Event = mailEvnt.Event; //mailEvntObj.Descrption = mailEvnt.Descrption; mailEvntObj.LastModifiedBy = mailEvnt.LastModifiedBy; context.Entry(mailEvntObj).CurrentValues.SetValues(mailEvntObj); context.SaveChanges(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Updated"; sinfo.listcount = 0; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Fail to update"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to update"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } [HttpPost] public HttpResponseMessage Delete(TEEmailTriggerEvent mailEvnt) { try { TEEmailTriggerEvent mailEvntObj = context.TEEmailTriggerEvents.Where(a => a.UniqueID == mailEvnt.UniqueID && a.IsDeleted == false).FirstOrDefault(); if (mailEvntObj != null) { mailEvntObj.IsDeleted = true; mailEvntObj.LastModifiedOn = DateTime.Now; mailEvntObj.LastModifiedBy = mailEvnt.LastModifiedBy; context.Entry(mailEvntObj).CurrentValues.SetValues(mailEvntObj); context.SaveChanges(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully delete"; sinfo.listcount = 0; return new HttpResponseMessage() { Content = new JsonContent(new { info = sinfo }) }; } else { finfo.errorcode = 1; finfo.errormessage = "Fail to delete"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to deleted"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } [HttpPost] public HttpResponseMessage GetEventByUniqueID(JObject json) { try { int uniqueId = json["UniqueID"].ToObject<int>(); int count = 0; var myList = (from evnt in context.TEEmailTriggerEvents join prof in context.UserProfiles on evnt.LastModifiedBy equals prof.UserId into tempProf from users in tempProf.DefaultIfEmpty() where evnt.IsDeleted == false && evnt.UniqueID==uniqueId select new { evnt.IsEmail, evnt.LastModifiedOn, evnt.Event, evnt.Description, evnt.UniqueID, evnt.LastModifiedBy, LastModifiedBy_Name = users.CallName }).FirstOrDefault(); if (myList != null) { count = 1; sinfo.errorcode = 0; sinfo.errormessage = "Success"; sinfo.fromrecords = 1; sinfo.torecords = 1; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result=myList,info = sinfo }) }; } else { sinfo.errorcode = 0; sinfo.errormessage = "No Data Found"; sinfo.fromrecords = 1; sinfo.torecords = 1; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; return new HttpResponseMessage() { Content = new JsonContent(new { result = myList, info = finfo }) }; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to get Records"; return new HttpResponseMessage() { Content = new JsonContent(new { info = finfo }) }; } } [HttpPost] public HttpResponseMessage GetAllEmailEvents_Pagination(JObject json) { int count = 0; HttpResponseMessage hrm = new HttpResponseMessage(); try { int pagenumber = json["page_number"].ToObject<int>(); int pagepercount = json["pagepercount"].ToObject<int>(); var myList = (from evnt in context.TEEmailTriggerEvents join prof in context.UserProfiles on evnt.LastModifiedBy equals prof.UserId into tempProf from users in tempProf.DefaultIfEmpty() where evnt.IsDeleted==false select new { evnt.IsEmail, evnt.LastModifiedOn, evnt.Event, evnt.Description, evnt.UniqueID, evnt.LastModifiedBy, LastModifiedBy_Name=users.CallName }).ToList(); count = myList.Count; if (count > 0) { if (pagenumber == 0) { pagenumber = 1; } int iPageNum = pagenumber; int iPageSize = pagepercount; int start = iPageNum - 1; start = start * iPageSize; var finalResult = myList.Skip(start).Take(iPageSize).ToList(); sinfo.errorcode = 0; sinfo.errormessage = "Success"; sinfo.fromrecords = (start == 0) ? 1 : start + 1; sinfo.torecords = finalResult.Count + start; sinfo.totalrecords = count; sinfo.listcount = finalResult.Count; sinfo.pages = "1"; if (finalResult.Count > 0) { hrm.Content = new JsonContent(new { result = finalResult, info = sinfo }); } else { finfo.errorcode = 0; finfo.errormessage = "No Records"; finfo.listcount = 0; hrm.Content = new JsonContent(new { result = finalResult, info = finfo }); } } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to get Records"; finfo.listcount = 0; hrm.Content = new JsonContent(new { info = finfo }); } return hrm; } } }
using System; using Petanque.Model.Repository; using Petanque.Model.Teams; namespace Petanque.Model.Results { public class Result : AbstractMongoEntity { public Team TeamWin { get; set; } public Team TeamLoose { get; set; } public DateTime Date { get; set; } public int DepthOfTheGame { get; set; } public bool GainProcessed { get; set; } public Result() { Date = DateTime.Now; GainProcessed = false; } } }
using Pe.Stracon.Politicas.Infraestructura.QueryModel.Base; using System; namespace Pe.Stracon.Politicas.Infraestructura.QueryModel.General { /// <summary> /// Representa los datos de Plantilla Notificacion /// </summary> /// <remarks> /// Creación: GMD 27032015 <br /> /// Modificación: <br /> /// </remarks> public class PlantillaNotificacionLogic : Logic { /// <summary> /// CodigoPlantillaNotificacion /// </summary> public Guid CodigoPlantillaNotificacion { get; set; } /// <summary> /// CodigoSistema /// </summary> public Guid CodigoSistema { get; set; } /// <summary> /// CodigoTipoNotificacion /// </summary> public string CodigoTipoNotificacion { get; set; } /// <summary> /// Asunto /// </summary> public string Asunto { get; set; } /// <summary> /// IndicadorActiva /// </summary> public bool IndicadorActiva { get; set; } /// <summary> /// Contenido /// </summary> public string Contenido { get; set; } /// <summary> /// Codigo Tipo Destinatario /// </summary> public string CodigoTipoDestinatario { get; set; } /// <summary> /// Destinatario /// </summary> public string Destinatario { get; set; } /// <summary> /// Destinatario Copia /// </summary> public string DestinatarioCopia { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Wee.Common.Contracts { public interface IWeeModule : IWeePackage { string RootMenuDefaultTitle { get; } } }
namespace Tests.Pages.Advocacy { using System; using Framework.Core.Common; using Framework.Core.Config; using OpenQA.Selenium; public class AddressValidation { private Driver driver; private IWebElement addressLine1; private IWebElement zip5; private IWebElement next; public AddressValidation(Driver driver) : this( driver, "AddressLine1", "PostalCode", "edit-submitform", AppConfig.AdvocatorBaseUrl + "/poc.html") { } private AddressValidation( Driver driver, string addressLine1Name, string zip5Name, string nextId, string pageUrl) { Guard.NotNull(() => driver, driver); Guard.NotNullOrEmpty(() => addressLine1Name, addressLine1Name); Guard.NotNullOrEmpty(() => zip5Name, zip5Name); Guard.NotNullOrEmpty(() => nextId, nextId); Guard.IsValid( () => pageUrl, pageUrl, s => !string.IsNullOrEmpty(s) && Uri.IsWellFormedUriString(s, UriKind.Absolute), "The Advocator URL is not valid"); this.SetupPage(driver, addressLine1Name, zip5Name, nextId, pageUrl); } public void FillAllValidation(string address, string zip) { this.driver.SendKeys(this.addressLine1, address); this.driver.SendKeys(this.zip5, zip); } public void Next() { this.next.Click(); } private void SetupPage( Driver advocatorDriver, string addressLine1Name, string zip5Name, string nextId, string pageUrl) { this.driver = advocatorDriver; this.driver.GoToPage(pageUrl); this.addressLine1 = this.driver.FindElement(By.Name(addressLine1Name)); this.zip5 = this.driver.FindElement(By.Name(zip5Name)); this.next = this.driver.FindElement(By.Id(nextId)); } } }
namespace Backpressure { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; internal class BackpressureDropOperatorFactory<T> : IObservable<T> { private readonly IObservable<T> _source; private readonly int _initialCount; private readonly Action<T> _onDrop; public BackpressureDropOperatorFactory( IObservable<T> source, int initialCount, Action<T> onDrop) { this._source = source; this._initialCount = initialCount; this._onDrop = onDrop; } public IDisposable Subscribe(IObserver<T> observer) { var op = new BackpressureDropOperator<T>( observer, this._initialCount, this._onDrop); var disposable = this._source.Subscribe(op); var subscription = new Subscription(disposable, op); var subscriber = observer as ISubscriber<T>; if (subscriber != null) { subscriber.OnSubscribe(subscription); } return subscription; } } }
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Threading; namespace csharp_client { class Program { static void Main(string[] args) { bool connected = CommunicationManager.instance.Init(); if (!connected) { Console.WriteLine("Cannot connect to server..."); Console.ReadKey(); return; } UIDisplayer.instance.Init(); while(true) { ConsoleKeyInfo input = System.Console.ReadKey(true); UIDisplayer.instance.HandleInput((int)(input.KeyChar)); } } } class CommunicationManager { private CommunicationManager() { } public static readonly CommunicationManager instance = new CommunicationManager(); SocketClient _socketClient; public bool Init() { _socketClient = new SocketClient(); bool ret = _socketClient.ConnectServer(); return ret; } public bool SendMessage(int type, string str ) { Message msg = new Message(); msg.Type = 0; msg.Content = str; byte[] bMsg; int len = msg.serializeToBytes(out bMsg); byte[] bLen = BitConverter.GetBytes(len); byte[] bSend = new byte[bMsg.Length + 4]; Array.Copy(bLen, 0, bSend, 0, 4); Array.Copy(bMsg, 0, bSend, 4, len); _socketClient.Send(bSend); return true; } public void Receive(byte[] data, int len) { Message msg = new Message(); msg.ParseFromBytes(data, len); HandleMessage(msg ); } private void HandleMessage(Message msg) { if(msg.Type == 0) { UIDisplayer.instance.AppendMessage(msg.Content); } } } class SocketClient { public SocketClient(){} private Socket _socket; public bool ConnectServer() { IPAddress ip = IPAddress.Parse(csharp_client.Config.server); int port = csharp_client.Config.port; _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _socket.Connect(new IPEndPoint(ip, port)); //Console.WriteLine("connected"); Thread tRecv = new Thread(new ThreadStart(ReceiveMsg)); tRecv.IsBackground = true; tRecv.Start(); return true; } catch { Console.WriteLine("connect fail"); return false; } } void ReceiveMsg() { byte[] lenBytes = new byte[4]; byte[] recvBytes = new byte[csharp_client.Config.buffer_max_length]; int bytes; while (true) { int len = 0; bytes = _socket.Receive(lenBytes, 4, 0); if(bytes > 0) { len = BitConverter.ToInt32(lenBytes, 0); } if (bytes < 0) { break; } if (len > 0) { bytes = _socket.Receive(recvBytes, len , 0); CommunicationManager.instance.Receive(recvBytes, len); } if (bytes < 0) { break; } } _socket.Close(); } public void Send(byte[] data) { _socket.Send(data); } } class UIDisplayer { private UIDisplayer() { } public static readonly UIDisplayer instance = new UIDisplayer(); readonly object msgQueueLock = new object(); private bool _needRefresh = true; Queue<string> _messagesWithFormat = new Queue<string>(); List<int> _input = new List<int>(); public bool Init() { Console.CursorVisible = false; DisplayInput(); Thread tDisplay = new Thread(new ThreadStart(Display)); tDisplay.IsBackground = true; tDisplay.Start(); return true; } public void HandleInput(int input) { lock (msgQueueLock) { if (input == 8 && _input.Count != 0) { _input.RemoveAt(_input.Count - 1); } else if (input == 13 && _input.Count != 0) { int count = _input.Count; StringBuilder sb = new StringBuilder(); for (int i = 0; i < count; i++) { sb.Append((char)_input[i]); } string str = sb.ToString(); CommunicationManager.instance.SendMessage(0, str); _input.Clear(); } else if (input != 8) { _input.Add(input); } _needRefresh = true; } } private void Display() { while (true) { if (_needRefresh) { _needRefresh = false; ClearScreen(); DisplayMessage(); Seperate(); DisplayInput(); } } } void ClearScreen() { System.Console.Clear(); } void DisplayMessage() { lock (msgQueueLock) { foreach (var msgStr in _messagesWithFormat) { Console.WriteLine(msgStr); } } } void Seperate() { int width = 30; while (width > 0) { System.Console.Write("-"); width--; } System.Console.WriteLine(""); } void DisplayInput() { int count = _input.Count; for (int i = 0; i < count; i++) { Console.Write((char)_input[i]); } Console.WriteLine(""); } public void AppendMessage(string str) { lock (msgQueueLock) { if (_messagesWithFormat.Count > csharp_client.Config.max_message_amount_display) { _messagesWithFormat.Dequeue(); } _messagesWithFormat.Enqueue(str); _needRefresh = true; } } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Domain { public class Todo { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public string Title { get; set; } public bool completed { get; set; } public string Description { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace task1_Count_Working_Days { public class task1_Count_Working_Days { public static void Main() { var input = Console.ReadLine(); var startDate = DateTime.ParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture); input = Console.ReadLine(); var endDate = DateTime.ParseExact(input, "dd-MM-yyyy", CultureInfo.InvariantCulture); var officialHolidays = new [] { "01-01", "03-03", "01-05", "06-05", "24-05", "06-09", "22-09", "01-11", "24-12", "25-12", "26-12" }.Select(a => DateTime.ParseExact(a, "dd-MM", CultureInfo.InvariantCulture)); int countDay = 0; for (DateTime currentDate = startDate; currentDate <= endDate; currentDate = currentDate.AddDays(1)) { if (currentDate.DayOfWeek != DayOfWeek.Saturday && currentDate.DayOfWeek != DayOfWeek.Sunday && !(officialHolidays.Any(d => d.Day == currentDate.Day && d.Month == currentDate.Month))) { countDay++; } } Console.WriteLine(countDay); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Max_Sequence_of_Equal_Elements { class Program { static void Main(string[] args) { int[] arr = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); int increasing = 1; int temp = 1; int start = 0; int resultstart = 0; for (int i = 1; i < arr.Length ; i++) { if (arr[i] > arr[i - 1]) { temp++; if (temp > increasing) { increasing = temp; resultstart = start; } } else { start = i; temp = 1; } } for (int i = resultstart; i < resultstart + increasing; i++) { Console.Write(arr[i] + " "); } } } }
using System; namespace Euler_Logic.Problems { public class Problem100 : ProblemBase { /* Brute Force results 4 3 21 15 120 85 697 493 4060 2871 23661 16731 137904 97513 803761 568345 4684660 3312555 27304197 19306983 159140520 112529341 927538921 655869061 */ /* If the total number of discs is T, the number of blue discs is A, and the probability is 50%, then the following equation is true: 0.5=(a/T)×((A-1)/(T-1)) You can rearrange the equation like so: 0.5(T*T-T)=A*A-A It can be seen that 0.5(T*T-T) is slightly less than a perfect square. If A is an integer, then the following must be true: x = 0.5(T*T-T) (int(Sqrt(x)) + 1)^2 = x (int function truncates the decimals and returns only the integer portion) We can use the above test to determine if any variable T will yield an integer A. Using this, after writing a brute force algorithm to see a list of the first few cases where this is true, it can be seen that where A is an integer, T is 5~ times the last time T had an integer for A. For example, 21 / 4 = 5.25, 120 / 21 = 5.71, 697 / 120 = 5.81. So rather than brute forcing every number, when we find a solution for T containing an integer A, we save the ratio of this T against the previons T, and then multiple this T by that ratio. This will get us close to the next one, and we begin incrementing by 1 from there until we find it. */ public override string ProblemName { get { return "100: Arranged probability"; } } public override string GetAnswer() { return Solve(2).ToString(); } private decimal Solve(decimal t) { decimal last = 1; do { decimal test = (t * t - t) / 2; decimal estimate = (ulong)Math.Sqrt((double)test) + 1; decimal final = estimate * estimate - estimate; if (test == final) { if (t > 1000000000000) { return estimate; } decimal next = ((ulong)(t * (t / last))); last = t; t = next; } else { t++; } } while (true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using TRPO_labe_3.Interfaces; using TRPO_labe_3.Utilities; namespace TRPO_labe_3.Classes.Models { public class FigureRandomer { private Random rnd; private IFactory factory; public FigureRandomer() { rnd = new Random(); } public List<IFigure> GetFigures() { List<IFigure> figures = new List<IFigure>(); for (int i = 0; i < 10; i++) { int figureSize = rnd.Next(0, 2); int type = rnd.Next(0, 7); Color color = Color.FromRgb((byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256), (byte)rnd.Next(0, 256)); IFigure figure = CreateOne(figureSize, type, color); figures.Add(figure); } return figures; } private IFigure CreateOne(int size, int type, Color color) { if (size == 0) factory = new ClassicFigureFactory(); else factory = new BigFigureFactory(); IFigure figure = factory.Create(); figure.Color = color; figure.Type = (FigureType)Enum.GetValues(typeof(FigureType)).GetValue(type); return figure; } } }
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Eevee.Models { public class Artist { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ArtistID { get; set; } [Required] public string Name { get; set; } [Required] [Display(Name = "Start Date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime StartDate { get; set; } [DataType(DataType.ImageUrl)] public string Image { get; set; } public string Description { get; set; } public int Listens { get; set; } = 0; public float Rating { get; set; } = 1.0f; public string WordVec { get; set; } } }
using SGCFT.Dominio.Entidades; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SGCFT.Apresentacao.Models { public class PerguntaViewModel { public int Id { get; set; } [Required(ErrorMessage = "Informe a pergunta")] public string Texto { get; set; } public int IdAutor { get; set; } [Required(ErrorMessage = "Informe o módulo")] public int IdModulo { get; set; } public List<TreinamentoViewModel> Treinamentos { get; set; } public string[] Alternativas { get; set; } public bool[] Corretos { get; set; } public Pergunta ConverterParaDominio() { Pergunta pergunta = new Pergunta(this.Texto, this.IdAutor,this.IdModulo); return pergunta; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AppCenter; using Welic.App.Models.Usuario; using Welic.App.Services.API; using static Welic.App.Services.API.WebApi; namespace Welic.App.Models.Schedule { public class ScheduleDto { public int ScheduleId { get; set; } public string Title { get; set; } public string Description { get; set; } public decimal Price { get; set; } public DateTime DateEvent { get; set; } public bool Private { get; set; } public bool Ativo { get; set; } public string TeacherId { get; set; } public ScheduleDto() { } private ObservableCollection<ScheduleDto> _listItem; private ObservableCollection<ScheduleDto> ListItem { get => _listItem; set => _listItem = value; } public async Task<ObservableCollection<ScheduleDto>> GetListLive() { try { var list = await WebApi.Current.GetListAsync<ScheduleDto>("Schedule/GetList"); return list; } catch (System.Exception ex) { AppCenterLog.Error("ScheduleGetListLive", $"{ex.Message}-{ex.InnerException.Message}"); return null; } } public async Task<List<ScheduleDto>> GetList(int pageIndex, int pageSize) { try { var list = await Current?.GetAsync<List<ScheduleDto>>("Schedule/GetList"); return list.Skip(pageIndex * pageSize).Take(pageSize).ToList(); } catch (System.Exception e) { AppCenterLog.Error("ScheduleGetList", $"{e.Message}-{e.InnerException.Message}"); return null; } } public async Task<ObservableCollection<ScheduleDto>> GetList() { try { _listItem = await Current?.GetAsync<ObservableCollection<ScheduleDto>>("Schedule/GetList"); return ListItem; } catch (System.Exception e) { AppCenterLog.Error("ScheduleGetLista", $"{e.Message}-{e.InnerException.Message}"); return null; } } public async Task<ObservableCollection<ScheduleDto>> GetListByUser() { try { var user = new UserDto().LoadAsync(); _listItem = await Current?.GetAsync<ObservableCollection<ScheduleDto>>($"Schedule/GetListByUser/{user.Id}"); return ListItem; } catch (System.Exception e) { AppCenterLog.Error("ScheduleGetListUser", $"{e.Message}-{e.InnerException.Message}"); return null; } } public async Task<ScheduleDto> GetListById(ScheduleDto scheduleDto) { try { return await Current?.GetAsync<ScheduleDto>($"Schedule/GetById/{scheduleDto.ScheduleId}"); } catch (System.Exception e) { AppCenterLog.Error("ScheduleGetListById", $"{e.Message}-{e.InnerException.Message}"); return null; } } public async Task<ScheduleDto> Create(ScheduleDto scheduleDto) { try { return await Current?.PostAsync<ScheduleDto>("schedule/save", scheduleDto); } catch (System.Exception e) { AppCenterLog.Error("ScheduleCreate", $"{e.Message}-{e.InnerException.Message}"); return null; } } public async Task<ScheduleDto> Edit(ScheduleDto scheduleDto) { try { return await Current?.PostAsync<ScheduleDto>("schedule/update", scheduleDto); } catch (System.Exception e) { AppCenterLog.Error("ScheduleEdit", $"{e.Message}-{e.InnerException.Message}"); return null; } } public async Task<bool> DeleteAsync(ScheduleDto scheduleDto) { try { return await Current?.DeleteAsync($"schedule/delete/{scheduleDto.ScheduleId}"); } catch (System.Exception e) { AppCenterLog.Error("ScheduleFeleteAsync", $"{e.Message}-{e.InnerException.Message}"); return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RAIN_EXAM_FINAL { class Program { static void Main(string[] args) { string input = Console.ReadLine(); var forceData = new Dictionary<string, List<string>>(); while (input != "Lumpawaroo") { if (input.Contains("|")) { string[] command = input.Split(new[] { " ", "|" }, StringSplitOptions.RemoveEmptyEntries); string forceSide = command[0]; string forceUser = command[1]; if (!forceData.ContainsKey(forceSide)) { forceData.Add(forceSide, new List<string>()); } if (!forceData[forceSide].Contains(forceUser)) { List<string> force = new List<string>(); force.Add(forceUser); forceData[forceSide] = force; } } else if (input.Contains("->")) { string[] command = input.Split(new[] { " ", "->" }, StringSplitOptions.RemoveEmptyEntries); string forceUser = command[0]; string forceSide = command[1]; if (!forceData.ContainsKey(forceSide)) { forceData.Add(forceUser, new List<string>()); } if (forceData.Values.Any(c => c.Contains(forceUser))) { foreach (var item in forceData) { if (item.Value.Contains(forceUser)) { item.Value.Remove(forceUser); } } } forceData[forceSide].Add(forceUser); Console.WriteLine($"{forceUser} joins the {forceSide} side!"); } input = Console.ReadLine(); } foreach (var item in forceData.OrderByDescending(x=>x.Value.Count).ThenBy(x=>x.Key)) { Console.WriteLine($"Side: {item.Key}, Members: {item.Value.Count}"); foreach (var i in item.Value) { Console.WriteLine("! " + i); } } } } }
using Newtonsoft.Json; using Paged; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NotNullTest { public class Program { public static void Main(string[] args) { //Console.WriteLine("aaa"); //DateTime? ad = null; // var cc=(ad)?.ToString("yyyy-MM-dd HH:mm:ss"); //Console.WriteLine("bbb"); //Console.WriteLine(cc); //Console.WriteLine("ccc"); testAsParallel(); //NullModelTest(); ////PageTest(); //extendLoadGamePrint(); //var dict = GetDict(); //Console.WriteLine("Hello World!" + dict[221] + "--" + ProductsMapper().ToList().Count() + "!!"); Console.ReadKey(); } public static async Task<IEnumerable<int>> GetRelatedChildSplitOrderIDsAsync(int orderId, bool readOnly) { List<int> relatedIDs = new List<int>(); IEnumerable<int> tempids = new List<int> { orderId }; do { relatedIDs.AddRange(tempids); var childids = await GetRelatedChildSplitOrderIDsAsync(tempids); tempids = childids; } while (tempids.Any()); return relatedIDs; } public static async Task<IEnumerable<int>> testAsParallel() { var numbers = Enumerable.Range(0, 5000); var result = numbers.AsParallel().AsOrdered().Where(i => i % 2 == 0); foreach (var i in result) Console.WriteLine(i); return numbers; } public static async Task<IEnumerable<int>> GetRelatedChildSplitOrderIDsAsync(IEnumerable<int> orderId ) { var numbers = Enumerable.Range(0, 100); var result = numbers.AsParallel().AsOrdered().Where(i => i % 2 == 0); foreach (var i in result) Console.WriteLine(i); List<int> relatedIDs = new List<int>(); IEnumerable<int> tempids = new List<int> { orderId?.FirstOrDefault()??0 }; do { relatedIDs.AddRange(tempids); var childids = relatedIDs; tempids = childids; } while (tempids.Any()); return relatedIDs; } public static void extendLoadGamePrint() { new TestProgram().loadGame(); } public static void CurrentPagerTest() { var pager = new Paged.PagerTest(); } public static void PageTest() { var list = GetPageTest(); //List<int> var c = list.OrderByDescending(x=>x); var pageSize = 99; var length = list.Count(); var pageNo = length / pageSize; var currentList = new List<int>(); for (int i = 1; i <= pageNo + 1; i++) { currentList = list.Skip((i - 1) * pageSize).Take(pageSize).ToList(); //var currentDict = await orderListManager.GetBasePriceDictAsync(currentList, orderNo, requestTracked); Console.WriteLine($"{i }---{JsonConvert.SerializeObject(currentList)}"); } } public static void NullModelTest() { Model2 mm = new Model2(); mm = null; var list = new List<Model2>(); list = null; if (!(list?.Any()?? false)) { Console.WriteLine($" null--"); } else { Console.WriteLine($"not null"); } } public static void NullStrTest() { Model2 mm = new Model2(); mm.Remark = null; var c = TestNullStr(mm); Console.WriteLine($"{c}---{JsonConvert.SerializeObject(c)}"); } public static string TestNullStr(Model2 mo) { var remark = @"UpdateBaseCost|"; if (!string.IsNullOrWhiteSpace(mo.Remark)) { var entityReamrk = mo.Remark ?? ""; if (!entityReamrk.StartsWith("UpdateBaseCost|")) { remark += entityReamrk; } } return remark; } public static List<int> GetPageTest() { var list = new List<int>(); for (int i = 0; i < 698; i++) { list.Add(i); } return list; } public static IEnumerable<int> ProductsMapper() { List<int> list = new List<int>(); var briefProducts = list.Where(x => x.ToString().Length < 3).Select(x => x).Distinct(); //var briefProducts = AutoMapper.Mapper.Map<List<PurchaseBriefProductItem>>(products); return briefProducts; } public static Dictionary<int, string> GetDict() { return new Dictionary<int, string>() { { 1,"123"}, { 3,"123"} }; } public static List<CheckList> GetItemList() { return new List<CheckList>() { new CheckList(1,5), new CheckList(1,6), new CheckList(2,5), new CheckList(2,7), new CheckList(3,5), }; } public void d() { Dictionary<int, CheckList> recountDict = new Dictionary<int, CheckList>(); var c = recountDict[0]; } } public class CheckList { public CheckList(int id, int PKID) { this.ItemId = id; this.PKID = PKID; } public virtual int PKID { get; set; } public virtual int ItemId { get; set; } public HashSet<CheckItem> Items { get; set; } public virtual int TotalNum { get; set; } public virtual decimal Cost { get; set; } public virtual decimal BaseCost { get; set; } public int Add(CheckItem item) { if (!Items.Select(x => x.POId).Contains(item.POId)) { Items.Add(item); TotalNum += item.Num; Cost += item.Cost; BaseCost += item.BaseCost; } return Items.Count; } public bool CheckFigureOut() { if (true) { } return false; } } public class CheckItem { public CheckItem(int id, int POId) { this.POId = id; this.POId = POId; } public virtual int OrderListId { get; set; } public virtual string Pid { get; set; } public virtual int Num { get; set; } public virtual int POId { get; set; } public virtual decimal Cost { get; set; } public virtual decimal BaseCost { get; set; } } }
using System.CodeDom; using InRule.Repository.RuleElements; namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.Rendering { public static partial class SdkCodeRenderingExtensions_SendMailActionDef { public static CodeObjectCreateExpression ToCodeExpression(this SendMailActionAttachmentDef def) { // public SendMailActionAttachmentDef(string argText) return typeof(SendMailActionAttachmentDef).CallCodeConstructor(def.ArgText.ToCodeExpression()); } } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Kata20170921_BreakCamelCase { [TestClass] public class BreakcamelCaseTests { [TestMethod] public void input_abc_should_return_abc() { BreakCamelCaseShouldBe("abc", "abc"); } [TestMethod] public void input_abcAbc_should_return_abcAbc() { BreakCamelCaseShouldBe("abc Abc", "abcAbc"); } [TestMethod] public void input_abcAbcAbc_should_return_abcAbc() { BreakCamelCaseShouldBe("abc Abc Abc", "abcAbcAbc"); } private static void BreakCamelCaseShouldBe(string expected, string str) { var kata = new Kata(); var actual = kata.BreakCamelCase(str); Assert.AreEqual(expected, actual); } } public class Kata { public string BreakCamelCase(string str) { return string.Concat(str.Select(c => char.IsUpper(c) ? " " + c : c.ToString())); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace DataAccessLayer.dbDTO { public class TermNetwork { [Key] public string graph { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace PingPongGame { class PingPong { static int firstPlayerPadSize = 4; static int secondPlayerPadSize = 4; static int ballPositionX = 0; static int ballPositionY = 0; static int firstPlayerPosition = 0; static int secondPlayerPosition = 0; static void RemoveScrollBars() { Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.WindowWidth; } static void DrawFIrstPlayer() { for (int y = firstPlayerPosition; y < firstPlayerPadSize - 1; y++ ) { PrintAtPosition(x, y, 'I'); } } static void PrintAtPosition(int x, int y, char'I') { Console.SetCursorPosition(x, y); PrintPosition(1, y, "I"); } static void DrawSecondPlayer() { for (int y = ) { PrintAtPosition(); } } static void DrawSecondPlayer() { } static void Main() { RemoveScrollBars(); while(true) { DrawFIrstPlayer(); DrawSecondPlayer(); // Move first player // Move second player // Move the ball // Redraw all // - clear all // - draw first player // - draw second player // - draw ball // - print result Thread.Sleep(60); } } } }
namespace _04._BasicQueueOperations { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { int[] inputParts = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int numbersToDequeue = inputParts[1]; int searchedNumber = inputParts[2]; int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); Queue<int> queue = new Queue<int>(numbers); for (int i = 0; i < numbersToDequeue; i++) { queue.Dequeue(); } if (queue.Contains(searchedNumber)) { Console.WriteLine("true"); } else if (queue.Count == 0) { Console.WriteLine(0); } else { Console.WriteLine(queue.Min()); } } } }
using System.Collections.Generic; namespace SFA.DAS.ProviderCommitments.Web.Models.Cohort { public class FileUploadReviewEmployerDetails { public string LegalEntityName { get; set; } public string AgreementId { get; set; } public string CohortRef { get; set; } public List<FileUploadReviewCohortDetail> CohortDetails { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Question : MonoBehaviour { public GameObject manager; private Answer rightAnswer; private Answer leftAnswer; public Text question; public Text rightText; public Text leftText; void SetUp(QuestionObject curr) { this.rightAnswer = new Answer(curr.right, curr.rightResult); this.leftAnswer = new Answer(curr.left, curr.leftResult); this.rightText.text = curr.rightChoice; this.leftText.text = curr.leftChoice; this.question.text = curr.question; } public void EffectClick(string Answer) { switch (Answer) { case "Right": manager.SendMessage("UpdatePlayer", rightAnswer); break; case "Left": manager.SendMessage("UpdatePlayer", leftAnswer); break; } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace HospitalSystem.Models.Mapping { public class adjust_price_recordMap : EntityTypeConfiguration<adjust_price_record> { public adjust_price_recordMap() { // Primary Key this.HasKey(t => t.AdjustPriceRecordID); // Properties // Table & Column Mappings this.ToTable("adjust_price_record", "teamwork"); this.Property(t => t.AdjustPriceRecordID).HasColumnName("AdjustPriceRecordID"); this.Property(t => t.MedicineID).HasColumnName("MedicineID"); this.Property(t => t.DoctorID).HasColumnName("DoctorID"); this.Property(t => t.MedicineOldPrice).HasColumnName("MedicineOldPrice"); this.Property(t => t.MedicineCurrentPrice).HasColumnName("MedicineCurrentPrice"); this.Property(t => t.AdjustPriceDate).HasColumnName("AdjustPriceDate"); // Relationships this.HasOptional(t => t.doctor) .WithMany(t => t.adjust_price_record) .HasForeignKey(d => d.DoctorID); this.HasOptional(t => t.medicine) .WithMany(t => t.adjust_price_record) .HasForeignKey(d => d.MedicineID); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Infrastructure.Logging { public class Logger { public Logger() { } public void Info(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { this.Log(message, LogMessageType.Info, memberName, sourceFilePath, sourceLineNumber); } public void Error(string message, Exception exception, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { this.Log(message, LogMessageType.Error, memberName, sourceFilePath, sourceLineNumber, exception); } public void Warning(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { this.Log(message, LogMessageType.Warning, memberName, sourceFilePath, sourceLineNumber); } public void Message(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { this.Log(message, LogMessageType.Message, memberName, sourceFilePath, sourceLineNumber); } private void Log(string message, LogMessageType logMessageType, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0, Exception exception = null) { } } public enum LogMessageType { Info, Error, Warning, Message } }
using System; namespace Vlc.DotNet.Core.Interops.Signatures { public enum EventTypes : int { MediaMetaChanged = 0, MediaSubItemAdded, MediaDurationChanged, MediaParsedChanged, MediaFreed, MediaStateChanged, MediaSubItemTreeAdded, MediaPlayerMediaChanged = 0x100, MediaPlayerNothingSpecial, MediaPlayerOpening, MediaPlayerBuffering, MediaPlayerPlaying, MediaPlayerPaused, MediaPlayerStopped, MediaPlayerForward, MediaPlayerBackward, MediaPlayerEndReached, MediaPlayerEncounteredError, MediaPlayerTimeChanged, MediaPlayerPositionChanged, MediaPlayerSeekableChanged, MediaPlayerPausableChanged, MediaPlayerTitleChanged, MediaPlayerSnapshotTaken, MediaPlayerLengthChanged, MediaPlayerVout, MediaPlayerScrambledChanged, MediaPlayerEsAdded, MediaPlayerEsDeleted, MediaPlayerEsSelected, MediaPlayerCorked, MediaPlayerUncorked, MediaPlayerMuted, MediaPlayerUnmuted, MediaPlayerAudioVolume, MediaPlayerAudioDevice, MediaPlayerChapterChanged, MediaListItemAdded = 0x200, MediaListWillAddItem, MediaListItemDeleted, MediaListWillDeleteItem, MediaListEndReached, MediaListViewItemAdded = 0x300, MediaListViewWillAddItem, MediaListViewItemDeleted, MediaListViewWillDeleteItem, MediaListPlayerPlayed = 0x400, MediaListPlayerNextItemSet, MediaListPlayerStopped, [Obsolete("Useless event, it will be triggered only when calling libvlc_media_discoverer_start()")] MediaDiscovererStarted = 0x500, [Obsolete("Useless event, it will be triggered only when calling libvlc_media_discoverer_stop()")] MediaDiscovererEnded, RendererDiscovererItemAdded, RendererDiscovererItemDeleted, VlmMediaAdded = 0x600, VlmMediaRemoved, VlmMediaChanged, VlmMediaInstanceStarted, VlmMediaInstanceStopped, VlmMediaInstanceStatusInit, VlmMediaInstanceStatusOpening, VlmMediaInstanceStatusPlaying, VlmMediaInstanceStatusPause, VlmMediaInstanceStatusEnd, VlmMediaInstanceStatusError } }
namespace MovieRating.Data.Configurations { using Entities; using System.Data.Entity.ModelConfiguration; public class EntityBaseConfiguration<T>:EntityTypeConfiguration<T> where T:class,IEntityBase { public EntityBaseConfiguration() { HasKey(e => e.ID); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using BuyNSell.Models; namespace BuyNSell.Controllers { public class RatingController : Controller { BuyNSell_DbEntities objDbEntities = new BuyNSell_DbEntities(); // GET: Rating public ActionResult AverageRating(int ProductId) { try { if (Session["UserId"] != null) { var SumRate = objDbEntities.RatingMasters.Where(m => m.ProductId == ProductId).Sum(m => m.Rate); var CountRate = objDbEntities.RatingMasters.Where(m => m.ProductId == ProductId).Count(); int Rate = Convert.ToInt32(SumRate / CountRate); ViewBag.ProductId = ProductId; ViewBag.Rate = Rate; ViewBag.UserCountRate = CountRate; return PartialView("_AverageRating", ProductId); } else { return RedirectToAction("Login", "Login"); } } catch (Exception ex) { throw ex; } } public ActionResult AddOwnRating(int ProductId) { try { if (Session["UserId"] != null) { int UserId = Convert.ToInt32(Session["UserId"]); Session["RatingProductId"] = ProductId; RatingMaster RatingMaster = objDbEntities.RatingMasters.Where(m => m.ProductId == ProductId && m.UserId == UserId).FirstOrDefault(); if (RatingMaster != null) { ViewBag.RatingLog = "You aleady rated this Product"; Session["RatingMaster"] = RatingMaster; ViewBag.RateLog = RatingMaster.Rate; } else { ViewBag.RatingLog = " Please Rate this Product !"; Session["RatingMaster"] = null; ViewBag.RateLog = 0; } return PartialView("_AddOwnRating"); } else { return RedirectToAction("Login", "Login"); } } catch (Exception ex) { throw ex; } } [HttpPost] public ActionResult AddOwnRating_Click(int Rate) { try { if (Session["UserId"] != null) { int UserId = Convert.ToInt32(Session["UserId"]); int RatingProductId = Convert.ToInt32(Session["RatingProductId"]); if (Session["RatingMaster"] != null) { RatingMaster RatingMaster = Session["RatingMaster"] as RatingMaster; RatingMaster objRM = objDbEntities.RatingMasters.Single(m => m.ProductId == RatingProductId && m.UserId == UserId); objRM.Rate = Rate; objRM.RatingModifiedDate = DateTime.Now; objDbEntities.SaveChanges(); } else { RatingMaster objRM = new RatingMaster(); objRM.ProductId = RatingProductId; objRM.UserId = UserId; objRM.Rate = Rate; objRM.RatingAddedDate = DateTime.Now; objRM.Active = true; objDbEntities.RatingMasters.Add(objRM); objDbEntities.SaveChanges(); } return JavaScript("fnAfter_AddOwnRating_Click()"); } else { return RedirectToAction("Login", "Login"); } } catch (Exception ex) { throw ex; } } } }
using DAL; using DAL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BL { public interface IDeclarationService { void Clear(); bool IsEdit { get; } bool CanEditDeclaration(Declaration dec); string Message { get; } Task<bool> ApplyDeclaration(); bool IsPadied { get; } /// <summary> /// Получить заполненое заявление от VM /// </summary> /// <param name="declaration"></param> void SetupFilledDeclaration(DeclarationDto declaration); /// <summary> /// Получить заполненный профиль /// </summary> /// <param name="declaration"></param> void SetupFilledProfile(ProfileDto declaration); /// <summary> /// Возвращает или существующий (при редактировании), или новый /// </summary> /// <returns></returns> DeclarationDto GetDeclaration(); int GetCost(); /// <summary> /// Возвращает или существующий (при редактировании), или новый /// </summary> /// <returns></returns> ProfileDto GetProfile(); /// <summary> /// Точка начала работы сервиса. Возращает результат, есть ли уже есть активное заявление /// </summary> /// <param name="evac">Экз. эвакуации, который нужно проверить</param> /// <returns></returns> Task<bool> SetupEvac(int evac); Task<IEnumerable<string>> GetTimesForDate(DateTime date); void DefineStatus(DecStatus decStatus); } }
using UnityEngine; using System.Collections; public class RotateAnimation : MonoBehaviour { public float rotateX = 0; public float rotateY = 0; public float rotateZ = 0; public float rotateTime = 1.0f; public float delayTime = 1.0f; public Direction direction = Direction.To; void Awake() { //ht.Add("x", moveToX); //ht.Add("y", moveToY); //ht.Add("z", moveToZ); //ht.Add("time", moveTime); //ht.Add("delay", delayTime); //ht.Add("looptype", iTween.LoopType.none); } void Start() { iTween.RotateTo(gameObject, new Vector3(rotateX, rotateY, rotateZ), rotateTime); //if (direction == Direction.To) //{ // iTween.MoveTo(gameObject, ht); //} //else //{ // iTween.MoveFrom(gameObject, ht); //} } }
using Cottle.Functions; using EddiDataDefinitions; using EddiGalnetMonitor; using EddiSpeechResponder.Service; using JetBrains.Annotations; using System; namespace EddiSpeechResponder.CustomFunctions { [UsedImplicitly] public class GalnetNewsMarkUnread : ICustomFunction { public string name => "GalnetNewsMarkUnread"; public FunctionCategory Category => FunctionCategory.Galnet; public string description => Properties.CustomFunctions_Untranslated.GalnetNewsMarkUnread; public Type ReturnType => typeof( string ); public NativeFunction function => new NativeFunction((values) => { News result = GalnetSqLiteRepository.Instance.GetArticle(values[0].AsString); if (result != null) { GalnetSqLiteRepository.Instance.MarkUnread(result); } return ""; }, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CableMan.ViewModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CableMan.View { public partial class PageTraCuuThueBao : TabbedPage { public PageTraCuuThueBao() { InitializeComponent(); BindingContext = new PageTraCuuThueBaoViewModel(TraCuuThueBao, DoKiem, MaThueBao, TenThueBao, NhapDiaChi, LocThongTin, ImgFind, MaThueBaoSuyHao, LocThongTinSuyHao, ImgFindSuyHao); } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace OwnArrayList.Core { public class PupilList { private int _nextIndex; private Pupil[] _pupils; public int Count { get { return _nextIndex; } } public int NextIndex { get { return _nextIndex; } set { _nextIndex = value; } } public PupilList() { _nextIndex = 0; _pupils = new Pupil[_nextIndex]; } public void Add(Pupil pupil) { Insert(_nextIndex, pupil); } public void RemoveAt(int index) { Remove(GetAt(index)); } public bool Remove(Pupil pupil) { bool wasSuccess; int index = 0; while (index < _pupils.Length - 1 && !pupil.Equals(_pupils[index])) { index++; } if (_pupils[index].Equals(pupil)) { for (int i = index; i < _pupils.Length - 1; i++) { _pupils[i] = _pupils[i + 1]; } _pupils[_pupils.Length - 1] = null; _nextIndex--; wasSuccess = true; } else { wasSuccess = false; } return wasSuccess; } public Pupil GetAt(int index) { return _pupils[index]; } public void Insert(int index, Pupil pupil) { if (_pupils.Length == 0)//0er-Array { _pupils = new Pupil[_nextIndex + 1]; _pupils[_nextIndex] = pupil; } else if (_pupils[_pupils.Length - 1] == null)//Leeres Ende { for (int i = _pupils.Length - 1; i > index; i--) { if (_pupils[i] != null) { _pupils[i + 1] = _pupils[i]; } } _pupils[index] = pupil; } else//Volles Ende 1,2 { int i = 0; bool wasNotInMiddle = true; Pupil[] temp = new Pupil[_pupils.Length + 1]; while (i < _pupils.Length) { temp[i] = _pupils[i]; if (i == index) { temp[i] = pupil; temp[i + 1] = _pupils[i]; i++; wasNotInMiddle = false; continue; } i++; } if (wasNotInMiddle) { temp[i] = pupil; } _pupils = temp; } _nextIndex++; } public void Sort() { int length = _pupils.Length; Pupil temp = _pupils[0]; for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { if (_pupils[i].Age > _pupils[j].Age) { temp = _pupils[i]; _pupils[i] = _pupils[j]; _pupils[j] = temp; } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Xamarin.Forms; namespace LorikeetMApp { public partial class ContactPage : ContentPage { private Data.MemberDatabase database; private static string databasePath = DependencyService.Get<Data.IFileHelper>().GetLocalFilePath("MemberSQLite.db"); private int memberID = -1; public ContactPage(int memberID) { InitializeComponent(); this.memberID = memberID; database = Data.MemberDatabase.Create(databasePath); } protected override async void OnAppearing() { base.OnAppearing(); try { ((App)App.Current).ResumeContactId = -1; listView.ItemsSource = await database.GetContactItemsAsync(memberID); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } async void OnListContactSelected(object sender, SelectedItemChangedEventArgs e) { ((App)App.Current).ResumeContactId = (e.SelectedItem as ModelsLinq.ContactSQLite).ContactId; await Navigation.PushAsync(new ContactIDPage { BindingContext = e.SelectedItem as ModelsLinq.ContactSQLite }); } } }
namespace ArquiteturaLimpaMVC.Dominio.Entidades { public abstract class Entity { public int Id { get; protected set; } protected abstract void ValidarDominio(); } }
namespace Common { public static class CO_MensajesSistema { public static string ExcepcionConsulta = "La cantidad de queries a ejecutar es mayor a los queries restantes en el programa"; public static string CantidadTest = "La cantidad de test cases a ejecutar debe ser mayor a 0 y menor a "; public static string AlMenos3Lineas = "El programa debe contener al menos 3 líneas"; public static string PrimeraLineaNumerica = "La primera línea debe ser numérica"; public static string FormatoMatriz = "Las características de la matriz deben tener el formato N M"; public static string TamañoMatriz = "El tamaño de la matriz 3D debe ser mayor a 1 y menor a "; public static string CantidadTest1 = "La cantidad de queries a ejecutar debe ser mayor a 1 y menor a "; public static string FormatoQuery = "El query a ejecutar no corresponde con el formato establecido: UPDATE x y z W, QUERY x1 y1 z1 x2 y2 z2"; public static string ValorActualizar = "El valor del valor a actualizar debe encontrarse entre "; } }