text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Data.Entity; namespace UsersApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { ApplicationContex db; public MainWindow() { InitializeComponent(); db = new ApplicationContex(); List<User> users = db.Users.ToList(); string str = ""; foreach (User user in users) str += "Login:"+ user.Login + " | "; } private void signinButton_Click(object sender, RoutedEventArgs e) { string login = loginBox.Text.Trim(); string email = emailBox.Text.Trim(' ').ToLower(); string password = passwordBox.Password; string passwordAgain = againPasswordBox.Password; if (!(email.Contains("@") && email.Contains("."))) { emailBox.ToolTip = "Введите email"; emailBox.Foreground = Brushes.Red; } else if(login.Length < 5) { loginBox.ToolTip = "Длина логина меньше 5 символов"; loginBox.Foreground = Brushes.Red; } else if (password.Length < 8) { passwordBox.ToolTip = "Пароль слабый"; passwordBox.Foreground = Brushes.Red; } else if (password != passwordAgain) { againPasswordBox.ToolTip = "Пароли не совпадают"; againPasswordBox.Foreground = Brushes.Red; } else { loginBox.ToolTip = ""; loginBox.Foreground = Brushes.Transparent; passwordBox.ToolTip = ""; passwordBox.Foreground = Brushes.Transparent; againPasswordBox.ToolTip = ""; againPasswordBox.Foreground = Brushes.Transparent; emailBox.ToolTip = ""; emailBox.ToolTip = emailBox.Foreground = Brushes.Transparent; MessageBox.Show("Молодец! Ты зарегистрирован! :)"); User user = new User(login, password, email); db.Users.Add(user); db.SaveChanges(); AuthWindow authWindow = new AuthWindow(); authWindow.Show(); Hide(); } } } }
using UnityEngine; public class Level21 : MonoBehaviour { public GameObject[] buttons; private int counter = 0; private GameObject lastGo; // Start is called before the first frame update private void Start() { ClickListener.ObjClicked += CheckClick; buttons = GameObject.FindGameObjectsWithTag("Button"); } private void OnDestroy() { ClickListener.ObjClicked -= CheckClick; } private void CheckClick(GameObject go) { ClickBehaviour clickBehaviour = go.GetComponent<ClickBehaviour>(); if (clickBehaviour.hold) { ResetTable(); return; } clickBehaviour.hold = true; if (!lastGo) { counter++; lastGo = go; return; } var goPos = go.transform.localPosition; var lastPos = lastGo.transform.localPosition; switch (lastGo.name) { case "D": if (lastPos.x == goPos.x && lastPos.y > goPos.y) { DoAction(go); } else { ResetTable(); } break; case "U": if (lastPos.x == goPos.x && lastPos.y < goPos.y) { DoAction(go); } else { ResetTable(); } break; case "R": if (lastPos.x < goPos.x && lastPos.y == goPos.y) { DoAction(go); } else { ResetTable(); } break; case "L": if (lastPos.x > goPos.x && lastPos.y == goPos.y) { DoAction(go); } else { ResetTable(); } break; case "Cross": ResetTable(); break; } CheckWin(); } private void CheckWin() { if (counter == buttons.Length) { Debug.Log("Win!"); GameManager.instance.NextLevel(); } } private void ResetTable() { lastGo = null; counter = 0; Utilites.ResetButtonsState(buttons); } public void DoAction(GameObject go) { lastGo = go; counter++; } }
using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Input.StylusPlugIns; using System.Windows.Media; namespace Client.Helpers.Paint { public class W1_DrawRectangle : W0_DrawObject { public W1_DrawRectangle(MyInkCanvas myInkCanvas) : base(myInkCanvas) { } public override void CreateNewStroke(InkCanvasStrokeCollectedEventArgs e) { InkStroke = new DrawRectangleStroke(this, e.Stroke.StylusPoints); } public override Point Draw(Point first, DrawingContext dc, StylusPointCollection points) { Point pt = (Point)points.Last(); Vector v = Point.Subtract(pt, first); if (v.Length > 4) { Rect rect = new Rect(first, v); //画轮廓 Pen pen = new Pen(colorBrush, 1.0); dc.DrawRectangle(null, pen, rect); } return first; } protected override void OnStylusDown(RawStylusInput rawStylusInput) { base.OnStylusDown(rawStylusInput); previousPoint = (Point)rawStylusInput.GetStylusPoints().First(); } protected override void OnStylusMove(RawStylusInput rawStylusInput) { StylusPointCollection stylusPoints = rawStylusInput.GetStylusPoints(); this.Reset(Stylus.CurrentStylusDevice, stylusPoints); base.OnStylusMove(rawStylusInput); } protected override void OnDraw(DrawingContext drawingContext, StylusPointCollection stylusPoints, Geometry geometry, Brush fillBrush) { Draw(previousPoint, drawingContext, stylusPoints); base.OnDraw(drawingContext, stylusPoints, geometry, brush); } } public class DrawRectangleStroke : DrawObjectStroke { public DrawRectangleStroke(W1_DrawRectangle ink, StylusPointCollection stylusPoints) : base(ink, stylusPoints) { this.RemoveDirtyStylusPoints(); } protected override void DrawCore(DrawingContext drawingContext, DrawingAttributes drawingAttributes) { base.DrawCore(drawingContext, drawingAttributes); Point pt1 = (Point)StylusPoints.First(); ink.Draw(pt1, drawingContext, StylusPoints); } } }
using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.Text; namespace gView.Drawing.Pro.Filters { class Grayscale : BaseFilter { public static readonly Grayscale BT709 = new Grayscale(0.2125, 0.7154, 0.0721); public static readonly Grayscale RMY = new Grayscale(0.5000, 0.4190, 0.0810); public static readonly Grayscale Y = new Grayscale(0.2990, 0.5870, 0.1140); public readonly double RedCoefficient; public readonly double GreenCoefficient; public readonly double BlueCoefficient; private Dictionary<PixelFormat, PixelFormat> _formatTranslations = new Dictionary<PixelFormat, PixelFormat>(); public Grayscale(double cr, double cg, double cb) { RedCoefficient = cr; GreenCoefficient = cg; BlueCoefficient = cb; _formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format8bppIndexed; _formatTranslations[PixelFormat.Format32bppRgb] = PixelFormat.Format8bppIndexed; _formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format8bppIndexed; _formatTranslations[PixelFormat.Format48bppRgb] = PixelFormat.Format16bppGrayScale; _formatTranslations[PixelFormat.Format64bppArgb] = PixelFormat.Format16bppGrayScale; } public override Dictionary<PixelFormat, PixelFormat> FormatTranslations { get { return _formatTranslations; } } protected override unsafe void ProcessFilter(BitmapData sourceData, BitmapData destinationData) { // get width and height int width = sourceData.Width; int height = sourceData.Height; PixelFormat srcPixelFormat = sourceData.PixelFormat; if ( (srcPixelFormat == PixelFormat.Format24bppRgb) || (srcPixelFormat == PixelFormat.Format32bppRgb) || (srcPixelFormat == PixelFormat.Format32bppArgb)) { int pixelSize = (srcPixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4; int srcOffset = sourceData.Stride - width * pixelSize; int dstOffset = destinationData.Stride - width; int rc = (int)(0x10000 * RedCoefficient); int gc = (int)(0x10000 * GreenCoefficient); int bc = (int)(0x10000 * BlueCoefficient); // make sure sum of coefficients equals to 0x10000 while (rc + gc + bc < 0x10000) { bc++; } // do the job byte* src = (byte*)sourceData.Scan0.ToPointer(); byte* dst = (byte*)destinationData.Scan0.ToPointer(); // for each line for (int y = 0; y < height; y++) { // for each pixel for (int x = 0; x < width; x++, src += pixelSize, dst++) { *dst = (byte)((rc * src[RGB.R] + gc * src[RGB.G] + bc * src[RGB.B]) >> 16); } src += srcOffset; dst += dstOffset; } } else { int pixelSize = (srcPixelFormat == PixelFormat.Format48bppRgb) ? 3 : 4; byte* srcBase = (byte*)sourceData.Scan0.ToPointer(); byte* dstBase = (byte*)destinationData.Scan0.ToPointer(); int srcStride = sourceData.Stride; int dstStride = destinationData.Stride; // for each line for (int y = 0; y < height; y++) { ushort* src = (ushort*)(srcBase + y * srcStride); ushort* dst = (ushort*)(dstBase + y * dstStride); // for each pixel for (int x = 0; x < width; x++, src += pixelSize, dst++) { *dst = (ushort)(RedCoefficient * src[RGB.R] + GreenCoefficient * src[RGB.G] + BlueCoefficient * src[RGB.B]); } } } } } }
using System.Collections.Generic; namespace Algorithms.LeetCode { // https://en.wikipedia.org/wiki/Gray_code public class GrayCodeTask { public IList<int> GrayCode(int n) { var result = new List<int>(); var nums = 1 << n; for (int i = 0; i < nums; i++) { int num = i ^ i >> 1; result.Add(num); } return result; } } }
using System; using System.Collections.Generic; namespace IrsMonkeyApi.Models.DB { public partial class Wizard { public Wizard() { WizardStep = new HashSet<WizardStep>(); } public int WizardId { get; set; } public int? FormId { get; set; } public int? ResolutionId { get; set; } public string Header { get; set; } public string MotivationalMessage { get; set; } public string FactsMessage { get; set; } public string Footer { get; set; } public int? ParentWizardId { get; set; } public Form Form { get; set; } public Resolution Resolution { get; set; } public ICollection<WizardStep> WizardStep { get; set; } } }
using Common; using Common.Log; using Common.Presentation; using Report.Extensions; using SessionSettings; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Windows.Forms; namespace Report { public partial class ReportForm : SkinnableModalBase { #region Private Fields private Point mCancelPt = new Point(548, 419); private string mChannel = String.Empty; private ClientPresentation mClientPresentation = new ClientPresentation(); private DataTable mDataSource = null; private DateTime? mEndDate = null; private string mExportPath = String.Empty; private Point mOKPt = new Point(12, 419); private bool mPrintToPrinter = false; private string mReportName = String.Empty; private int mSortOption = -1; private DateTime? mStartDate = null; private List<string> mStringList = new List<string>(); private Dictionary<string, DataTable> mSubreports = new Dictionary<string, DataTable>(); #endregion #region Delegates public delegate void ReportFormClosedHandler(string reportName); public delegate void ReportFormOpenedHandler(string reportName); #endregion #region Events public static event ReportFormClosedHandler ReportFormClosed; public static event ReportFormOpenedHandler ReportFormOpened; #endregion #region Constructors public ReportForm(string reportName, DataTable dataSource, ParameterStruct parameters, SkinnableFormBase owner) : base(parameters, owner) { InitializeComponent(); ApplySkin(parameters); SetCaption(reportName); mReportName = reportName; mDataSource = dataSource; Logging.ConnectionString = Settings.ConnectionString; } #endregion #region Public Properties public string Channel { set { mChannel = value; } } public DateTime? EndDate { set { mEndDate = value; } } public string ExportPath { set { mExportPath = value; } } public bool PrintToPrinter { set { mPrintToPrinter = value; } } public int SortOption { set { mSortOption = value; } } public DateTime? StartDate { set { mStartDate = value; } } public List<string> StringList { set { mStringList = value; } } public Dictionary<string, DataTable> Subreports { set { mSubreports = value; } } #endregion #region Private Methods private void Cancel_Click(object sender, EventArgs e) { Close(); } private void ExportToExcel() { string fileName = ""; if (!String.IsNullOrEmpty(mExportPath)) fileName = mExportPath; if (!ImportExport.Export(reportGrid, "Excel", ref fileName)) { Console.Beep(); MessageBox.Show("Failed to export '" + mReportName + "'.", "Fail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void OK_Click(object sender, EventArgs e) { ExportToExcel(); } private bool Render() { bool result = true; switch (mReportName) { case "BLOCK CONTENT LISTING": reportGrid.RenderBlockContentListingReport(mDataSource, mSortOption, mStartDate, mEndDate, mChannel, ref result); break; case "CAST LIST": reportGrid.RenderCastListReport(mDataSource, ref result); break; case "CLOSED-CAPTIONED TITLES": reportGrid.RenderClosedCaptionedTitlesReport(mDataSource, ref result); break; case "DAYCART REPORTS": reportGrid.RenderDaycartReport(mDataSource, mStartDate, mEndDate, ref result); break; case "MARKET ANALYSIS": reportGrid.RenderMarketingAnalysisReport(mSubreports, mStartDate, mEndDate, ref result); break; case "MASTER RECORDS AND FADS": reportGrid.RenderMasterRecordFADReport(mDataSource, mStartDate, mEndDate, ref result); break; case "MOVIE AND CLIP AIR DATES": reportGrid.RenderAccountingAirDatesReport(mDataSource, mStartDate, mEndDate, mStringList, ref result); break; case "MOVIE LISTING BY ACTOR": reportGrid.RenderMovieActorListReport(mDataSource, ref result); break; case "MOVIES WITH NO CAST/SYNOPSIS": reportGrid.RenderMovieNoCastSynopsisReport(mDataSource, ref result); break; case "REPORT USAGE": reportGrid.RenderReportUsageReport(mDataSource, ref result); break; } return result; } private void RenderReport() { statusLabel.LabelText = "Rendering '" + mReportName + "'..."; Cursor = Cursors.AppStarting; try { if (!Render()) { Console.Beep(); MessageBox.Show("Failed to render '" + mReportName + "'.", "Fail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //TODO: //If print to printer, do it. //Else do export to Excel. //DO NOT WORRY ABOUT PAGING. } catch (Exception e) { mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); } finally { Cursor = Cursors.Default; statusLabel.LabelText = "Ready"; } } private void ReportForm_FormClosing(object sender, FormClosingEventArgs e) { if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; mStringList.Clear(); if (ReportFormClosed != null) ReportFormClosed(mReportName); } private void ReportForm_Load(object sender, EventArgs e) { RenderReport(); } private void ReportForm_Shown(object sender, EventArgs e) { ok.Location = mOKPt; cancel.Location = mCancelPt; if (ReportFormOpened != null) ReportFormOpened(mReportName); } #endregion } }
using System; using System.Collections.Generic; using Conditions.Guards; using Properties.Core.Interfaces; using Properties.Core.Objects; namespace Properties.Core.Services { public class PostcodeDistrictService : IPostcodeDistrictService { private readonly IPostcodeDistrictRepository _postcodeDistrictRepository; private readonly IReferenceGenerator _referenceGenerator; public PostcodeDistrictService(IPostcodeDistrictRepository postcodeDistrictRepository, IReferenceGenerator referenceGenerator) { Check.If(postcodeDistrictRepository).IsNotNull(); Check.If(referenceGenerator).IsNotNull(); _postcodeDistrictRepository = postcodeDistrictRepository; _referenceGenerator = referenceGenerator; } public List<PostcodeDistrict> GetPostcodeDistricts(string postcodeAreaReference) { return _postcodeDistrictRepository.GetPostcodeDistricts(postcodeAreaReference); } public PostcodeDistrict GetPostcodeDistrict(string postcodeAreaReference, string postcodeDistrictReference) { return _postcodeDistrictRepository.GetPostcodeDistrict(postcodeAreaReference, postcodeDistrictReference); } public string CreatePostcodeDistrict(string postcodeAreaReference, PostcodeDistrict postcodeDistrict) { Check.If(postcodeAreaReference).IsNotNullOrEmpty(); Check.If(postcodeDistrict).IsNotNull(); var result = _postcodeDistrictRepository.CreatePostcodeDistrict(postcodeAreaReference, postcodeDistrict.CreateReference(_referenceGenerator)); return result ? postcodeDistrict.PostcodeDistrictReference : null; } public bool UpdatePostcodeDistrict(string postcodeAreaReference, string postcodeDistrictReference, PostcodeDistrict postcodeDistrict) { Check.If(postcodeAreaReference).IsNotNullOrEmpty(); Check.If(postcodeDistrictReference).IsNotNullOrEmpty(); Check.If(postcodeDistrict).IsNotNull(); return _postcodeDistrictRepository.UpdatePostcodeDistrict(postcodeAreaReference, postcodeDistrictReference, postcodeDistrict); } public bool DeletePostcodeDistrict(string postcodeAreaReference, string postcodeDistrictReference) { Check.If(postcodeAreaReference).IsNotNullOrEmpty(); Check.If(postcodeDistrictReference).IsNotNullOrEmpty(); return _postcodeDistrictRepository.DeletePostcodeDistrict(postcodeAreaReference, postcodeDistrictReference); } } }
using System.Windows; using System.Windows.Media; namespace Crystal.Plot2D.Charts { public abstract class ViewportPolylineBase : ViewportShape { protected ViewportPolylineBase() { } #region Properties /// <summary> /// Gets or sets the points in Viewport coordinates, that form the line. /// </summary> /// <value>The points.</value> public PointCollection Points { get { return (PointCollection)GetValue(PointsProperty); } set { SetValue(PointsProperty, value); } } /// <summary> /// Identifies the Points dependency property. /// </summary> public static readonly DependencyProperty PointsProperty = DependencyProperty.Register( "Points", typeof(PointCollection), typeof(ViewportPolylineBase), new FrameworkPropertyMetadata(new PointCollection(), OnPropertyChanged)); protected static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ViewportPolylineBase polyline = (ViewportPolylineBase)d; PointCollection currentPoints = (PointCollection)e.NewValue; polyline.UpdateUIRepresentation(); } /// <summary> /// Gets or sets the fill rule of polygon or polyline. /// </summary> /// <value>The fill rule.</value> public FillRule FillRule { get { return (FillRule)GetValue(FillRuleProperty); } set { SetValue(FillRuleProperty, value); } } public static readonly DependencyProperty FillRuleProperty = DependencyProperty.Register( "FillRule", typeof(FillRule), typeof(ViewportPolylineBase), new FrameworkPropertyMetadata(FillRule.EvenOdd, OnPropertyChanged)); #endregion private readonly PathGeometry geometry = new(); protected PathGeometry PathGeometry { get { return geometry; } } protected sealed override Geometry DefiningGeometry { get { return geometry; } } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace ProyectoSCA_Navigation.Clases { public class BeneficiarioNormal : Beneficiario { float porcentajeAportaciones_; public float porcentajeAportaciones { get { return this.porcentajeAportaciones_; } set { this.porcentajeAportaciones_ = value; } } float porcentajeSeguros_; public float porcentajeSeguros { get { return this.porcentajeSeguros_; } set { this.porcentajeSeguros_ = value; } } } }
using System; using System.Collections.Generic; using System.Text; namespace AppointmentManagement.Entities.Concrete { public class PostedType { public string Id { get; set; } public string PostedTypeDesc { get; set; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace GenSpriteMap { class Program { static void Main(string[] args) { int dim = 512; var spriteSheet = new Bitmap(dim, dim, PixelFormat.Format32bppArgb); var g = Graphics.FromImage(spriteSheet); var areas = new List<Rectangle>(); areas.Add(new Rectangle(0, 0, spriteSheet.Width, spriteSheet.Height)); string sourcePath = "..\\..\\..\\sprites\\"; var indexLookup = new Dictionary<string, int>(); var outSprites = new SpriteOutput(); foreach (string file in Directory.EnumerateFiles(sourcePath, "*.png")) { indexLookup[file.Replace(sourcePath, "").Replace(".png", "")] = indexLookup.Count; bool placed = false; var img = Image.FromFile(file); var outerSize = new Point(img.Width + 2, img.Height + 2); for (int i = 0; i < areas.Count && !placed; i++) { var area = areas[i]; if (outerSize.X <= area.Width && outerSize.Y <= area.Height) { outSprites.areas.Add(new SpriteOutArea { x = area.X + 1, y = area.Y + 1, width = img.Width, height = img.Height }); // Top-left pixel g.DrawImage(img, new Rectangle(area.Location, new Size(1, 1)), new Rectangle(0, 0, 1, 1), GraphicsUnit.Pixel); // Top-right pixel g.DrawImage(img, new Rectangle(area.Location.X + img.Width + 1, area.Location.Y, 1, 1), new Rectangle(img.Width - 1, 0, 1, 1), GraphicsUnit.Pixel); // Bottom-left pixel g.DrawImage(img, new Rectangle(area.Location.X, area.Location.Y + img.Height + 1, 1, 1), new Rectangle(0, img.Height - 1, 1, 1), GraphicsUnit.Pixel); // Bottom-right pixel g.DrawImage(img, new Rectangle(area.Location.X + img.Width + 1, area.Location.Y + img.Height + 1, 1, 1), new Rectangle(img.Width - 1, img.Height - 1, 1, 1), GraphicsUnit.Pixel); // Top row g.DrawImage(img, new Rectangle(area.Location.X + 1, area.Location.Y, img.Width, 1), new Rectangle(0, 0, img.Width, 1), GraphicsUnit.Pixel); // Left row g.DrawImage(img, new Rectangle(area.Location.X, area.Location.Y + 1, 1, img.Height), new Rectangle(0, 0, 1, img.Height), GraphicsUnit.Pixel); // Right row g.DrawImage(img, new Rectangle(area.Location.X + img.Width + 1, area.Location.Y + 1, 1, img.Height), new Rectangle(img.Width - 1, 0, 1, img.Height), GraphicsUnit.Pixel); // Bottom row g.DrawImage(img, new Rectangle(area.Location.X + 1, area.Location.Y + img.Height + 1, img.Width, 1), new Rectangle(0, img.Height - 1, img.Width, 1), GraphicsUnit.Pixel); // Main image g.DrawImage(img, area.Location.X + 1, area.Location.Y + 1, img.Size.Width, img.Size.Height); areas.RemoveAt(i); if (outerSize.Y < area.Height) { areas.Insert(i, new Rectangle(area.X, area.Y + outerSize.Y, area.Width, area.Height - outerSize.Y)); } if (outerSize.X < area.Width) { areas.Insert(i, new Rectangle(area.X + outerSize.X, area.Y, area.Width - outerSize.X, outerSize.Y)); } placed = true; } } if (!placed) { throw new Exception(file + " won't fit!"); } } var inSprites = JsonConvert.DeserializeObject<List<SpriteInput>>(File.ReadAllText(sourcePath + "sprites.json")); outSprites.sprites = inSprites.Select(i => new SpriteOutItem { name = i.name, indices = i.frames.Select(f => indexLookup[f]).ToList(), frameRate = i.frameRate, looped = i.looped, flipX = i.flipX, flipY = i.flipY }).ToList(); spriteSheet.Save("..\\..\\..\\..\\assets\\images\\sprites.png", ImageFormat.Png); File.WriteAllText("..\\..\\..\\..\\assets\\data\\sprites.json", JsonConvert.SerializeObject(outSprites, Formatting.Indented)); Console.WriteLine("Done, press any key..."); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CommandTimer : MonoBehaviour { public delegate void OnCompleted(); public delegate void OnUpdate(float t); /// <summary> /// 创建一个计时器 /// </summary> /// <param name="timerName">计时器名字</param> /// <returns></returns> public static CommandTimer CreateTimer(string timerName="Timer") { CommandTimer timer = new GameObject(timerName).AddComponent<CommandTimer>(); return timer; } OnCompleted onCompleted;//计时完成事件 OnUpdate onUpdate;//计时中事件,可以获得剩余时间 float startTime;//开始时间 float curTime;//现在时间 float leftTime;//剩余时间 bool isTimer;//是否开始计时 bool isDestory;//是否要摧毁 // Update is called once per frame void Update () { //出现断开连接或者急停或者痉挛,停止计时 if (!MainCore.Instance.IsMachineDisabled) { if (CommandFunctions.IsEmrgencyStop || !CommandFunctions.IsConnected || CommandFunctions.spasmState != CommandFunctions.SpasmState.NoSpasm || CommandFunctions.IsPause) return; } if (isTimer) { if (curTime < startTime) { //剩余时间 leftTime = startTime - curTime; //监听计时中 if (onUpdate != null) onUpdate(leftTime); //累加计时 curTime += Time.deltaTime; } else { if (onCompleted != null) onCompleted(); destory(); } } } /// <summary> /// 记时结束,销毁计时器 /// </summary> public void destory() { isTimer = false; if (isDestory) Destroy(gameObject); } /// <summary> /// 初始化计时器 /// </summary> /// <param name="startTime">计时器时间</param> /// <param name="onCompleted">计时完成事件</param> /// <param name="onUpdate">计时中事件</param> /// <param name="isDestory">计时完是否要摧毁</param> public void StartTimer(float startTime,OnCompleted onCompleted=null,OnUpdate onUpdate=null,bool isDestory=true) { this.startTime = startTime; leftTime = startTime; curTime = 0; if (onCompleted != null) this.onCompleted = onCompleted; if (onUpdate != null) this.onUpdate = onUpdate; this.isDestory = isDestory; isTimer = true; } /// <summary> /// 暂停计时器 /// </summary> public void PauseTimer() { if (isTimer) isTimer = false; } /// <summary> /// 继续开始计时器 /// </summary> public void ContinueTimer() { if (!isTimer) isTimer = true; } }
namespace Model.EF { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("TaiKhoan")] public partial class TaiKhoan { [Key] public int MaTK { get; set; } [StringLength(100)] public string Hoten { get; set; } [StringLength(50)] public string Email { get; set; } public int? SDT { get; set; } [StringLength(50)] public string Fb { get; set; } [StringLength(50)] public string DiaChi { get; set; } [StringLength(50)] public string Quyen { get; set; } [StringLength(50)] public string Username { get; set; } [StringLength(50)] public string Password { get; set; } public bool? Status { get; set; } [Column(TypeName = "date")] public DateTime? NgayTao { get; set; } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Reflection; using Phenix.Core.Dictionary; using Phenix.Core.Log; using Phenix.Core.Security; using Phenix.Services.Host.Core; namespace Phenix.Services.Host.Service { public sealed class DataSecurity : MarshalByRefObject, IDataSecurity { #region 属性 public bool AllowUserMultipleAddressLogin { get { ServiceManager.CheckActive(); return DataSecurityHub.AllowUserMultipleAddressLogin; } } public int SessionExpiresMinutes { get { ServiceManager.CheckActive(); return DataSecurityHub.SessionExpiresMinutes; } } public bool EmptyRolesIsDeny { get { ServiceManager.CheckActive(); return DataSecurityHub.EmptyRolesIsDeny; } } public bool EasyAuthorization { get { ServiceManager.CheckActive(); return DataSecurityHub.EasyAuthorization; } } #endregion #region 事件 internal static event Action<DataSecurityEventArgs> Changed; private static void OnChanged(DataSecurityEventArgs e) { Action<DataSecurityEventArgs> action = Changed; if (action != null) action(e); } #endregion #region 方法 public IDictionary<string, RoleInfo> GetRoleInfos(UserIdentity identity) { ServiceManager.CheckIn(identity); DataSecurityContext context = DataSecurityHub.CheckIn(identity, false); return DataSecurityHub.GetRoleInfos(context.Identity); } public IDictionary<string, RoleInfo> GetGrantRoleInfos(UserIdentity identity) { ServiceManager.CheckIn(identity); DataSecurityContext context = DataSecurityHub.CheckIn(identity, false); return DataSecurityHub.GetGrantRoleInfos(context.Identity); } public IDictionary<string, SectionInfo> GetSectionInfos(UserIdentity identity) { ServiceManager.CheckIn(identity); DataSecurityContext context = DataSecurityHub.CheckIn(identity, false); return DataSecurityHub.GetSectionInfos(context.Identity); } public IDictionary<string, IIdentity> GetIdentities(long departmentId, IList<long> positionIds, UserIdentity identity) { ServiceManager.CheckIn(identity); DataSecurityContext context = DataSecurityHub.CheckIn(identity, false); return DataSecurityHub.GetIdentities(departmentId, positionIds, context.Identity); } public DataSecurityContext CheckIn(UserIdentity identity, bool reset) { ServiceManager.CheckActive(); OnChanged(new DataSecurityEventArgs(identity.LocalAddress, identity.UserNumber, true)); return DataSecurityHub.CheckIn(identity, reset); } public DataSecurityContext CheckIn(string localAddress, string servicesAddress, string userNumber, string timestamp, string signature, bool reset) { ServiceManager.CheckActive(); OnChanged(new DataSecurityEventArgs(localAddress, userNumber, true)); return DataSecurityHub.CheckIn(localAddress, servicesAddress, userNumber, timestamp, signature, reset); } public bool? LogOnVerify(string userNumber, string tag) { ServiceManager.CheckActive(); return DataSecurityHub.LogOnVerify(userNumber, tag); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Runtime.Remoting.Messaging.OneWay] public void LogOff(UserIdentity identity) { try { OnChanged(new DataSecurityEventArgs(identity, false)); DataSecurityHub.LogOff(identity); } catch (Exception ex) { EventLog.SaveLocal(MethodBase.GetCurrentMethod(), String.Format("{0}-{1}", identity.LocalAddress, identity.UserNumber), ex); } } public bool ChangePassword(string newPassword, UserIdentity identity) { ServiceManager.CheckActive(); OnChanged(new DataSecurityEventArgs(identity, true)); return DataSecurityHub.ChangePassword(newPassword, false, identity); } public bool UnlockPassword(string userNumber, UserIdentity identity) { ServiceManager.CheckActive(); return DataSecurityHub.UnlockPassword(userNumber, identity); } public bool ResetPassword(string userNumber, UserIdentity identity) { ServiceManager.CheckActive(); return DataSecurityHub.ResetPassword(userNumber, identity); } public void SetProcessLockInfo(string processName, string caption, bool toLocked, TimeSpan expiryTime, string remark, UserIdentity identity) { ServiceManager.CheckIn(identity); DataSecurityContext context = DataSecurityHub.CheckIn(identity, false); DataSecurityHub.SetProcessLockInfo(processName, caption, toLocked, expiryTime, remark, context.Identity); } public ProcessLockInfo GetProcessLockInfo(string processName, UserIdentity identity) { ServiceManager.CheckIn(identity); DataSecurityContext context = DataSecurityHub.CheckIn(identity, false); return DataSecurityHub.GetProcessLockInfo(processName, context.Identity); } #region 应用服务不支持传事务 public void AddUser(DbTransaction transaction, long id, string userName, string userNumber, string password) { throw new NotSupportedException(MethodBase.GetCurrentMethod().Name); } public bool ChangePassword(DbTransaction transaction, string userNumber, string newPassword) { throw new NotSupportedException(MethodBase.GetCurrentMethod().Name); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Utilities; namespace EddiDataDefinitions { public class SignalSource : ResourceBasedLocalizedEDName<SignalSource> { static SignalSource() { resourceManager = Properties.SignalSource.ResourceManager; resourceManager.IgnoreCase = true; missingEDNameHandler = edname => new SignalSource(edname); UnidentifiedSignalSource = new SignalSource("USS"); GenericSignalSource = new SignalSource("GenericSignalSource"); var NavBeacon = new SignalSource("MULTIPLAYER_SCENARIO42_TITLE"); var CompromisedNavBeacon = new SignalSource("MULTIPLAYER_SCENARIO80_TITLE"); var ResourceExtraction = new SignalSource("MULTIPLAYER_SCENARIO14_TITLE"); var ResourceExtractionLow = new SignalSource("MULTIPLAYER_SCENARIO77_TITLE"); var ResourceExtractionHigh = new SignalSource("MULTIPLAYER_SCENARIO78_TITLE"); var ResourceExtractionHazardous = new SignalSource("MULTIPLAYER_SCENARIO79_TITLE"); var SalvageableWreckage = new SignalSource("MULTIPLAYER_SCENARIO81_TITLE"); var CombatZoneHigh = new SignalSource("Warzone_PointRace_High"); var CombatZoneMedium = new SignalSource("Warzone_PointRace_Med"); var CombatZoneLow = new SignalSource("Warzone_PointRace_Low"); var CombatZoneThargoid = new SignalSource("Warzone_TG"); var CombatZoneThargoidHigh = new SignalSource("Warzone_TG_High"); var CombatZoneThargoidMedium = new SignalSource("Warzone_TG_Med"); var CombatZoneThargoidLow = new SignalSource("Warzone_TG_Low"); var CombatZoneThargoidVeryHigh = new SignalSource("Warzone_TG_VeryHigh"); var Aftermath = new SignalSource("USS_Type_Aftermath", "USS_SalvageHaulageWreckage"); var Anomaly = new SignalSource("USS_Type_Anomaly"); var Ceremonial = new SignalSource("USS_Type_Ceremonial", "USS_CeremonialComms"); var Convoy = new SignalSource("USS_Type_Convoy", "USS_ConvoyDispersalPattern"); var DegradedEmissions = new SignalSource("USS_Type_Salvage", "USS_DegradedEmissions"); var Distress = new SignalSource("USS_Type_DistressSignal", "USS_DistressCall"); var EncodedEmissions = new SignalSource("USS_Type_ValuableSalvage"); var HighGradeEmissions = new SignalSource("USS_Type_VeryValuableSalvage", "USS_HighGradeEmissions"); var MissionTarget = new SignalSource("USS_Type_MissionTarget"); var NonHuman = new SignalSource("USS_Type_NonHuman", "USS_NonHumanSignalSource"); var TradingBeacon = new SignalSource("USS_Type_TradingBeacon", "USS_TradingBeacon"); var WeaponsFire = new SignalSource("USS_Type_WeaponsFire", "USS_WeaponsFire"); var UnregisteredCommsBeacon = new SignalSource("NumberStation"); var ListeningPost = new SignalSource("ListeningPost"); var CapShip = new SignalSource("FIXED_EVENT_CAPSHIP"); var Checkpoint = new SignalSource("FIXED_EVENT_CHECKPOINT"); var ConvoyBeacon = new SignalSource("FIXED_EVENT_CONVOY"); var DebrisField = new SignalSource("FIXED_EVENT_DEBRIS"); var DistributionCenter = new SignalSource("FIXED_EVENT_DISTRIBUTIONCENTRE"); var PirateAttackT5 = new SignalSource("FIXED_EVENT_HIGHTHREATSCENARIO_T5"); var PirateAttackT6 = new SignalSource("FIXED_EVENT_HIGHTHREATSCENARIO_T6"); var PirateAttackT7 = new SignalSource("FIXED_EVENT_HIGHTHREATSCENARIO_T7"); var NotableStellarPhenomenaCloud = new SignalSource("Fixed_Event_Life_Cloud"); var NotableStellarPhenomenaRing = new SignalSource("Fixed_Event_Life_Ring"); var AttackAftermath = new SignalSource("AttackAftermath"); var AftermathLarge = new SignalSource("Aftermath_Large"); var Biological = new SignalSource("SAA_SignalType_Biological"); var Geological = new SignalSource("SAA_SignalType_Geological"); var Guardian = new SignalSource("SAA_SignalType_Guardian"); var Human = new SignalSource("SAA_SignalType_Human"); var Thargoid = new SignalSource("SAA_SignalType_Thargoid"); var PlanetAnomaly = new SignalSource("SAA_SignalType_PlanetAnomaly"); var Other = new SignalSource("SAA_SignalType_Other"); var AncientGuardianRuins = new SignalSource("Ancient"); var GuardianStructureTiny = new SignalSource("Ancient_Tiny"); var GuardianStructureSmall = new SignalSource("Ancient_Small"); var GuardianStructureMedium = new SignalSource("Ancient_Medium"); var ThargoidBarnacle = new SignalSource("Settlement_Unflattened_Unknown"); var ThargoidCrashSite = new SignalSource("Settlement_Unflattened_WreckedUnknown"); var AbandonedBuggy = new SignalSource("Abandoned_Buggy"); var ActivePowerSource = new SignalSource("Perimeter"); var CrashedShip = new SignalSource("CrashedShip"); var DamagedEagleAssassination = new SignalSource("Damaged_Eagle_Assassination"); var DamagedSidewinderAssassination = new SignalSource("Damaged_Sidewinder_Assassination"); var DamagedEagle = new SignalSource("Damaged_Eagle"); var DamagedSidewinder = new SignalSource("Damaged_Sidewinder"); var SmugglersCache = new SignalSource("Smugglers_Cache"); var Cargo = new SignalSource("Cargo"); var TrapCargo = new SignalSource("Trap_Cargo"); var TrapData = new SignalSource("Trap_Data"); var WreckageAncientProbe = new SignalSource("Wreckage_AncientProbe"); var WreckageBuggy = new SignalSource("Wreckage_Buggy"); var WreckageCargo = new SignalSource("Wreckage_Cargo"); var WreckageProbe = new SignalSource("Wreckage_Probe"); var WreckageSatellite = new SignalSource("Wreckage_Satellite"); var WrecksEagle = new SignalSource("Wrecks_Eagle"); var WrecksSidewinder = new SignalSource("Wrecks_Sidewinder"); var ArmedRevolt = new SignalSource("Gro_controlScenarioTitle"); } public static readonly SignalSource UnidentifiedSignalSource; public static readonly SignalSource GenericSignalSource; public int index; public string spawningFaction { get; set; } public DateTime? expiry { get; set; } public int? threatLevel { get; set; } public bool? isStation { get; set; } public FactionState spawningState { get; set; } public long? systemAddress { get; set; } // Not intended to be user facing public string altEdName { get; private set; } // dummy used to ensure that the static constructor has run public SignalSource() : this("") { } private SignalSource(string edname, string altEdName = null) : base(edname, edname) { this.altEdName = altEdName; } public static new SignalSource FromEDName(string from) { if (from == null) return null; if (!from.Contains("$")) { // Appears to be a simple proper name return new SignalSource(from) { fallbackInvariantName = from, fallbackLocalizedName = from }; } SignalSource result = null; int? threatLvl = null; int indexResult = 0; // Signal names can mix symbolic and proper names, e.g. "INV Audacious Dream $Warzone_TG_Med;", // so use regex to separate any symbolic names from proper names. var regex = new Regex("\\$.*;"); var match = regex.Match(from); if (match.Success && from.Length > match.Value.Length) { // This appears to be a mixed name, look for the symbolic portion only then // prepend and append any proper names that were previously set aside var symbolicFrom = match.Value; var symbolicResult = FromEDName(symbolicFrom.Trim()); result = new SignalSource(from.Replace(symbolicFrom, symbolicResult.invariantName).Trim()) { fallbackInvariantName = from.Replace(symbolicFrom, symbolicResult.invariantName).Trim(), fallbackLocalizedName = from.Replace(symbolicFrom, symbolicResult.localizedName).Trim() }; } else { string tidiedFrom = from .Replace("$", "") .Replace(";", "") .Replace("_name", ""); // Remove various prefix and suffix tags from non-USS sources if (!tidiedFrom.StartsWith("USS_")) { tidiedFrom = tidiedFrom .Replace("POI_", "") .Replace("POIScenario_", "") .Replace("POIScene_", "") .Replace("Watson_", "") .Replace("_Heist", "") .Replace("_Salvage", "") .Replace("_Skimmers", ""); } // Extract any sub-type from the name (e.g. $SAA_Unknown_Signal:#type=$SAA_SignalType_Geological;:#index=3; ) if (tidiedFrom.Contains(":#type=")) { string[] fromArray = tidiedFrom.Split(new[] { ":#type=" }, System.StringSplitOptions.None); tidiedFrom = fromArray[1]; } // Extract any threat value which might be present and then strip the index value if (tidiedFrom.Contains("USS_ThreatLevel:#threatLevel=")) { string[] fromArray = tidiedFrom.Split(new[] { "USS_ThreatLevel:#threatLevel=" }, System.StringSplitOptions.None); if (int.TryParse(fromArray[1], out var threat)) { threatLvl = threat; } tidiedFrom = fromArray[0] .Replace("_Easy", "") .Replace("_Medium", "") .Replace("_Hard", ""); } else { // Derive threat levels for Odyssey content from "Easy", "Medium", and "Hard" suffix tags if (tidiedFrom.Contains("_Easy")) { threatLvl = 1; tidiedFrom = tidiedFrom.Replace("_Easy", ""); } else if (tidiedFrom.Contains("_Medium") && !tidiedFrom.StartsWith("Ancient_")) { // We need to use size to distinguish between guardian structures so preserve the "Medium" tag // when it represents the size of an ancient guardian structures. Remove it when it describes the difficulty of the encounter. threatLvl = 2; tidiedFrom = tidiedFrom.Replace("_Medium", ""); } else if (tidiedFrom.Contains("_Hard")) { threatLvl = 3; tidiedFrom = tidiedFrom.Replace("_Hard", ""); } } // Extract any index value which might be present and then strip the index value if (tidiedFrom.Contains(":#index=")) { string[] fromArray = tidiedFrom.Split(new[] { ":#index=" }, System.StringSplitOptions.None); if (int.TryParse(fromArray[1], out indexResult)) { } tidiedFrom = fromArray[0]; } // Extract any pure number parts (e.g. '_01_') var parts = new List<string>(); foreach (var part in tidiedFrom.Split(new[] { "_" }, StringSplitOptions.None)) { if (int.TryParse(part, out _)) { } else { parts.Add(part); } } tidiedFrom = string.Join("_", parts); // Use the USS Type for USS signals (since those are always unique) // There is an FDev bug where both Encoded Emissions and High Grade Emissions use the `USS_HighGradeEmissions` symbol. if (tidiedFrom.StartsWith("USS_") && !tidiedFrom.Contains("Type_")) { tidiedFrom = AllOfThem.FirstOrDefault(s => s.altEdName == tidiedFrom)?.edname ?? tidiedFrom; } // Find our signal source if (AllOfThem.Any(s => s.edname.Equals(tidiedFrom.Trim(), StringComparison.InvariantCultureIgnoreCase))) { result = ResourceBasedLocalizedEDName<SignalSource>.FromEDName(tidiedFrom.Trim()); } else { // There is no match, return a generic result result = GenericSignalSource; Logging.Warn($"Unknown ED name {from} in resource {resourceManager.BaseName}."); } } // Include our index value with our result result.index = indexResult; result.threatLevel = threatLvl; return result; } public static SignalSource FromStationEDName(string from) { if (string.IsNullOrEmpty(from)) { return null; } // Signal might be a fleet carrier with name and carrier id in a single string. If so, we break them apart var fleetCarrierRegex = new Regex("^(.+)(?> )([A-Za-z0-9]{3}-[A-Za-z0-9]{3})$"); if (fleetCarrierRegex.IsMatch(from)) { // Fleet carrier names include both the carrier name and carrier ID, we need to separate them var fleetCarrierParts = fleetCarrierRegex.Matches(from)[0].Groups; if (fleetCarrierParts.Count == 3) { var fleetCarrierName = fleetCarrierParts[2].Value; var fleetCarrierLocalizedName = fleetCarrierParts[1].Value; return new SignalSource(fleetCarrierName) { fallbackLocalizedName = fleetCarrierLocalizedName, isStation = true}; } } return new SignalSource(from) {isStation = true}; } } }
namespace Apache.Shiro.Util { public interface IFactory<T> { T Instance { get; } } }
using DrivingSchool_Api; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Services.Interfaces { public interface IBookingTypeService { void Add(BookingType bookingType); void Update(BookingType bookingType); void Delete(int? bkTId); IQueryable<BookingType> GatAll(); BookingType GetSingle(int? bkTId); } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public sealed class StateMachine<TLabel> { private class State { public readonly Action onStart; public readonly Action onExecute; public readonly Action onStop; public readonly TLabel label; public State(TLabel label, Action onStart, Action onExecute, Action onStop) { this.onStart = onStart; this.onExecute = onExecute; this.onStop = onStop; this.label = label; } } private readonly Dictionary<TLabel, State> stateDictionary; private State currentState; public TLabel CurrentState { get { return currentState.label; } set { ChangeState(value); } } private State beforeTheState; public TLabel BeforeTheState { get { return beforeTheState.label; } } public StateMachine() { stateDictionary = new Dictionary<TLabel, State>(); } //注册一个新状态到字典里 public void AddState(TLabel label,IStateMethod state_Method) { stateDictionary[label] = new State(label, state_Method.OnEnter, state_Method.OnExecute, state_Method.OnExit); } //切换状态 private void ChangeState(TLabel newState) { if (currentState != null && currentState.onStop != null) { currentState.onStop(); } beforeTheState = currentState; currentState = stateDictionary[newState]; if (currentState.onStart != null) { currentState.onStart(); } } //执行状态,每帧执行 public void Update() { if (currentState != null && currentState.onExecute != null) { currentState.onExecute(); } } }
using UnityEngine; using System.Collections; public interface ISaveAndloadClient { void OnSave();//this event will call just befor save operation start. void OnLoad();//this event will call just after load operation finished. }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HotelManagement.DataObject; using HotelManagement.BusinessObject; using System.Windows.Forms; using System.Data; namespace HotelManagement.Controller { public class ThanhToanControl { ThanhToanData data = new ThanhToanData(); BindingSource bs = new BindingSource(); public void HienThi(DataGridView dgv, BindingNavigator bn) { BindingSource bs = new BindingSource(); bs.DataSource = data.LoadTraPhongData(); dgv.DataSource = bs; bn.BindingSource = bs; } public float LayDoanhThuBaoCaoPhong(string id, int thang, int nam) { float tongDoanhThuThang = 0; DataTable dt = data.LayThongTinBaoCaoPhong(id, thang ,nam); for (int i = 0; i < dt.DefaultView.Count; i++) { tongDoanhThuThang += Convert.ToSingle(dt.Rows[i]["TongTien"]); } return tongDoanhThuThang; } public DataRow NewRow() { return data.NewRow(); } public void Add(DataRow row) { data.Add(row); } public bool Save() { return data.Save(); } } }
//------------------------------------------------------------------------------ // <copyright file="GestureDetector.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Samples.Kinect.DiscreteGestureBasics { using System; using System.Collections.Generic; using Microsoft.Kinect.VisualGestureBuilder; using WindowsPreview.Kinect; /// <summary> /// Gesture Detector class which listens for VisualGestureBuilderFrame events from the service /// and updates the associated GestureResultView object with the latest results for the 'Seated' gesture /// </summary> public class GestureDetector : IDisposable { /// <summary> Path to the gesture database that was trained with VGB </summary> private readonly string gestureDatabase = @"Database\Seated.gbd"; /// <summary> Name of the discrete gesture in the database that we want to track </summary> private readonly string seatedGestureName = "Seated"; /// <summary> Gesture frame source which should be tied to a body tracking ID </summary> private VisualGestureBuilderFrameSource vgbFrameSource = null; /// <summary> Gesture frame reader which will handle gesture events coming from the sensor </summary> private VisualGestureBuilderFrameReader vgbFrameReader = null; /// <summary> /// Initializes a new instance of the GestureDetector class along with the gesture frame source and reader /// </summary> /// <param name="kinectSensor">Active sensor to initialize the VisualGestureBuilderFrameSource object with</param> /// <param name="gestureResultView">GestureResultView object to store gesture results of a single body to</param> public GestureDetector(KinectSensor kinectSensor, GestureResultView gestureResultView) { if (kinectSensor == null) { throw new ArgumentNullException("kinectSensor"); } if (gestureResultView == null) { throw new ArgumentNullException("gestureResultView"); } this.GestureResultView = gestureResultView; // create the vgb source. The associated body tracking ID will be set when a valid body frame arrives from the sensor. this.vgbFrameSource = new VisualGestureBuilderFrameSource(kinectSensor, 0); this.vgbFrameSource.TrackingIdLost += this.Source_TrackingIdLost; // open the reader for the vgb frames this.vgbFrameReader = this.vgbFrameSource.OpenReader(); if (this.vgbFrameReader != null) { this.vgbFrameReader.IsPaused = true; this.vgbFrameReader.FrameArrived += this.Reader_GestureFrameArrived; } // load the 'Seated' gesture from the gesture database using (VisualGestureBuilderDatabase database = new VisualGestureBuilderDatabase(this.gestureDatabase)) { // we could load all available gestures in the database with a call to vgbFrameSource.AddGestures(database.AvailableGestures), // but for this program, we only want to track one discrete gesture from the database, so we'll load it by name foreach (Gesture gesture in database.AvailableGestures) { if (gesture.Name.Equals(this.seatedGestureName)) { this.vgbFrameSource.AddGesture(gesture); } } } } /// <summary> Gets the GestureResultView object which stores the detector results for display in the UI </summary> public GestureResultView GestureResultView { get; private set; } /// <summary> /// Gets or sets the body tracking ID associated with the current detector /// The tracking ID can change whenever a body comes in/out of scope /// </summary> public ulong TrackingId { get { return this.vgbFrameSource.TrackingId; } set { if (this.vgbFrameSource.TrackingId != value) { this.vgbFrameSource.TrackingId = value; } } } /// <summary> /// Gets or sets a value indicating whether or not the detector is currently paused /// If the body tracking ID associated with the detector is not valid, then the detector should be paused /// </summary> public bool IsPaused { get { return this.vgbFrameReader.IsPaused; } set { if (this.vgbFrameReader.IsPaused != value) { this.vgbFrameReader.IsPaused = value; } } } /// <summary> /// Disposes all unmanaged resources for the class /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes the VisualGestureBuilderFrameSource and VisualGestureBuilderFrameReader objects /// </summary> /// <param name="disposing">True if Dispose was called directly, false if the GC handles the disposing</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (this.vgbFrameReader != null) { this.vgbFrameReader.FrameArrived -= this.Reader_GestureFrameArrived; this.vgbFrameReader.Dispose(); this.vgbFrameReader = null; } if (this.vgbFrameSource != null) { this.vgbFrameSource.TrackingIdLost -= this.Source_TrackingIdLost; this.vgbFrameSource.Dispose(); this.vgbFrameSource = null; } } } /// <summary> /// Handles gesture detection results arriving from the sensor for the associated body tracking Id /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void Reader_GestureFrameArrived(object sender, VisualGestureBuilderFrameArrivedEventArgs e) { VisualGestureBuilderFrameReference frameReference = e.FrameReference; using (VisualGestureBuilderFrame frame = frameReference.AcquireFrame()) { if (frame != null) { // get the discrete gesture results which arrived with the latest frame IReadOnlyDictionary<Gesture, DiscreteGestureResult> discreteResults = frame.DiscreteGestureResults; if (discreteResults != null) { // we only have one gesture in this source object, but you can get multiple gestures foreach (Gesture gesture in this.vgbFrameSource.Gestures) { if (gesture.Name.Equals(this.seatedGestureName) && gesture.GestureType == GestureType.Discrete) { DiscreteGestureResult result = null; discreteResults.TryGetValue(gesture, out result); if (result != null) { // update the GestureResultView object with new gesture result values this.GestureResultView.UpdateGestureResult(true, result.Detected, result.Confidence); } } } } } } } /// <summary> /// Handles the TrackingIdLost event for the VisualGestureBuilderSource object /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void Source_TrackingIdLost(object sender, TrackingIdLostEventArgs e) { // update the GestureResultView object to show the 'Not Tracked' image in the UI this.GestureResultView.UpdateGestureResult(false, false, 0.0f); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class KcalTextController : MonoBehaviour { public Text kcalText; // Use this for initialization void Start () { } // Update is called once per frame void Update () { kcalText.text = PlayTimeController.kcal_m.ToString("f1") + "kcal/m"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BankApp.Services { public class PdfReport : Report { public PdfReport(byte[] data) : base(data) { } } }
using System; using System.Collections.Generic; using System.Text; namespace RakutenVoucherDownload.Enums { public enum EServicos { Nenhum = 1, BaixarXMLVoucher = 2 } }
using System; using Microsoft.Azure.Devices.Client; using System.Text; using Newtonsoft.Json; using System.Threading.Tasks; namespace SimulationDeviceToCloud { class Program { private static DeviceClient s_deviceClient; //Provide your hub connection string private readonly static string s_connectionString01 = ""; static void Main(string[] args) { s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString01, TransportType.Mqtt); SendDeviceToCloudMessagesAsync(s_deviceClient); Console.ReadLine(); } private static async void SendDeviceToCloudMessagesAsync(DeviceClient s_deviceClient) { try { double minTemperature = 20; double minHumidity = 60; Random rand = new Random(); while (true) { double currentTemperature = minTemperature + rand.NextDouble() * 15; double currentHumidity = minHumidity + rand.NextDouble() * 20; // Create JSON message var telemetryDataPoint = new { temperature = currentTemperature, humidity = currentHumidity }; string messageString = ""; messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); // Add a custom application property to the message. // An IoT hub can filter on these properties without access to the message body. //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); // Send the telemetry message await s_deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); await Task.Delay(1000 * 10); } } catch (Exception ex) { throw ex; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassTypesEx { interface IMath { void PrintLocalVariables(); decimal GetInterfaceAddition(int a, int b); decimal GetInterfaceMultiplication(int a, int b); int InterfacePpt1 { get; set; } } interface IVehicle { int Wheels { get; set; } string Dimensions { get; set; } int VehicleSize(); void VehicleType(); void VehicleDimensions(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace QLNhaTro { class KiemTra { public int Check(string ten, string mk) { Data d = new Data(); SqlDataReader rd = d.ExecuteReader("SELECT * FROM TaoTaiKhoan"); while (rd.Read()) { if (rd[1].ToString() == ten && rd[2].ToString() == mk) { return 1; } } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; using System.ComponentModel; using System.Data; using System.Drawing; namespace APP_Biblioteca { public class Socio //Estableciendo valores { public String Cedula { get; set; } public String Nombre { get; set; } public String Telefono_Casa { get; set; } public String Telefono_Cell { get; set; } public String Direccion { get; set; } public String Correo { get; set; } public Socio() { } //Constructor public Socio(String xCedula, String xNombre, String xTelefono_Casa, String xTelefono_Cell, String xDireccion, String xCorreo) { this.Cedula = xCedula; this.Nombre = xNombre; this.Telefono_Casa = xTelefono_Casa; this.Telefono_Cell = xTelefono_Cell; this.Direccion = xDireccion; this.Correo = xCorreo; } } }
namespace PrimeChecker { using System; public class StartUp { public static void Main() { long num = long.Parse(Console.ReadLine()); if (IsPrime(num)) Console.WriteLine("True"); else Console.WriteLine("False"); } public static bool IsPrime(long num) { if (num == 0 || num == 1) return false; for (int i = 2; i <= Math.Sqrt(num); i++) { if (num % i == 0) return false; } return true; } } }
using System; namespace _01.Bigger_Number { class BiggerNumber { static void Main() { int n1 = int.Parse(Console.ReadLine()); int n2 = int.Parse(Console.ReadLine()); Console.WriteLine(GetMax(n1, n2)); } static int GetMax(int n1, int n2) { int max = n1 > n2 ? n1 : n2; return max; } } }
using CsvHelper; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; namespace MovieAPI.App { public static class CSVReader<T> { public static List<T> Read(string file) { var data = new List<T>(); using (var streamReader = new StreamReader(file)) { using (var csvReader = new CsvReader(streamReader, CultureInfo.InvariantCulture)) { data = csvReader.GetRecords<T>().ToList(); } } return data; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CEMAPI.Models { public class TEApplicantMgntModel { } public class REQ_ListOfApplicants { public Nullable<int> OrderID { get; set; } public Nullable<int> PageNumber { get; set; } public Nullable<int> PagePerCount { get; set; } } public class Res_ListOfApplicants { public int ApplicantID { get; set; } public Nullable<int> ContextID { get; set; } public Nullable<int> ContactID { get; set; } public string ApplicantName { get; set; } public string FatherName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public string PanNumber { get; set; } public string CountryCode { get; set; } public string Mobile { get; set; } public string TypeofApplicant { get; set; } public Nullable<bool> Status { get; set; } public Nullable<bool> DeclarationSigned { get; set; } public Nullable<bool> IsAFSGenerated { get; set; } } public class Res_ApplicantBasicDetails { public int ApplicantBasicDetailsID { get; set; } public Nullable<int> ApplicantID { get; set; } public Nullable<int> ContactID { get; set; } public string Title { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string FatherName { get; set; } public Nullable<System.DateTime> DateOfBirth { get; set; } public Nullable<System.DateTime> AnniversaryDate { get; set; } public string Nationality { get; set; } public string Country { get; set; } public string ContactCategory { get; set; } public string GSTClassification { get; set; } public string GSTNumber { get; set; } public Nullable<bool> IsExistingCustomer { get; set; } public Nullable<int> LastModifiedBy { get; set; } public string LastModifiedByName { get; set; } public Nullable<System.DateTime> LastModifiedOn { get; set; } } public partial class Req_ApplicantIdentityDetails { public int ApplicantIdentityDetailsID { get; set; } public Nullable<int> ApplicantID { get; set; } public Nullable<int> ContactID { get; set; } public string Profession { get; set; } public string Industry { get; set; } public string Company { get; set; } public string Designation { get; set; } public string IdentityProfType { get; set; } public string IndentityProfNumber { get; set; } public Nullable<System.DateTime> DateOfIssue { get; set; } public string AddressProfType { get; set; } public string PanNumber { get; set; } public string AadharNumber { get; set; } public Nullable<System.DateTime> AadharIsssueDate { get; set; } public Nullable<System.DateTime> AadharValidityDate { get; set; } public Nullable<int> LastModifiedBy { get; set; } public Nullable<System.DateTime> LastModifiedOn { get; set; } public string LastModifiedByName { get; set; } public Nullable<bool> IsDeleted { get; set; } public string IdentityProfAttachment { get; set; } public string AddressProfAttachment { get; set; } public string PanAttachment { get; set; } public string AadharAttachment { get; set; } public string IdentityProfAttachment_Type { get; set; } public string AddressProfAttachment_Type { get; set; } public string PanAttachment_Type { get; set; } public string AadharAttachment_Type { get; set; } } public partial class Req_ApplicantIFundingDetails { public int ApplicantFundingDetailID { get; set; } public Nullable<int> ApplicantID { get; set; } public Nullable<int> ContactID { get; set; } public string TypeOfFunding { get; set; } public Nullable<decimal> FundingAmount { get; set; } public Nullable<bool> PreApproveLoan { get; set; } public string PreferredBankForLoan { get; set; } public string LoanAccountNumber { get; set; } public Nullable<decimal> ApprovedAmount { get; set; } public string BankContactPerson { get; set; } public string BankContactNumber { get; set; } public string BankEmailID { get; set; } public string BankAddress { get; set; } public string Branch { get; set; } public string BranchCode { get; set; } public string AccountHolder { get; set; } public string AccountNumber { get; set; } public string TypeOfAccount { get; set; } public int LastModifiedBy { get; set; } public Nullable<DateTime> LastModifiedOn { get; set; } public Nullable<bool> IsDeleted { get; set; } } public partial class Req_ApplicantICorrespondingDetails { public int ApplicantComAddressID { get; set; } public Nullable<int> ApplicantID { get; set; } public Nullable<int> ContactID { get; set; } public string Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string RelationshipWithApplicant { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string PinCode { get; set; } public string Mobile { get; set; } public string Email { get; set; } public string Fax { get; set; } public int LastModifiedBy { get; set; } public Nullable<DateTime> LastModifiedOn { get; set; } public Nullable<bool> IsDeleted { get; set; } } public partial class Req_ApplicantIGAPDetails { public int ApplicantGPADetailID { get; set; } public Nullable<int> ApplicantID { get; set; } public Nullable<int> ContactID { get; set; } public string Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string RelationWithAboveApplicant { get; set; } public string RelationWithMainApplicant { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string PinCode { get; set; } public string Mobile { get; set; } public string Email { get; set; } public int LastModifiedBy { get; set; } public Nullable<DateTime> LastModifiedOn { get; set; } public Nullable<bool> IsDeleted { get; set; } } }
namespace TicTacToe.Src { public class Row { public int Value { get; private set; } public Row(int row) { Value = row; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2._6_IDisposable { //https://docs.microsoft.com/pt-br/dotnet/standard/garbage-collection/implementing-dispose class Program { static void Main(string[] args) { using(var file = new OpenFile("myFile.txt")) { } } } }
using System; using System.Collections.Generic; using System.Data.Objects; using System.Linq; using TY.SPIMS.Controllers.Interfaces; using TY.SPIMS.Entities; using TY.SPIMS.POCOs; using TY.SPIMS.Utilities; namespace TY.SPIMS.Controllers { public class PurchaseReturnController : IPurchaseReturnController { private readonly IUnitOfWork unitOfWork; private readonly IActionLogController actionLogController; private readonly IAutoPartController autopartController; private TYEnterprisesEntities db { get { return unitOfWork.Context; } } public PurchaseReturnController(IUnitOfWork unitOfWork, IAutoPartController autopartController, IActionLogController actionLogController) { this.unitOfWork = unitOfWork; this.actionLogController = actionLogController; this.autopartController = autopartController; } #region CUD Functions public void InsertPurchaseReturn(PurchaseReturnColumnModel model) { try { using (this.unitOfWork) { PurchaseReturn item = new PurchaseReturn() { MemoNumber = model.MemoNumber, CustomerId = model.CustomerId, ReturnDate = model.ReturnDate, AmountReturn = model.AmountReturn, Adjustment = model.Adjustment, TotalDebitAmount = model.TotalDebitAmount, Remarks = model.Remarks, IsDeleted = model.IsDeleted, RecordedBy = model.RecordedByUser, ApprovedBy = model.ApprovedByUser, AmountUsed = 0 }; if (model.Details.Count > 0) { foreach (PurchaseReturnDetailModel d in model.Details) { PurchaseReturnDetail detail = new PurchaseReturnDetail() { PartDetailId = d.PartDetailId, PONumber = d.PONumber, Quantity = d.Quantity, UnitPrice = d.UnitPrice, TotalAmount = d.TotalAmount, Balance = d.TotalAmount }; item.PurchaseReturnDetail.Add(detail); AutoPartDetail autoDetail = db.AutoPartDetail.FirstOrDefault(a => a.Id == d.PartDetailId); if (autoDetail != null) autoDetail.Quantity -= d.Quantity; } } this.unitOfWork.Context.AddToPurchaseReturn(item); string action = string.Format("Added New Purchase Return - {0}", item.MemoNumber); this.actionLogController.AddToLog(action, UserInfo.UserId); this.unitOfWork.SaveChanges(); } } catch (Exception ex) { throw ex; } } public void UpdatePurchaseReturn(PurchaseReturnColumnModel model) { try { using (this.unitOfWork) { var item = FetchPurchaseReturnById(model.Id); if (item != null) { //Delete old details if (item.PurchaseReturnDetail.Any()) { foreach (var d in item.PurchaseReturnDetail.ToList()) { AutoPartDetail detail = db.AutoPartDetail.FirstOrDefault(a => a.Id == d.PartDetailId); detail.Quantity += d.Quantity; foreach (var payment in d.PurchasePayments.ToList()) { item.AmountUsed -= payment.Amount; db.DeleteObject(payment); } db.DeleteObject(d); } } item.MemoNumber = model.MemoNumber; item.CustomerId = model.CustomerId; item.ReturnDate = model.ReturnDate; item.AmountReturn = model.AmountReturn; item.Adjustment = model.Adjustment; item.TotalDebitAmount = model.TotalDebitAmount; item.Remarks = model.Remarks; item.IsDeleted = model.IsDeleted; item.RecordedBy = model.RecordedByUser; item.ApprovedBy = model.ApprovedByUser; //Add the new items if (model.Details.Count > 0) { foreach (PurchaseReturnDetailModel d in model.Details) { var autoPart = db.AutoPartDetail.FirstOrDefault(a => a.Id == d.PartDetailId); autoPart.Quantity -= d.Quantity; PurchaseReturnDetail detail = new PurchaseReturnDetail() { PartDetailId = d.PartDetailId, PONumber = d.PONumber, Quantity = d.Quantity, UnitPrice = d.UnitPrice, TotalAmount = d.TotalAmount, Balance = d.TotalAmount }; item.PurchaseReturnDetail.Add(detail); } } } string action = string.Format("Updated Purchase Return - {0}", item.MemoNumber); this.actionLogController.AddToLog(action, UserInfo.UserId); this.unitOfWork.SaveChanges(); } } catch (Exception ex) { throw ex; } } public void DeletePurchaseReturn(int id) { try { using (this.unitOfWork) { var item = FetchPurchaseReturnById(id); if (item != null) { item.IsDeleted = true; foreach (var i in item.PurchaseReturnDetail) { AutoPartDetail a = db.AutoPartDetail.FirstOrDefault(b => b.Id == i.PartDetailId); a.Quantity += i.Quantity; } } string action = string.Format("Deleted Purchase Return - {0}", item.MemoNumber); this.actionLogController.AddToLog(action, UserInfo.UserId); this.unitOfWork.SaveChanges(); } } catch (Exception ex) { throw ex; } } #endregion #region Fetch Functions private IQueryable<PurchaseReturn> CreateQuery(PurchaseReturnFilterModel filter) { var items = from i in db.PurchaseReturn where i.IsDeleted == false select i; if (filter != null) { if (filter.CustomerId != 0) items = items.Where(a => a.CustomerId == filter.CustomerId); if (!string.IsNullOrWhiteSpace(filter.MemoNumber)) items = items.Where(a => a.MemoNumber.Contains(filter.MemoNumber)); if (filter.AmountType != NumericSearchType.All) { if (filter.AmountType == NumericSearchType.Equal) items = items.Where(a => a.TotalDebitAmount == filter.AmountValue); else if (filter.AmountType == NumericSearchType.GreaterThan) items = items.Where(a => a.TotalDebitAmount > filter.AmountValue); else if (filter.AmountType == NumericSearchType.LessThan) items = items.Where(a => a.TotalDebitAmount < filter.AmountValue); } if (filter.DateType != DateSearchType.All) { DateTime dateFrom = filter.DateFrom.Date; DateTime dateTo = filter.DateTo.AddDays(1).Date; items = items.Where(a => a.ReturnDate >= dateFrom && a.ReturnDate < dateTo); } if (filter.Status != ReturnStatusType.All) { if (filter.Status == ReturnStatusType.Used) items = items.Where(a => a.IsUsed != null && a.IsUsed == true); else items = items.Where(a => a.IsUsed == null || a.IsUsed == false); } } else { //Default sorting items = items.OrderByDescending(a => a.ReturnDate); } return items; } public SortableBindingList<PurchaseReturnDisplayModel> FetchPurchaseReturnWithSearch(PurchaseReturnFilterModel filter) { try { var query = CreateQuery(filter); var result = from a in query select new PurchaseReturnDisplayModel { Id = a.Id, MemoNumber = a.MemoNumber, Customer = a.Customer.CompanyName, ReturnDate = a.ReturnDate.Value, AmountReturn = a.AmountReturn.Value, Adjustment = a.Adjustment.Value, TotalDebitAmount = a.TotalDebitAmount.Value, Remarks = a.Remarks, RecordedBy = a.RecordedByUser.Firstname + " " + a.RecordedByUser.Lastname, AmountUsed = a.AmountUsed.HasValue ? a.AmountUsed.Value : 0, //ApprovedBy = a.ApprovedBy.HasValue ? a.ApprovedByUser.Firstname + " " + a.ApprovedByUser.Lastname : "-", IsDeleted = a.IsDeleted.Value, }; SortableBindingList<PurchaseReturnDisplayModel> b = new SortableBindingList<PurchaseReturnDisplayModel>(result); return b; } catch (Exception ex) { throw ex; } } public List<PurchaseReturnDisplayModel> FetchAllPurchaseReturns() { try { var query = CreateQuery(null); var result = from a in query select new PurchaseReturnDisplayModel { Id = a.Id, MemoNumber = a.MemoNumber, Customer = a.Customer.CompanyName, ReturnDate = a.ReturnDate.Value, AmountReturn = a.AmountReturn.Value, Adjustment = a.Adjustment.Value, TotalDebitAmount = a.TotalDebitAmount.Value, Remarks = a.Remarks, IsDeleted = a.IsDeleted.Value, }; return result.ToList(); } catch (Exception ex) { throw ex; } } public PurchaseReturn FetchPurchaseReturnById(int id) { try { var item = (from i in db.PurchaseReturn where i.Id == id select i).FirstOrDefault(); return item; } catch (Exception ex) { throw ex; } } public SortableBindingList<PurchaseReturnDetailModel> FetchPurchaseReturnDetails(int id) { try { var details = (from r in db.PurchaseReturnDetail where r.PRId == id && r.PurchaseReturn.IsDeleted != true select r).ToList(); var results = from d in details select new PurchaseReturnDetailModel() { AutoPart = d.PartDetailId.HasValue ? this.autopartController.FetchPartNameById(d.PartDetailId.Value) : "-", PartDetailId = d.PartDetailId.HasValue ? d.PartDetailId.Value : 0, PartNumber = d.PartDetailId.HasValue ? this.autopartController.FetchAutoPartDetailById(d.PartDetailId.Value).PartNumber : "-", PONumber = d.PONumber, Quantity = d.Quantity.HasValue ? d.Quantity.Value : 0, UnitPrice = d.UnitPrice.HasValue ? d.UnitPrice.Value : 0, TotalAmount = d.TotalAmount.HasValue ? d.TotalAmount.Value : 0 }; SortableBindingList<PurchaseReturnDetailModel> b = new SortableBindingList<PurchaseReturnDetailModel>(results); return b; } catch (Exception ex) { throw ex; } } public int FetchQuantityReturned(int CustomerId, string poNumber, int itemId, int returnId) { try { var qty = (from r in db.PurchaseReturnDetail where r.PurchaseReturn.CustomerId == CustomerId && r.PONumber == poNumber && r.PartDetailId == itemId && r.PRId != returnId && r.PurchaseReturn.IsDeleted != true select r.Quantity).Sum(); return qty.HasValue ? qty.Value : 0; } catch (Exception ex) { throw ex; } } public bool POHasReturn(string poNumber) { try { var result = (from r in db.PurchaseReturnDetail select r).Any(a => a.PurchaseReturn.IsDeleted == false && a.PONumber == poNumber); return result; } catch (Exception ex) { throw ex; } } public SortableBindingList<PurchaseReturnDetailModel> FetchAllPurchaseReturnDetails() { try { var details = (from r in db.PurchaseReturnDetail where r.PurchaseReturn.IsDeleted != true select r).ToList(); var results = from d in details select new PurchaseReturnDetailModel() { MemoNumber = d.PurchaseReturn.MemoNumber, ReturnDate = d.PurchaseReturn.ReturnDate, AutoPart = d.PartDetailId.HasValue ? this.autopartController.FetchPartNameById(d.PartDetailId.Value) : "-", PartNumber = d.PartDetailId.HasValue ? this.autopartController.FetchAutoPartDetailById(d.PartDetailId.Value).PartNumber : "-", PONumber = d.PONumber, Quantity = d.Quantity.HasValue ? d.Quantity.Value : 0, UnitPrice = d.UnitPrice.HasValue ? d.UnitPrice.Value : 0, TotalAmount = d.TotalAmount.HasValue ? d.TotalAmount.Value : 0 }; SortableBindingList<PurchaseReturnDetailModel> b = new SortableBindingList<PurchaseReturnDetailModel>(results); return b; } catch (Exception ex) { throw ex; } } public bool? IsItemDebited(int id) { try { var debited = db.PurchasePayments.Any(a => a.PurchaseReturnDetail.PRId == id); return debited; } catch (Exception ex) { throw ex; } } public bool CheckReturnHasDuplicate(string codeToCheck, int id) { try { var hasReturn = db.PurchaseReturn.Where(a => a.IsDeleted == false) .Any(a => a.MemoNumber == codeToCheck && a.Id != id); return hasReturn; } catch (Exception ex) { throw ex; } } public List<PurchaseReturnDetailModel> GetReturnsPerInvoice(string invoiceNumber) { try { var details = db.PurchaseReturnDetail .Where(a => a.PurchaseReturn.IsDeleted != true && a.PONumber == invoiceNumber && a.Balance != 0) .Select(a => new PurchaseReturnDetailModel() { Id = a.Id, MemoNumber = a.PurchaseReturn.MemoNumber, MemoDisplay = a.PurchaseReturn.MemoNumber + " - " + a.AutoPartDetail.PartNumber, ReturnDate = a.PurchaseReturn.ReturnDate, TotalAmount = a.TotalAmount.HasValue ? a.TotalAmount.Value : 0, Balance = a.Balance.HasValue ? a.Balance.Value : 0 }) .ToList(); return details; } catch (Exception ex) { throw ex; } } public SortableBindingList<PaymentDebitModel> FetchPaymentDetails(int returnId) { try { var payment = db.PurchasePayments.Where(a => a.PurchaseReturnDetailId != null && a.PurchaseReturnDetail.PurchaseReturn.IsDeleted != true && a.PurchaseReturnDetail.PurchaseReturn.Id == returnId); var result = payment.Select(a => new PaymentDebitModel { VoucherNumber = a.PaymentDetail.VoucherNumber, Amount = a.Amount.HasValue ? a.Amount.Value : 0 }); return new SortableBindingList<PaymentDebitModel>(result); } catch (Exception ex) { throw ex; } } public SortableBindingList<PurchaseReturnDetailModel> FetchAllReturnsInPurchase(string poNumber) { try { var returns = db.PurchaseReturnDetail.Where(a => a.PurchaseReturn.IsDeleted != true && a.PONumber == poNumber) .ToList() .Select(a => new PurchaseReturnDetailModel() { MemoNumber = a.PurchaseReturn.MemoNumber, ReturnDate = a.PurchaseReturn.ReturnDate, Quantity = a.Quantity.HasValue ? a.Quantity.Value : 0, AutoPart = a.PartDetailId.HasValue ? this.autopartController.FetchPartNameById(a.PartDetailId.Value) : "-" }); return new SortableBindingList<PurchaseReturnDetailModel>(returns); } catch (Exception ex) { throw ex; } } public List<SalesReturnDetailModel> GetReturnsWithBalance(int customerId) { try { var details = db.PurchaseReturnDetail .Where(a => a.PurchaseReturn.IsDeleted != true && a.Balance != 0 && a.PurchaseReturn.CustomerId == customerId) .Select(a => new SalesReturnDetailModel() { Id = a.Id, MemoNumber = a.PurchaseReturn.MemoNumber, InvoiceNumber = a.PONumber, TotalAmount = a.TotalAmount.HasValue ? a.TotalAmount.Value : 0, Balance = a.Balance.HasValue ? a.Balance.Value : 0, ReturnDate = a.PurchaseReturn.ReturnDate }) .ToList(); return details; } catch (Exception ex) { throw ex; } } public SortableBindingList<PurchaseReturnDetailModel> FetchPurchaseReturnByIds(List<int> list) { try { var purchaseReturns = db.PurchaseReturnDetail.Where(a => list.Contains(a.Id)) .Select(a => new PurchaseReturnDetailModel() { Id = a.Id, MemoNumber = a.PurchaseReturn.MemoNumber, PONumber = a.PONumber, TotalAmount = a.TotalAmount.HasValue ? a.TotalAmount.Value : 0, Balance = a.Balance.HasValue ? a.Balance.Value : 0, ReturnDate = a.PurchaseReturn.ReturnDate }); return new SortableBindingList<PurchaseReturnDetailModel>(purchaseReturns); } catch (Exception ex) { throw ex; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class TransformExtensions { public static void ClearAll(this Transform item) { GameObject[] childs = new GameObject[item.childCount]; int i = 0; foreach(Transform children in item) { childs[i] = children.gameObject; i += 1; } foreach(var children in childs) { GameObject.Destroy(children); } } }
using Cottle.Functions; using Cottle.Values; using EddiDataDefinitions; using EddiGalnetMonitor; using EddiSpeechResponder.Service; using JetBrains.Annotations; using System; using System.Collections.Generic; namespace EddiSpeechResponder.CustomFunctions { [UsedImplicitly] internal class GalnetNewsArticles : ICustomFunction { public string name => "GalnetNewsArticles"; public FunctionCategory Category => FunctionCategory.Galnet; public string description => Properties.CustomFunctions_Untranslated.GalnetNewsArticles; public Type ReturnType => typeof( List<News> ); public NativeFunction function => new NativeFunction((values) => { List<News> results = null; if (values.Count == 0) { // Obtain all unread articles results = GalnetSqLiteRepository.Instance.GetArticles(); } else if (values.Count == 1) { // Obtain all unread news of a given category results = GalnetSqLiteRepository.Instance.GetArticles(values[0].AsString); } else if (values.Count == 2) { // Obtain all news of a given category results = GalnetSqLiteRepository.Instance.GetArticles(values[0].AsString, values[1].AsBoolean); } return new ReflectionValue(results ?? new List<News>()); }, 0, 2); } }
using MobileCollector; using MobileCollector.model; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ServerCollector { internal static class Extensions { internal static KindKey toKindKey(this string kindKey) { if (string.IsNullOrWhiteSpace(kindKey)) throw new ArgumentNullException( "string.toKindKey requires a non zero length string"); return new KindKey() { Value = kindKey }; } internal static KindName toKind(this string kindName) { if (string.IsNullOrWhiteSpace(kindName)) throw new ArgumentNullException( "string.toKind requires a non zero length string"); return new KindName() {Value = kindName }; } internal static List<KindName> toKinds(this List<string> kindNames) { return (from kind in kindNames select kind.toKind()).ToList(); } public static int toYMDInt(this DateTime dateValue) { var timeofday = dateValue.ToString("yyyyMMdd"); return Convert.ToInt32(timeofday); } internal static List<OutEntity> DecompressFromBase64String(this string compressedString) { //var compressedString = File.ReadAllText("Assets\\unsyncd.txt"); var barray = System.Convert.FromBase64String(compressedString); var toReturn = new MemoryStream(); var jsonString = string.Empty; using (var outStream = new System.IO.MemoryStream(barray)) using (var deflateStream = new System.IO.Compression .DeflateStream(outStream, System.IO.Compression.CompressionMode.Decompress)) { deflateStream.CopyTo(toReturn); deflateStream.Close(); jsonString = System.Text.Encoding.UTF8.GetString(toReturn.ToArray()); } var js = Newtonsoft.Json.JsonConvert .DeserializeObject<List<MobileCollector.model.OutEntity>>(jsonString); return js; } internal static string CompressToBase64String(this List<OutEntity> unsyncdRecs) { var js = Newtonsoft.Json.JsonConvert.SerializeObject(unsyncdRecs); var bytes = System.Text.Encoding.UTF8.GetBytes(js); var b64 = string.Empty; using (var input = new System.IO.MemoryStream(bytes)) { using (var outStream = new System.IO.MemoryStream()) using (var deflateStream = new System.IO.Compression .DeflateStream(outStream, System.IO.Compression.CompressionMode.Compress)) { input.CopyTo(deflateStream); deflateStream.Close(); b64 = System.Convert.ToBase64String(outStream.ToArray()); } } return b64; } //internal static long toSafeDate(this DateTime dateValue) //{ // return (dateValue.Year * 100 + dateValue.Month) * 100 + dateValue.Day; //} //internal static DateTime fromSafeDate(this int safeDate) //{ // var asString = safeDate.ToString(); // var day = Convert.ToInt16(asString.Substring(5, 2)); // var month = Convert.ToInt16(asString.Substring(3, 2)); // var year = Convert.ToInt16(asString.Substring(0, 4)); // return new DateTime(year, month, day); //} //internal static T GetDataView<T>(this FieldItem field, Android.App.Activity context) where T : Android.Views.View //{ // //we convert these into int Ids // var fieldName = // (field.dataType == Constants.DATEPICKER || field.dataType == Constants.TIMEPICKER) // ? // Constants.DATE_TEXT_PREFIX + field.name : // field.name; // int resourceId = context.Resources.GetIdentifier( // fieldName, "id", context.PackageName); // T view = null; // view = context.FindViewById<T>(resourceId); // return view; //} internal static string toText(this System.IO.Stream stream) { //var buffer = new byte[length]; //prepexFieldsStream.Read(buffer, 0, Convert.ToInt32(length)); //var asString = Convert.ToString(buffer); var mstream = new System.IO.MemoryStream(); stream.CopyTo(mstream); var bytes = mstream.ToArray(); return System.Text.Encoding.Default.GetString(bytes); } internal static byte[] toByteArray(this System.IO.Stream stream) { var mstream = new System.IO.MemoryStream(); stream.CopyTo(mstream); var bytes = mstream.ToArray(); return bytes; } //this System.Json.JsonValue internal static string decryptAndGetApiSetting(this Dictionary<string,string> jsonObject, string settingString) { var value = jsonObject[settingString]; if (Constants.ENCRYPTED_ASSETS.Contains(settingString)) { //we decrypt return JhpSecurity.Decrypt(value); } return value; } } }
using EduHome.Models.Base; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace EduHome.Models.Entity { public class Event : BaseEntity { [Required, StringLength(maximumLength: 100)] public string Title { get; set; } [BindNever] public string Image { get; set; } [Required, NotMapped] public IFormFile Photo { get; set; } [Required] public string ByWhom { get; set; } [Required] public string Address { get; set; } [DataType(dataType: DataType.Text)] public string Details { get; set; } public bool IsDeleted { get; set; } public TimeInterval TimeInterval { get; set; } public int? TimeIntervalId { get; set; } public Course Course { get; set; } public int? CourseId { get; set; } public List<PostMessage> PostMessages { get; set; } public List<EventSpeaker> EventSpeakers { get; set; } } }
using System.Collections.Generic; namespace Algorithms.LeetCode { public class FindAndReplacePatternTask { public IList<string> FindAndReplacePattern(string[] words, string pattern) { var mathes = new List<string>(); foreach (var word in words) { if (MathesPattern(word, pattern)) mathes.Add(word); } return mathes; } private bool MathesPattern(string word, string pattern) { var wordToPattern = new int?[26]; var patternToWord = new int?[26]; for (int i = 0; i < word.Length; ++i) { var wIndex = word[i] - 'a'; var pIndex = pattern[i] - 'a'; if (wordToPattern[wIndex] is null && patternToWord[pIndex] is null) { wordToPattern[wIndex] = pIndex; patternToWord[pIndex] = wIndex; } else if (wordToPattern[wIndex] != pIndex || patternToWord[pIndex] != wIndex) return false; } return true; } } }
/* * ClassName: TableDef * Author: Blade * Date Created: 08/12/2008 * Description: Represents a table definition row */ using System; using System.Collections.Generic; using System.Text; namespace RecordBuilder { class TableDef { private string _table; public string Table { get { return _table; } set { _table = value; } } private string _column; public string Column { get { return _column; } set { _column = value; } } private string _datatype; public string Datatype { get { return _datatype; } set { _datatype = value; } } private int _length; public int Length { get { return _length; } set { _length = value; } } private string _default; [MappingAttribute("Default")] public string DefaultValue { get { return _default; } set { _default = value; } } private string _nullable; public string Nullable { get { return _nullable; } set { _nullable = value; } } private int _xprecision; public int XPrecision { get { return _xprecision; } set { _xprecision = value; } } private int _xscale; public int XScale { get { return _xscale; } set { _xscale = value; } } private int _precision; public int Precision { get { return _precision; } set { _precision = value; } } } }
namespace Tutorial.Tests.LinqToSql { using System; using System.Diagnostics; using Tutorial.LinqToSql; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class TranslationTests { [TestMethod] public void TranslationTest() { Translation.InlinePredicate(); Translation.InlinePredicateCompiled(); try { Translation.MethodPredicate(); Assert.Fail(); } catch (NotSupportedException exception) { Trace.WriteLine(exception); } try { Translation.MethodPredicateCompiled(); Assert.Fail(); } catch (NotSupportedException exception) { Trace.WriteLine(exception); } Translation.MethodSelector(); Translation.LocalSelector(); Translation.RemoteMethod(); } } }
using Microsoft.Extensions.Logging; using System; namespace SimulationDemo.Logger { public static class SimLogger { public static ILogger Logger; public static void Info(string info) { Logger.LogInformation($"Iteration {Simulation.GlobalTime} - {info}"); } } }
using System.Reflection; [assembly: AssemblyTitle("ShopExpander")] [assembly: AssemblyDescription("")] [assembly: AssemblyVersion("1.6.2")] [assembly: AssemblyFileVersion("1.6.2")]
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using CreamBell_DMS_WebApps.App_Code; using Microsoft.Reporting.WebForms; using Elmah; namespace CreamBell_DMS_WebApps { public partial class frmItemSKUWise : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["USERID"] == null || Session["USERID"].ToString() == string.Empty) { Response.Redirect("Login.aspx"); return; } if (!IsPostBack) { BindFilters(); txtFromDate.Text = string.Format("{0:dd-MMM-yyyy }", DateTime.Today.AddDays(-1)); txtToDate.Text = string.Format("{0:dd-MMM-yyyy }", DateTime.Today); } } protected void BtnShowReport_Click(object sender, EventArgs e) { bool b = Validate(); if (b) { ShowReport(); } } private void BindFilters() { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); string queryCustomerGroup = " Select CUSTGROUP_CODE, CUSTGROUP_NAME, CUSTGROUP_CODE+'-'+ CUSTGROUP_NAME as CUSTGROUP from [ax].[ACXCUSTGROUPMASTER] where DATAAREAID='" + Session["DATAAREAID"].ToString() + "' and BLOCKED<>1 "; DDLCustGroupNew.Items.Clear(); DDLCustGroupNew.Items.Add("ALL"); obj.BindToDropDownp(DDLCustGroupNew, queryCustomerGroup, "CUSTGROUP", "CUSTGROUP_CODE"); string queryProductGroup = "Select distinct PRODUCT_GROUP from ax.INVENTTABLE"; DDLProductGroupNew.Items.Clear(); DDLProductGroupNew.Items.Add("ALL"); obj.BindToDropDownp(DDLProductGroupNew, queryProductGroup, "PRODUCT_GROUP", "PRODUCT_GROUP"); } private bool Validate() { bool b; if (txtFromDate.Text == string.Empty || txtToDate.Text == string.Empty) { b = false; LblMessage.Text = "Please Provide From Date and To Date"; } else { b = true; LblMessage.Text = string.Empty; } return b; } protected void DDLCustGroup_SelectedIndexChanged(object sender, EventArgs e) { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); if (DDLCustGroupNew.Text == "ALL") { string queryALLCustomer = " Select CUSTOMER_CODE, CUSTOMER_NAME from ax.acxcustmaster where SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'and BLOCKED = 0"; DDLCustomersNew.Items.Clear(); //DDLCustomers.Items.Add("-Select-"); //obj.BindToDropDown(DDLCustomers, queryALLCustomer, "CUSTOMER_NAME", "CUSTOMER_CODE"); } else { string queryCustomer = " Select CUSTOMER_CODE, CUSTOMER_NAME from ax.acxcustmaster where CUST_GROUP='" + DDLCustGroupNew.SelectedValue.ToString() + "' " + " and SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'and BLOCKED = 0"; DDLCustomersNew.Items.Clear(); DDLCustomersNew.Items.Add("-Select-"); obj.BindToDropDownp(DDLCustomersNew, queryCustomer, "CUSTOMER_NAME", "CUSTOMER_CODE"); } } protected void DDLProductGroup_SelectedIndexChanged(object sender, EventArgs e) { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); if (DDLProductGroupNew.Text == "ALL") { DDLSubCategoryNew.Items.Clear(); //DDLProduct.Items.Clear(); } else { string strQuery = " Select distinct replace(replace(PRODUCT_SUBCATEGORY, char(9), ''), char(13) + char(10), '') as SUBCATEGORY from " + " ax.INVENTTABLE where replace(replace(PRODUCT_GROUP, char(9), ''), char(13) + char(10), '') = '" + DDLProductGroupNew.SelectedItem.Text.ToString() + "' "; DDLSubCategoryNew.Items.Clear(); DDLSubCategoryNew.Items.Add("-Select-"); obj.BindToDropDownp(DDLSubCategoryNew, strQuery, "SUBCATEGORY", "SUBCATEGORY"); } } protected void DDLSubCategory_SelectedIndexChanged(object sender, EventArgs e) { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); if (DDLSubCategoryNew.Text == "-Select-") { // DDLProduct.Items.Clear(); } else { string strQuery = " Select ITEMID +'-(' + PRODUCT_NAME+')' as PRODUCT_NAME,PRODUCT_NAME as PRODDESCP, ITEMID,PRODUCT_GROUP, PRODUCT_SUBCATEGORY from ax.INVENTTABLE where " + " replace(replace(PRODUCT_SUBCATEGORY, char(9), ''), char(13) + char(10), '') = '" + DDLSubCategoryNew.SelectedItem.Text.ToString() + "' "; // DDLProduct.Items.Clear(); //DDLProduct.Items.Add("-Select-"); //obj.BindToDropDown(DDLProduct, strQuery, "PRODUCT_NAME", "PRODDESCP"); } } private void ShowReport() { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); string FilterQuery = string.Empty; DataTable dtSetHeader = null; DataTable dtSetData = null; try { string query = "Select NAME from ax.inventsite where SITEID IN (" + ucRoleFilters.GetCommaSepartedSiteId() + ") "; dtSetHeader = new DataTable(); dtSetHeader = obj.GetData(query); string CUST_GROUP = string.Empty; string CUSTOMER_NAME = string.Empty; string PRODUCT_GROUP = string.Empty; string PRODUCT_SUBCATEGORY = string.Empty; //string Product = string.Empty; if (DDLCustGroupNew.SelectedIndex > 0) { CUST_GROUP = DDLCustGroupNew.SelectedValue.ToString(); } else { CUST_GROUP = ""; } if (DDLCustomersNew.SelectedIndex > 0) { CUSTOMER_NAME = DDLCustomersNew.SelectedValue.ToString(); } else { CUSTOMER_NAME = ""; } if (DDLProductGroupNew.SelectedIndex > 0) { PRODUCT_GROUP = DDLProductGroupNew.SelectedValue.ToString(); } else { PRODUCT_GROUP = ""; } if (DDLSubCategoryNew.SelectedIndex > 0) { PRODUCT_SUBCATEGORY = DDLSubCategoryNew.SelectedValue.ToString(); } else { PRODUCT_SUBCATEGORY = ""; } // FilterQuery = "select ASS.SITEID, ASS.NAMEALIAS, ASS.PRODUCT_NAME,c.CUST_GROUP, c.CUSTOMER_NAME,"+ // "INVT.PRODUCT_GROUP,INVT.PRODUCT_SUBCATEGORY, "+ // "BOXQTY as BOX, PCSQTY as PCS, isnull(BOXPCS, '0') as [TotalBoxPCS],"+ // "BOX as TotalQtyConv, ASS.LTR, AMOUNT from ACX_SKUWISE_SALE ASS "+ // "INNER JOIN AX.INVENTTABLE INVT ON ASS.PRODUCT_CODE = INVT.ITEMID "+ // "INNER JOIN ax.acxcustmaster C on ASS.SITEID = c.SITE_CODE "+ // " where SITEID = '" + Session["SiteCode"].ToString() + "' and INVOICE_DATE >='" + Convert.ToDateTime(txtFromDate.Text).ToString("yyyy-MM-dd") + "'"+ //" and INVOICE_DATE <='" + Convert.ToDateTime(txtToDate.Text).ToString("yyyy-MM-dd") + "' and " + //" CUST_GROUP ='" + CUST_GROUP + "' and CUSTOMER_NAME='" + CUSTOMER_NAME + "' and PRODUCT_GROUP='" + PRODUCT_GROUP + "' and PRODUCT_SUBCATEGORY='" + PRODUCT_SUBCATEGORY + "' ORDER BY NAMEALIAS ASC "; FilterQuery = "EXEC Usp_ITEMSKUWISE '" + ucRoleFilters.GetCommaSepartedSiteId() + "','" + Convert.ToDateTime(txtFromDate.Text).ToString("yyyy-MM-dd") + "','" + Convert.ToDateTime(txtToDate.Text).ToString("yyyy-MM-dd") + "','" + CUST_GROUP + "','" + CUSTOMER_NAME + "','" + PRODUCT_GROUP + "','" + PRODUCT_SUBCATEGORY + "'"; dtSetData = new DataTable(); dtSetData = obj.GetData(FilterQuery); LoadDataInReportViewer(dtSetHeader, dtSetData); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); LblMessage.Text = ex.Message.ToString(); } } private void LoadDataInReportViewer(DataTable dtSetHeader, DataTable dtSetData) { try { if (dtSetHeader.Rows.Count > 0 && dtSetData.Rows.Count > 0) { ReportViewer1.LocalReport.ReportPath = Server.MapPath("Reports\\SKUWiseSale.rdl"); ReportParameter FromDate = new ReportParameter(); FromDate.Name = "FromDate"; FromDate.Values.Add(txtFromDate.Text); ReportParameter ToDate = new ReportParameter(); ToDate.Name = "ToDate"; ToDate.Values.Add(txtToDate.Text); ReportParameter[] parameter = new ReportParameter[2]; parameter[1] = FromDate; parameter[0] = ToDate; ReportViewer1.LocalReport.SetParameters(parameter); ReportViewer1.ProcessingMode = ProcessingMode.Local; ReportViewer1.AsyncRendering = true; ReportViewer1.LocalReport.DataSources.Clear(); ReportDataSource RDS1 = new ReportDataSource("DSetHeader", dtSetHeader); ReportViewer1.LocalReport.DataSources.Add(RDS1); ReportDataSource RDS2 = new ReportDataSource("DSetData", dtSetData); ReportViewer1.LocalReport.DataSources.Add(RDS2); ReportViewer1.ShowPrintButton = true; this.ReportViewer1.LocalReport.Refresh(); ReportViewer1.Visible = true; ReportViewer1.ZoomPercent = 100; LblMessage.Text = String.Empty; } else { LblMessage.Text = "No Records Exists !!"; ReportViewer1.Visible = false; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); LblMessage.Text = ex.Message.ToString(); } } } }
namespace TripLog.Models { using System; using System.Collections.Generic; public class TripLogEntry { public string Id { get; set; } public string Title { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } public DateTime Date { get; set; } public int Rating { get; set; } public string Notes { get; set; } public TripLogEntry() { Title = string.Empty; Id = Guid.NewGuid().ToString(); Notes = string.Empty; } public override bool Equals(object obj) { if (!(obj is TripLogEntry)) { return false; } var instance = (TripLogEntry)obj; return instance.Id.Equals(Id); } public override int GetHashCode() { return 2108858624 + EqualityComparer<string>.Default.GetHashCode(Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using XH.Domain.Catalogs.Models; using XH.Infrastructure.Mapper; using XH.Queries.Categories.Dtos; using XH.Domain.Hazards; using XH.Queries.Hazards.Dtos; namespace XH.Query.Handlers.Configs { public class HazardsMapperRegistrar : IAutoMapperRegistrar { public void Register(IMapperConfigurationExpression cfg) { cfg.CreateMap<HazardLevel, HazardLevelDto>(); cfg.CreateMap<HazardLevel, HazardLevelOverviewDto>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using IRAP.Global; using IRAPShared; namespace IRAP.Entity.MDM { /// <summary> /// Logo图片信息 /// </summary> public class FVS_LogoImages { /// <summary> /// 公司Logo图片(Base64转换) /// </summary> public string CompanyLogoImage { get; set; } /// <summary> /// 客户Logo图片(Base64转换) /// </summary> public string CustomerLogoImage { get; set; } /// <summary> /// 客户产品图片(Base64转换) /// </summary> public string CustomerProductImage { get; set; } [IRAPORMMap(ORMMap = false)] public Image CompanyLogo { get { return Base64ToImage(CompanyLogoImage); } } [IRAPORMMap(ORMMap = false)] public Image CustomerLogo { get { return Base64ToImage(CustomerLogoImage); } } [IRAPORMMap(ORMMap = false)] public Image CustomerProduct { get { return Base64ToImage(CustomerProductImage); } } private Image Base64ToImage(string stringBase64) { byte[] imageBytes; try { imageBytes = Convert.FromBase64String(stringBase64); return Tools.BytesToImage(imageBytes); } catch { return null; } } public FVS_LogoImages Clone() { return MemberwiseClone() as FVS_LogoImages; } } }
public class Solution { public IList<string> SummaryRanges(int[] nums) { var res = new List<string>(); if (nums.Length == 0) return res; bool isContinuous = false; int start = nums[0], end = nums[0]; for (int i=1; i<=nums.Length; i++) { if (i < nums.Length && nums[i] == nums[i-1] + 1) { end = nums[i]; isContinuous = true; } else { if (isContinuous) { res.Add($"{start}->{end}"); } else { res.Add(start.ToString()); } if (i < nums.Length) { start = nums[i]; isContinuous = false; } } } return res; } }
using System; namespace ELearning.Model { public class UserModel { public int UserId { set; get; } public string Name { get; set; } public string Email { get; set; } public string Password { get; set; } public int RoleId { get; set; } public bool IsAuthenticated { get; set; } public string ActivationCode { get; set; } } }
using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html; using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de PDFHelper /// </summary> public class PDFHelper : PdfPageEventHelper { // This is the contentbyte object of the writer PdfContentByte obj_cb; // we will put the final number of pages in a template PdfTemplate obj_template; // this is the BaseFont we are going to use for the header / footer BaseFont obj_bf = null; // This keeps track of the creation time DateTime obj_time = DateTime.Now; public string sRuta { get; set; } public override void OnEndPage(PdfWriter obj_writer, Document obj_document) { base.OnEndPage(obj_writer, obj_document); //PdfContentByte cb = obj_writer.DirectContent; //Image imgSoc = Image.GetInstance(HttpContext.Current.Server.MapPath("../../Styles/Imagenes/logo_esaner_ro.png")); //imgSoc.ScaleToFit(110,110); //imgSoc.SetAbsolutePosition(0, 750); //ColumnText ct = new ColumnText(cb); //ct.AddText(new Chunk(imgSoc, 0, 0)); } public override void OnStartPage(PdfWriter writer, Document document) { base.OnStartPage(writer, document); PdfPTable t; PdfPCell c; Image imgLogo; imgLogo = iTextSharp.text.Image.GetInstance(sRuta); imgLogo.ScaleToFit(200, 200); t = new PdfPTable(1); t.WidthPercentage = 100; float[] w = new float[1]; w[0] = 10; t.SetWidths(w); c = new PdfPCell(imgLogo); c.Border = 0; c.VerticalAlignment = Element.ALIGN_TOP; c.HorizontalAlignment = Element.ALIGN_LEFT; t.AddCell(c); document.Add(t); } public PDFHelper() { // // TODO: Agregar aquí la lógica del constructor // } }
using EBS.Domain.ValueObject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.Entity { /// <summary> /// 调拨单 明细 /// </summary> public class TransferOrder:BaseEntity { public TransferOrder() { this.CreatedOn = DateTime.Now; this.UpdatedOn = DateTime.Now; this.Status = TransferOrderStatus.Create; this.Items = new List<TransferOrderItem>(); } public int FromStoreId { get; set; } public string FromStoreName { get; set; } public int ToStoreId { get; set; } public string ToStoreName { get; set; } public string Code { get; set; } public DateTime CreatedOn { get; set; } public int CreatedBy { get; set; } public string CreatedByName { get; set; } public DateTime UpdatedOn { get; set; } public int UpdatedBy { get; set; } public string UpdatedByName { get; set; } public TransferOrderStatus Status { get; set; } public virtual List<TransferOrderItem> Items { get; set; } public void Audit(int editBy,string editByName) { if (this.Status != TransferOrderStatus.WaitAudit) { throw new Exception("必须是待审调拨单"); } this.Status = TransferOrderStatus.Audited; EditBy(editBy, editByName); } public void Cancel(int editBy,string editByName) { if (this.Status == TransferOrderStatus.Audited) { throw new Exception("已审调拨单不能作废"); } this.Status = TransferOrderStatus.Cancel; EditBy(editBy, editByName); } public void Submit(int editBy, string editByName) { if (this.Status != TransferOrderStatus.Create) { throw new Exception("只能提交初始状态的单据"); } this.Status = TransferOrderStatus.WaitAudit; EditBy(editBy, editByName); } public void Reject(int editBy, string editByName) { if (this.Status != TransferOrderStatus.WaitAudit) { throw new Exception("只能驳回待审单据"); } this.Status = TransferOrderStatus.Create; EditBy(editBy, editByName); } private void EditBy(int editBy, string editByName) { this.UpdatedBy = editBy; this.UpdatedByName = editByName; this.UpdatedOn = DateTime.Now; } } }
// Programming Using C# @MAH // Assignment 5 // Author: Per Jonsson // Version 1 // Created: 2013-07-11 // Project: CustomerRegistry // Class: ContactManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ContactRegistry { /// <summary> /// This class is a container class for Contact objects. It saves contact /// objects in a dynamic list of the type List. /// /// The class has methods for adding a new contact, deleting and /// changing an existing contact. /// </summary> public class ContactManager { // Field private List<Contact> contactRegistry; /// <summary> /// Constructor /// </summary> public ContactManager() { contactRegistry = new List<Contact>(); // this.??.. } /// <summary> /// Property /// </summary> public int Count { get { return contactRegistry.Count; } } #region Methods /// <summary> /// Calls the overloaded method in order to add a Contact /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="addressIn"></param> /// <returns>True/false</returns> public bool AddContact(string firstName, string lastName, Address addressIn) { return AddContact(new Contact(firstName, lastName, addressIn)); } /// <summary> /// Tries to add a contact in the registry /// </summary> /// <param name="contactIn"></param> /// <returns>True/false</returns> public bool AddContact(Contact contactIn) { // Check validity to avoid program termination if (contactIn != null) { // Use copy constructor contactRegistry.Add(new Contact(contactIn)); return true; } return false; } /// <summary> /// Tries to change a selected contact, by removing the old record and adding a new /// </summary> /// <param name="contactIn"></param> /// <param name="index"></param> /// <returns>True/false</returns> public bool ChangeContact(Contact contactIn, int index) { // Check validity to avoid program termination if (contactIn != null) { // Use copy constructor contactRegistry.Insert(index, new Contact(contactIn)); // Delete old record contactRegistry.RemoveAt(index+1); return true; } return false; } /// <summary> /// Tries to delete a specified Contact /// </summary> /// <param name="index"></param> /// <returns>True/false</returns> public bool DeleteContact(int index) { if (!(CheckIndexOutOfRange(index))) { contactRegistry.RemoveAt(index); return true; } return false; } /// <summary> /// Checks if contact registry contains the selected index /// </summary> /// <param name="index"></param> /// <returns>True/false</returns> private bool CheckIndexOutOfRange(int index) { return (index < 0 || index >= this.contactRegistry.Count); } /// <summary> /// A method that returns an element of the list saved in a given position. /// </summary> /// <param name="index"></param> /// <returns>A deep copy</returns> public Contact GetContact(int index) { if (CheckIndexOutOfRange(index)) { return null; } else { return GetContactCopy(index); } } /// <summary> /// Creates a deep copy instead of a reference /// </summary> /// <param name="index"></param> /// <returns>A copy of a Contact object</returns> public Contact GetContactCopy(int index) { // Fetch reference to item at selected index Contact origObj = this.contactRegistry[index]; // Use copy constructor to allocate a new object on the heap Contact copyObj = new Contact(origObj); return copyObj; } /// <summary> /// This method prepares an array of strings, where every string is /// made up of information about the Contact object. /// </summary> /// <returns>An array of strings where every string represents a contact</returns> public string[] GetContactsInfo() { string[] strInfoStrings = new string[this.contactRegistry.Count]; int i = 0; foreach (Contact contact in this.contactRegistry) { strInfoStrings[i++] = contact.ToString(); } return strInfoStrings; } #endregion } }
using System; using System.Diagnostics.CodeAnalysis; namespace Atc.Data.Models { /// <summary> /// KeyValueItem. /// </summary> [Serializable] public class KeyValueItem { /// <summary> /// Initializes a new instance of the <see cref="KeyValueItem"/> class. /// </summary> public KeyValueItem() { this.Key = string.Empty; this.Value = string.Empty; } /// <summary> /// Initializes a new instance of the <see cref="KeyValueItem"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [SuppressMessage("Major Code Smell", "S5766:Deserializing objects without performing data validation is security-sensitive", Justification = "OK.")] public KeyValueItem(string key, string value) { this.Key = key ?? throw new ArgumentNullException(nameof(key)); this.Value = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// Gets or sets the key. /// </summary> /// <value> /// The key. /// </value> public string Key { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; set; } /// <inheritdoc /> public override string ToString() { return $"{nameof(this.Key)}: {this.Key}, {nameof(this.Value)}: {this.Value}"; } } }
using Autofac; using Tests.Pages.ActionID; using Framework.Core.Common; using NUnit.Framework; using Tests.Data.Oberon; using Tests.Pages.Oberon.Contact; namespace Tests.Projects.Oberon.Contact { public class CanCreateIndividualWithOnlyPhoneAndThatPhoneBecomesPrimaryAndDisclosure : BaseTest { private Driver Driver {get { return Scope.Resolve<Driver>(); }} [Test] [Category("oberon"), Category("oberon_smoketest"), Category("oberon_contact")] public void CanCreateIndividualWithOnlyPhoneAndThatPhoneBecomesPrimaryAndDisclosureTest() { var actionIdLogin = Scope.Resolve<ActionIdLogIn>(); actionIdLogin.LogInTenant(); // Create a contact var contact = Scope.Resolve<ContactCreate>(); var testContact = new TestContact { ContactType = ContactType.Individual, FirstName = "Leo", LastName = "Khan", PhoneNumber = "(202) 555-4477", PhoneType = "Mobile" }; contact.GoToPage(); var contactId = contact.CreateContact(testContact); // Verify contact detail page var detail = Scope.Resolve<ContactDetail>(); Assert.IsNotNull(detail.PhoneNumber()); Assert.AreEqual(testContact.PhoneType, detail.PhoneType().TrimEnd(':')); Assert.AreEqual(testContact.PhoneNumber, detail.PhoneNumber()); Assert.IsTrue(Driver.IsElementPresent(detail.PrimaryPhoneIcon), "Primary Phone icon is present"); Assert.IsTrue(Driver.IsElementPresent(detail.PrimaryDisclosurePhoneIcon), "Primary Disclosure Phone icon is present"); // delete contact detail.ClickDeleteLink(); } } }
using System.Collections.Generic; using MongoDB.Driver; using rp1_analytics_server.Models; namespace rp1_analytics_server.Services { public class CareerLogService { private readonly IMongoCollection<CareerLog> _careerLogs; public CareerLogService(ICareerLogDatabaseSettings settings) { { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _careerLogs = database.GetCollection<CareerLog>(settings.CareerLogsCollectionName); } } public List<CareerLog> Get() => _careerLogs.Find(FilterDefinition<CareerLog>.Empty).ToList(); public CareerLog Get(string id) => _careerLogs.Find<CareerLog>(book => book.Id == id).FirstOrDefault(); public CareerLog Create(CareerLog careerLog) { _careerLogs.InsertOne(careerLog); return careerLog; } public List<CareerLog> CreateMany(List<CareerLog> careerLogs) { _careerLogs.InsertMany(careerLogs); return careerLogs; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Events; public abstract class State { //Preguntar a Pablo public readonly EnableTurnEvent ev_enableturn = new EnableTurnEvent(); public enum turnstate { turninfo = 0, chooseaction = 1, qte = 2, anim = 3, } public abstract void InitState(); public abstract void UpdateState(float delta); public abstract void ExitState(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Linq.Mapping; using System.ComponentModel; namespace upSight.CartaoCorp.Identificacao.ACSOIDTSC_R { public class ACSOIDTSC_RDetalheEN : DetalheRetornoBaseEN { [Column(Name = "TpRegistro", DbType = "CHAR(1) NOT NULL")] public const string TpRegistro = "1"; #region Propriedades [Column(Name = "IdRetIdentDet", DbType = "INT NOT NULL")] public int IdRetIdentDet { get; set; } [Column(Name = "Cpf", DbType = "VARCHAR(11) NOT NULL")] public string Cpf { get; set; } [Column(Name = "DataProc", DbType = "DATETIME2 NOT NULL")] public DateTime DataProc { get; set; } [Column(Name = "IdRegistro", DbType = "VARCHAR(10) NULL")] public string IdRegistro { get; set; } [Column(Name = "NumLinha", DbType = "INT NOT NULL")] public int NumLinha { get; set; } #endregion #region Construtores public ACSOIDTSC_RDetalheEN() { } #endregion #region Métodos public override string ToString() { return String.Concat(ACSOIDTSC_RDetalheEN.TpRegistro, Convert.ToByte(this.TpIdentificacao).ToString("0"), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(this.Identificacao, 32), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(this.Cpf, 11), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(this.DataProc.ToString("yyyyMMdd"), 8), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(this.DataProc.ToString("HHmmss"), 6), Convert.ToInt32(this.StatusProc).ToString("000"), Convert.ToInt16(this.StatusCart).ToString("00"), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(this.Retorno, 50), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(String.Empty, 20), upSight.Consulta.Base.Sistema.CompletaEspacoDireita(this.IdRegistro, 10), this.NumLinha.ToString("000000")); } #endregion } }
using Microsoft; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using Xunit; using Task = System.Threading.Tasks.Task; namespace VsAsyncPackage.Tests { public class AsyncPackageTests { [VsTheory(Version = "2017-")] [InlineData(VSPackage.PackageGuidString, true)] [InlineData("11111111-2222-3333-4444-555555555555", false)] async Task LoadTestAsync(string guidString, bool expectedSuccess) { var shell = (IVsShell7)ServiceProvider.GlobalProvider.GetService(typeof(SVsShell)); Assumes.Present(shell); var guid = Guid.Parse(guidString); if (expectedSuccess) await shell.LoadPackageAsync(ref guid); else await Assert.ThrowsAnyAsync<Exception>(async () => await shell.LoadPackageAsync(ref guid)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MobilePhoneRetailer.DataLayer; namespace MobilePhoneRetailer.BusinessLayer.Factory { public interface iInvoice { void print(); void setPrice(); int getPrice(); void setCustID(); int getCustID(); void setProductID(); int getProductID(); void setAddress(); string getAddress(); } }
using System; using System.Threading; using System.Threading.Tasks; namespace O2.ToolKit.Core { public static class TaskHelper { //public static Task RunAsync(Action action) //{ // var tcs = new TaskCompletionSource<object>(); // ThreadPool.QueueUserWorkItem(_ => // { // try // { // action(); // tcs.SetResult(null); // } // catch (Exception exc) // { // tcs.SetException(exc); // } // }); // return tcs.Task; //} } }
using System; using System.Collections.Generic; namespace DemoEF.Domain.Models { public partial class TbOrder { public long Id { get; set; } public string CustomerOrderNo { get; set; } public string CustomerName { get; set; } public string CustomerTel { get; set; } public string CustomerAddrArea { get; set; } public string CustomerAddrCommunity { get; set; } public string CustomerAddrHourse { get; set; } public string CustomerMeasurementTime { get; set; } public string CustomerSituation { get; set; } public string CustomerRegistTime { get; set; } public string CustomerChudanyuan { get; set; } public string CustomerLevel { get; set; } public string CustomerRoomType { get; set; } public string CustomerRoomSize { get; set; } public string CustomerBudget { get; set; } public string CustomerOrderStatus { get; set; } public string CustomerPrice { get; set; } public string CustomerChudanbeizhu { get; set; } public int AskState { get; set; } public long? TrackAssigner { get; set; } public DateTime? TrackAssignTime { get; set; } public long? TrackUser { get; set; } public string TrackUsername { get; set; } public long? TypeinUser { get; set; } public string TypeinUsername { get; set; } public DateTime? TypeinTime { get; set; } public DateTime? LastUpdateTime { get; set; } public string ReceiveUsername { get; set; } public int? ReceiveCount { get; set; } public int? SignState { get; set; } public long? SignCompany { get; set; } public string SignPrice { get; set; } public DateTime? SignTime { get; set; } public DateTime? SignStartTime { get; set; } public string SignComment { get; set; } public DateTime? AskStarttime { get; set; } public string CustomerOrderTags { get; set; } public string TypeinComment { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace SUPPRIMER { class Program { public static string lire() { string ch; do { Console.WriteLine("Tapez une chaîne non vide"); Console.Write(" ch = "); ch = Console.ReadLine(); } while (!ch.Contains(" ")); return ch; } static void Main(string[] args) { string chaine = lire(); superflus(ref chaine); Console.WriteLine($"Votre chaîne Après suppression des espaces superflus = {chaine} "); Console.ReadKey(); } private static void superflus(ref string ch) { string nouvelleChaine = ""; string[] elements = ch.Trim().Split(' '); for (int i = 0; i < elements.Count(); i++) { if (elements[i] != "") { nouvelleChaine += elements[i]+ " "; } } ch = nouvelleChaine.Trim(); } } }
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Poc1; using System.Collections.Generic; namespace My.Functions { public static class ReturnUsers { [FunctionName("ReturnUsers")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, [CosmosDB( databaseName: "UsersDB", collectionName: "UsersContainer", ConnectionStringSetting = "myCosmosDb", SqlQuery = "SELECT * FROM Users") ] IEnumerable<Users> users, ILogger log) { log.LogInformation("Returning All Users..."); return new OkObjectResult(users); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Docller.Core.Models; using Docller.Core.Repository; using Docller.Core.Services; using Docller.Core.Storage; namespace Docller.Tests.Mocks { public class MockStorageService:StorageService { public MockStorageService(IStorageRepository repository, IBlobStorageProvider blobStorageProvider) : base(repository, blobStorageProvider) { } public override IEnumerable<File> GetPreUploadInfo(long projectId, long folderId, string[] fileNames, bool attachCADFilesToPdfs, bool patternMatchForVersions) { List<File> files = GetFilesWithAttachments(fileNames, attachCADFilesToPdfs,null); return files; } } }
using Core; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Threading.Tasks; namespace DBCore { /// <summary> /// взаимодействие комплектации заказа с БД, использует Core, Connection /// </summary> public static class KitDB { /// <summary> /// получение комплектации заказа /// </summary> /// <param name="id_order"> ID заказа </param> /// <returns> List комплектации </returns> public static async Task<List<Kit>> GetKitByOrderAsync(int id_order) { List<Kit> kits = new List<Kit>(); using (SqlConnection connection = Connection.Connect.SqlConnect()) { try { await connection.OpenAsync(); SqlCommand query = new SqlCommand("SELECT K.[ID_Kit], [Kit_name] FROM [dbo].[Kit] K " + "JOIN [dbo].[Order_Kit] KO ON K.[ID_Kit] = KO.[ID_Kit] " + "WHERE KO.[ID_Order] = @id", connection); query.Parameters.AddWithValue("@id", id_order); SqlDataReader reader = await query.ExecuteReaderAsync(); while (await reader.ReadAsync()) { Kit kit = new Kit(Convert.ToInt32(reader["ID_Kit"]), Convert.ToString(reader["Kit_name"])); kits.Add(kit); } } catch (Exception e) { kits = null; Log.Loging("DBCore.KitDB.GetKitByOrderAsync(int id_order): " + e.Message); } } return kits; } /// <summary> /// получение всех вариантов комплектации /// </summary> /// <returns> List комплектации </returns> public static async Task<List<Kit>> GetKitAsync() { List<Kit> kits = new List<Kit>(); using (SqlConnection connection = Connection.Connect.SqlConnect()) { try { await connection.OpenAsync(); SqlCommand query = new SqlCommand("SELECT [ID_Kit], [Kit_name] FROM [dbo].[Kit]", connection); SqlDataReader reader = await query.ExecuteReaderAsync(); while (await reader.ReadAsync()) { Kit kit = new Kit(Convert.ToInt32(reader["ID_Kit"]), Convert.ToString(reader["Kit_name"])); kits.Add(kit); } } catch (Exception e) { kits = null; Log.Loging("DBCore.KitDB.GetKitAsync(): " + e.Message); } } return kits; } } }
using System; namespace CarOODemo { class Program { static void Main(string[] args) { //TODO: create different cars and drive them //Car car = new Car("Ford", "Prefect"); GasCar explorer = new GasCar("Ford", "Explorer", 20, 15 ); ElectricCar leaf = new ElectricCar("Nissan", "Leaf", 75, 3); //Console.WriteLine(explorer.Make); //Console.ReadKey(); explorer.Drive(75); explorer.Drive(50); leaf.Drive(200); leaf.Drive(200); } } }
using System.Net; namespace EngageNet { public interface IEngageNetSettings { string ApiKey { get; } string ApiBaseUrl { get; } IWebProxy WebProxy { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainMenu : MonoBehaviour { [SerializeField] private GameObject logo; [SerializeField] private GameObject menus; [SerializeField] private GameObject credits; public bool showCredits; // Use this for initialization void Start () { GlobalData.GetSetCurrentActions = 6; GlobalData.Day = 1; showCredits = false; } // Update is called once per frame void Update () { } public void ShowCredits() { showCredits = !showCredits; menus.SetActive(!showCredits); credits.SetActive(showCredits); } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace VoxelSpace { // a column like a log, a top and bottom texture and a side texture, oriented based on voxel data public class ColumnVoxelSkin : IVoxelSkin { public TileTexture TopTexture { get; protected set; } public TileTexture BottomTexture { get; protected set; } public TileTexture SideTexture { get; protected set; } public IEnumerable<TileTexture> Textures { get { yield return TopTexture; yield return BottomTexture; yield return SideTexture; } } public ColumnVoxelSkin(TileTexture top, TileTexture bottom, TileTexture side) { TopTexture = top; BottomTexture = bottom; SideTexture = side; } public QuadUVs GetFaceUVs(Voxel voxel, Orientation voxelOrientation, Orientation faceNormal, Orientation faceUp, Orientation faceRight) { var orientation = (Orientation) voxel.Data; if (orientation == faceNormal) { return TopTexture.UV; } if (orientation == faceNormal.Inverse()) { return BottomTexture.UV; } var uvs = SideTexture.UV; if (!faceUp.IsParallel(orientation)) { uvs = uvs.rotatedCW; } return uvs; } } }
using Stock_Exchange_Analyzer.Exceptions; namespace Stock_Exchange_Analyzer.Data_Storage { public class Stock { string currency; string stockName; public Stock(string name, string currency) { this.StockName = name; this.Currency = currency; } public Stock(string name) { this.StockName = name; try { this.currency = CurrencyRetriever.getCurrency(name); } catch (CurrencyParseFailedException ex) { throw new CurrencyParseFailedException(ex.Message); } } [Newtonsoft.Json.JsonConstructor] public Stock() { } public string Currency { get { return currency; } set { currency = value; } } public string StockName { get { return stockName; } set { stockName = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BlackJack.model { interface ISubject { void AddSubscriber(IBlackJackObserver a_sub); void RemoveSubscriber(IBlackJackObserver a_observer); void NotifySubscriber(); } }
using System; using SecureNetRestApiSDK.Api.Models; using SNET.Core; namespace SecureNetRestApiSDK.Api.Requests { public class TransactionUpdateRequest : SecureNetRequest { #region Properties public int ReferenceTransactionId { get; set; } public string DutyAmount { get; set; } public DeveloperApplication DeveloperApplication { get; set; } #endregion #region Methods public override string GetUri() { return String.Format("api/transactions/{0}", ReferenceTransactionId); } public override HttpMethodEnum GetMethod() { return HttpMethodEnum.PUT; } #endregion } }
using gView.Framework.Data; using gView.Framework.Geometry; using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace gView.Interoperability.OGC.Dataset.GML { internal class XmlSchemaReader { private XmlDocument _schema = null; private XmlNamespaceManager _ns = null; public XmlSchemaReader(XmlDocument schema) { if (schema == null) { return; } _schema = schema; _ns = new XmlNamespaceManager(_schema.NameTable); _ns.AddNamespace("W3", "http://www.w3.org/2001/XMLSchema"); } public string[] ElementNames { get { if (_schema == null) { return null; } List<string> names = new List<string>(); foreach (XmlNode element in _schema.SelectNodes("W3:schema/W3:element[@name]", _ns)) { names.Add(element.Attributes["name"].Value); } return names.ToArray(); } } public FieldCollection ElementFields(string elementName, out string shapeFieldname, out GeometryType geomType) { shapeFieldname = ""; geomType = GeometryType.Unknown; if (_schema == null) { return null; } XmlNode elementNode = _schema.SelectSingleNode("W3:schema/W3:element[@name='" + elementName + "']", _ns); if (elementNode == null || elementNode.Attributes["type"] == null) { elementNode = _schema.SelectSingleNode("W3:schema/W3:element[@name='" + TypeWithoutPrefix(elementName) + "']", _ns); if (elementNode == null || elementNode.Attributes["type"] == null) { return null; } } string type = TypeWithoutPrefix(elementNode.Attributes["type"].Value); XmlNode complexTypeNode = _schema.SelectSingleNode("W3:schema/W3:complexType[@name='" + type + "']", _ns); if (complexTypeNode == null) { return null; } FieldCollection fields = new FieldCollection(); foreach (XmlNode eNode in complexTypeNode.SelectNodes("W3:complexContent/W3:extension/W3:sequence/W3:element", _ns)) { string name = String.Empty; if (eNode.Attributes["name"] != null) { name = eNode.Attributes["name"].Value; } FieldType fType = FieldType.String; int size = 8; XmlNode restrictionNode = eNode.SelectSingleNode("W3:simpleType/W3:restriction[@base]", _ns); if (restrictionNode != null) { switch (restrictionNode.Attributes["base"].Value.ToLower()) { case "string": fType = FieldType.String; XmlNode maxLengthNode = restrictionNode.SelectSingleNode("W3:maxLength[@value]", _ns); if (maxLengthNode != null) { size = int.Parse(maxLengthNode.Attributes["value"].Value); } break; case "decimal": fType = FieldType.Double; break; case "integer": fType = FieldType.integer; break; } } else if (eNode.Attributes["type"] != null) { switch (TypeWithoutPrefix(eNode.Attributes["type"].Value.ToLower())) { case "string": fType = FieldType.String; break; case "int": case "integer": fType = FieldType.integer; break; case "decimal": case "double": fType = FieldType.Double; break; case "geometrypropertytype": shapeFieldname = name; continue; case "polygonproperty": case "polygonpropertytype": case "multipolygonproperty": case "multipolygonpropertytype": shapeFieldname = name; geomType = GeometryType.Polygon; continue; case "linestringproperty": case "linestringpropertytype": case "multilinestringproperty": case "multilinestringpropertytype": shapeFieldname = name; geomType = GeometryType.Polyline; continue; case "pointproperty": case "pointpropertytype": shapeFieldname = name; geomType = GeometryType.Point; continue; case "multipointproperty": case "multipointpropertytype": shapeFieldname = name; geomType = GeometryType.Multipoint; continue; case "featureidtype": case "gmlobjectidtype": fType = FieldType.ID; break; case "datetime": fType = FieldType.Date; break; case "long": fType = FieldType.biginteger; break; case "short": fType = FieldType.smallinteger; break; default: break; } } else if (eNode.Attributes["ref"] != null) { switch (TypeWithoutPrefix(eNode.Attributes["ref"].Value.ToLower())) { case "polygonproperty": case "polygonpropertytype": case "multipolygonproperty": case "multipolygonpropertytype": shapeFieldname = name; geomType = GeometryType.Polygon; continue; case "linestringproperty": case "linestringpropertytype": case "multilinestringproperty": case "multilinestringpropertytype": shapeFieldname = name; geomType = GeometryType.Polyline; continue; case "pointproperty": case "pointpropertytype": shapeFieldname = name; geomType = GeometryType.Point; continue; case "multipointproperty": case "multipointpropertytype": shapeFieldname = name; geomType = GeometryType.Multipoint; continue; } } if (name != String.Empty) { fields.Add(new Field(name, fType, size)); } } return fields; } public string TargetNamespaceURI { get { if (_schema == null) { return String.Empty; } XmlNode schemaNode = _schema.SelectSingleNode("W3:schema[@targetNamespace]", _ns); if (schemaNode == null) { return String.Empty; } return schemaNode.Attributes["targetNamespace"].Value; } } public string MyNamespaceName(string elementName) { if (_schema == null) { return null; } XmlNode elementNode = _schema.SelectSingleNode("W3:schema/W3:element[@name='" + elementName + "']", _ns); if (elementNode == null || elementNode.Attributes["type"] == null) { return null; } string myns = elementNode.Attributes["type"].Value.Split(':')[0]; return myns; } private string TypeWithoutPrefix(string type) { return gView.Framework.OGC.XML.Globals.TypeWithoutPrefix(type); } } internal class XmlSchemaWriter { private List<FeatureClassSchema> _fcschemas = null; public XmlSchemaWriter(IFeatureClass fc) { if (fc == null) { return; } _fcschemas = new List<FeatureClassSchema>(); _fcschemas.Add(new FeatureClassSchema(fc.Name, fc)); } public XmlSchemaWriter(List<IFeatureClass> fcs) { if (fcs == null) { return; } _fcschemas = new List<FeatureClassSchema>(); foreach (IFeatureClass fc in fcs) { if (fc == null) { continue; } _fcschemas.Add(new FeatureClassSchema(fc.Name, fc)); } } public XmlSchemaWriter(FeatureClassSchema fcschema) { if (fcschema == null) { return; } _fcschemas = new List<FeatureClassSchema>(); _fcschemas.Add(fcschema); } public XmlSchemaWriter(List<FeatureClassSchema> fcschemas) { _fcschemas = fcschemas; } public string Write() { if (_fcschemas == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append(@"<?xml version=""1.0"" encoding=""utf-8"" ?>"); sb.Append(@"<schema targetNamespace=""http://www.gViewGIS.com/server"" xmlns:gv=""http://www.gViewGIS.com/server"" xmlns:ogc=""http://www.opengis.net/ogc"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://www.w3.org/2001/XMLSchema"" xmlns:gml=""http://www.opengis.net/gml"" elementFormDefault=""qualified"" version=""0.1"" > <import namespace=""http://www.opengis.net/gml"" schemaLocation=""http://schemas.opengeospatial.net/gml/2.1.2/feature.xsd"" /> "); foreach (FeatureClassSchema fcschema in _fcschemas) { if (fcschema == null || fcschema.FeatureClass == null) { continue; } IFeatureClass fc = fcschema.FeatureClass; sb.Append(@"<element name=""" + fcschema.FeatureClassID + @""" type=""gv:" + fcschema.FeatureClassID + @"Type"" substitutionGroup=""gml:_Feature"" /> "); sb.Append(@"<complexType name=""" + fcschema.FeatureClassID + @"Type""> <complexContent> <extension base=""gml:AbstractFeatureType""> <sequence>"); // Fields string geomTypeName = "gml:GeometryPropertyType"; switch (fc.GeometryType) { case GeometryType.Point: geomTypeName = "gml:PointPropertyType"; break; case GeometryType.Multipoint: geomTypeName = "gml:MultiPointPropertyType"; break; case GeometryType.Polyline: geomTypeName = "gml:MultiLineStringPropertyType"; break; case GeometryType.Polygon: geomTypeName = "gml:MultiPolygonPropertyType"; break; } sb.Append(@"<element name=""" + fc.ShapeFieldName.Replace("#", "") + @""" type=""" + geomTypeName + @""" minOccurs=""0"" maxOccurs=""1""/>"); foreach (IField field in fc.Fields.ToEnumerable()) { if (field.name == fc.ShapeFieldName) { continue; } sb.Append(@"<element name=""" + field.name + @""" "); switch (field.type) { case FieldType.String: sb.Append(@"> <simpleType> <restriction base=""string""> <maxLength value=""" + field.size + @"""/> </restriction> </simpleType></element>"); break; case FieldType.Float: case FieldType.Double: sb.Append(@"> <simpleType> <restriction base=""decimal""> <totalDigits value=""11""/> <fractionDigits value=""0""/> </restriction> </simpleType></element>"); break; case FieldType.smallinteger: sb.Append(@"type=""short""/>"); break; case FieldType.biginteger: sb.Append(@"type=""long""/>"); break; case FieldType.integer: sb.Append(@"type=""integer""/>"); break; case FieldType.Date: sb.Append(@"type=""datetime""/>"); break; case FieldType.ID: sb.Append(@"type=""ogc:FeatureIdType""/>"); break; default: sb.Append(@"type=""string""/>"); break; } } sb.Append(@" </sequence> </extension> </complexContent> </complexType>"); } sb.Append(@" </schema>"); return sb.ToString(); } #region HelperClasses public class FeatureClassSchema { private string _fcID; private IFeatureClass _fc; public FeatureClassSchema(string fcID, IFeatureClass fc) { _fcID = fcID; _fc = fc; } public string FeatureClassID { get { return _fcID; } } public IFeatureClass FeatureClass { get { return _fc; } } } #endregion } }
using System; using FluentAssertions; using NUnit.Framework; namespace Hatchet.Tests.HatchetConvertTests.SerializeTests { [TestFixture] public class EnumTests { [Flags] enum TestEnum { One = 1, Two = 2, Four = 4 } [Test] public void Serialize_EnumValue_CorrectValueIsWritten() { // Arrange var input = TestEnum.Four; // Act var result = HatchetConvert.Serialize(input); // Assert result.Should().Be(TestEnum.Four.ToString()); } [Test] public void Serialize_EnumFlags_CorrectValuesAreWritten() { // Arrange var input = TestEnum.One | TestEnum.Two; // Act var result = HatchetConvert.Serialize(input); // Assert result.Should().Be("[One, Two]"); } } }
using UnityEngine; using System.Collections; public class InputAxis : MonoBehaviour { public const string MOVEHORIZONTAL = "MoveHorizontal"; public const string ATTACK = "Attack"; public const string JUMP = "Jump"; }
using POGOProtos.Map.Fort; using POGOProtos.Networking.Responses; using PoGoSlackBot.Configuration; using PoGoSlackBot.Entities; using PoGoSlackBot.Extensions; using Slack.Webhooks; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PoGoSlackBot.Messages.Gym { public class GymNeutralMessage : BaseMessage { private GymDetails gymDetails; public GymNeutralMessage(GymDetails gymDetails, InstanceConfiguration configuration) : base(configuration) { this.gymDetails = gymDetails; } protected override SlackMessage CreateMessage() { var message = base.CreateMessage(); var slackAttachment = new SlackAttachment { Color = "#0000FF", Fallback = String.Format("Gym, {0}, is now neutral.", gymDetails.Name), AuthorName = String.Format("Gym, {0}, is now neutral.", gymDetails.Name), ThumbUrl = gymDetails.ImageURL, }; if (!String.IsNullOrWhiteSpace(configuration.MainConfiguration.MapURLFormat)) { slackAttachment.Title = "View on map"; slackAttachment.TitleLink = String.Format(configuration.MainConfiguration.MapURLFormat, gymDetails.Latitude.ToString().Replace(",", "."), gymDetails.Longitude.ToString().Replace(",", ".")); } message.Attachments = new List<SlackAttachment> { slackAttachment }; return message; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio4 {class AlinhaDireita { static void Main(string[] args) { { Console.WriteLine("Ana Ruivo".PadLeft(20) + "Porto".PadLeft(10)); Console.WriteLine("Joaquina Pinto".PadLeft(20) + "Aveiro".PadLeft(10)); Console.WriteLine("Miguel Costa".PadLeft(20) + "Braga".PadLeft(10)); } } } }
// Utility.cs // using System; using System.Collections; using System.Html; using System.Runtime.CompilerServices; using jQueryApi; namespace SportsLinkScript.Shared { [Imported] [IgnoreNamespace] [ScriptName("Object")] internal class WebServiceResponse { [ScriptName("d")] public object Data; } [Imported] [IgnoreNamespace] [ScriptName("Object")] internal class AddUserResponse { [ScriptName("Item1")] public long UserId; [ScriptName("Item2")] public bool NewUser; } }
using System; using OpenTK; namespace Axon { public class Transformation { public Vector3 Scale { get { return this.scale; } set { this.scale = value; this.update(); } } public Vector3 Position { get { return this.translation; } set { this.translation = value; this.update(); } } public Vector3 Rotation { get { return this.rotation; } set { this.rotation = value; this.update(); } } private Vector3 scale; private Vector3 translation; private Vector3 rotation; private Matrix4 scaleMatrix; private Matrix4 translationMatrix; private Matrix4 rotationXMatrix; private Matrix4 rotationYMatrix; private Matrix4 rotationZMatrix; public Matrix4 Matrix; public Transformation() { this.translation = new Vector3(0,0,0); this.scale = new Vector3(1,1,1); this.rotation = new Vector3(0,0,0); this.update(); } public Transformation(Vector3 Scale, Vector3 Position, Vector3 Rotation) { this.scale = Scale; this.translation = Position; this.rotation = Rotation; this.update(); } private void update() { this.scaleMatrix = Matrix4.CreateScale(this.scale); this.translationMatrix = Matrix4.CreateTranslation(this.translation); this.rotationXMatrix = Matrix4.CreateRotationX(this.rotation.X); this.rotationYMatrix = Matrix4.CreateRotationY(this.rotation.Y); this.rotationZMatrix = Matrix4.CreateRotationZ(this.rotation.Z); Matrix = Matrix4.Identity; Matrix = Matrix4.Mult(translationMatrix, Matrix); Matrix = Matrix4.Mult(rotationXMatrix, Matrix); Matrix = Matrix4.Mult(rotationYMatrix, Matrix); Matrix = Matrix4.Mult(rotationZMatrix, Matrix); Matrix = Matrix4.Mult(scaleMatrix, Matrix); } } }
using System; using System.Collections.Generic; using System.Text; namespace PaperPlane.API.ProtocolStack.Transport { internal enum PacketState { Queued, Sent, Error } }
using Fingo.Auth.Domain.Infrastructure.EventBus.Events.Base; using Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces; using Xunit; namespace Fingo.Auth.Domain.Infrastructure.Tests.EventBus { public class EventBusTests { private class BaseCustomEventClass : EventBase { public static string Results { get; set; } public string Result { get; set; } } private class CustomEventClass : BaseCustomEventClass { } private class CustomEventClass1 : BaseCustomEventClass { } [Fact] public void Can_Subscribe_All() { //Arrange var baseCustomEventClass = new BaseCustomEventClass(); var eventClass = new CustomEventClass(); var eventClass1 = new CustomEventClass1(); IEventBus eventBus = new Infrastructure.EventBus.Implementation.EventBus(); //Act eventBus.SubscribeAll(eb => { baseCustomEventClass.Result += "Received CustomEvent"; BaseCustomEventClass.Results += "Received CustomEvent"; }); eventBus.Subscribe<CustomEventClass>(cec => eventClass.Result += "Received CustomEvent"); eventBus.Subscribe<CustomEventClass1>(cec => eventClass1.Result += "Received CustomEvent"); eventBus.Publish(eventClass); eventBus.Publish(eventClass1); //Assert Assert.True(eventClass.Result == "Received CustomEvent"); Assert.True(eventClass1.Result == "Received CustomEvent"); Assert.True(baseCustomEventClass.Result == "Received CustomEventReceived CustomEvent"); Assert.True(BaseCustomEventClass.Results == "Received CustomEventReceived CustomEvent"); } [Fact] public void Can_Subscribe_One() { //Arrange var eventClass = new CustomEventClass(); IEventBus eventBus = new Infrastructure.EventBus.Implementation.EventBus(); //Act eventBus.Subscribe<CustomEventClass>(cec => cec.Result = "Received CustomEvent"); eventBus.Publish(eventClass); //Assert Assert.True(eventClass.Result == "Received CustomEvent"); } [Fact] public void Dont_Recive_Message_When_Not_Subscribing_Event() { //Arrange var eventClass = new CustomEventClass(); var eventClass1 = new CustomEventClass1(); IEventBus eventBus = new Infrastructure.EventBus.Implementation.EventBus(); //Act eventBus.Subscribe<CustomEventClass>(cec => eventClass.Result += "Received CustomEvent"); eventBus.Subscribe<CustomEventClass1>(cec => eventClass1.Result += "Received CustomEvent"); eventBus.Publish(new CustomEventClass()); //Assert Assert.True(eventClass.Result == "Received CustomEvent"); Assert.Null(eventClass1.Result); } } }
using System; using Company.Interface; namespace Company.Models { class Sale : ISale { //private string prodName; //private DateTime dateSale; //private decimal price; public Sale(string prodName, DateTime dateSale, decimal price) { this.ProdName = ProdName; this.DateSale = dateSale; this.Price = price; } public string ProdName { get; set; } public DateTime DateSale { get; set; } public decimal Price { get; set; } } }
using Pe.Stracon.Politicas.Aplicacion.Core.Base; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using System.Collections.Generic; namespace Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract { /// <summary> /// Definición del servicio de aplicación Parametro /// </summary> /// <remarks> /// Creación: GMD 22150326 <br /> /// Modificación: <br /> /// </remarks> public interface IParametroService : IGenericService { /// <summary> /// Realiza la busqueda de Parametro /// </summary> /// <param name="filtro">Filtro de Parametro</param> /// <returns>Listado de Parametro</returns> ProcessResult<List<ParametroResponse>> BuscarParametro(ParametroRequest filtro); /// <summary> /// Realiza el registro de un de Parametro Valor /// </summary> /// <param name="filtro">Parametro Valor a Registrar</param> /// <returns>Indicador de Error</returns> ProcessResult<string> RegistrarParametro(ParametroRequest filtro); /// <summary> /// Realiza la eliminación de un Parámetro /// </summary> /// <param name="filtro">Parametro Eliminar</param> /// <returns>Indicador de Error</returns> ProcessResult<string> EliminarParametro(ParametroRequest filtro); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using DrasCommon.Extensions; namespace DrasCommon.ValidationAttributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public class DateInFiscalQuarter : ValidationAttribute, IClientValidatable { string date; string quarter; public DateInFiscalQuarter(string date, string quarter, string errorMessage) : base(errorMessage) { this.date = date; this.quarter = quarter; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ValidationResult validationResult = ValidationResult.Success; if (value != null) { string endQuarter = string.Empty; switch (this.quarter) { case "1": endQuarter = DateExtensions.GetQ1End(); break; case "2": endQuarter = DateExtensions.GetQ2End(); break; case "3": endQuarter = DateExtensions.GetQ3End(); break; case "4": endQuarter = DateExtensions.GetQ4End(); break; } if (DateTime.Parse(value.ToString()) > DateTime.Parse(endQuarter)) validationResult = new ValidationResult(ErrorMessageString); } return validationResult; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { string errorMessage = ErrorMessageString; // this value is needed by the jQuery adapter ModelClientValidationRule rule = new ModelClientValidationRule(); rule.ValidationType = "dateinfiscalquarter"; // the name the jQuery adapter will use rule.ErrorMessage = errorMessage; rule.ValidationParameters.Add("date", this.date); rule.ValidationParameters.Add("quarter", this.quarter); yield return rule; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using MSTestFramework.API; using MSTestFramework.Helpers; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MSTestFramework.Tests { [TestClass] public class DataRandomizerTests { [TestMethod] public void AlphaLowerTest() { var alphaLower = DataRandomizer.CreateString(DataRandomizer.DataType.AlphaLower, 10); Assert.IsTrue(alphaLower.All(ch => char.IsLower(ch)), $"The string {alphaLower} wasn't all lowercase."); Assert.AreEqual(10, alphaLower.Length, "The string length wasn't 10."); } [TestMethod] public void AlphaUpperTest() { var alphaUpper = DataRandomizer.CreateString(DataRandomizer.DataType.AlphaUpper, 10); Assert.IsTrue(alphaUpper.All(ch => char.IsUpper(ch)), $"The string {alphaUpper} wasn't all uppercase."); Assert.AreEqual(10, alphaUpper.Length, "The string length wasn't 10."); } [TestMethod] public void AlphaLowerUpperTest() { var alphaLowerUpper = DataRandomizer.CreateString(DataRandomizer.DataType.AlphaLowerUpper, 10); Assert.IsTrue(alphaLowerUpper.Any(ch => char.IsUpper(ch)), $"The string {alphaLowerUpper} didn't contain uppercase."); Assert.IsTrue(alphaLowerUpper.Any(ch => char.IsLower(ch)), $"The string {alphaLowerUpper} didn't contain lowercase."); Assert.AreEqual(10, alphaLowerUpper.Length, "The string length wasn't 10."); } [TestMethod] public void AlphaLowerNumericTest() { var alphaLowerNumeric = DataRandomizer.CreateString(DataRandomizer.DataType.AlphaLowerNumeric, 10); Assert.IsTrue(alphaLowerNumeric.Any(ch => char.IsLower(ch)), $"The string {alphaLowerNumeric} didn't contain lowercase."); Assert.IsTrue(alphaLowerNumeric.Any(ch => char.IsNumber(ch)), $"The string {alphaLowerNumeric} didn't contain a number."); Assert.AreEqual(10, alphaLowerNumeric.Length, "The string length wasn't 10."); } [TestMethod] public void AlphaUpperNumericTest() { var alphaUpperNumeric = DataRandomizer.CreateString(DataRandomizer.DataType.AlphaUpperNumeric, 10); Assert.IsTrue(alphaUpperNumeric.Any(ch => char.IsUpper(ch)), $"The string {alphaUpperNumeric} didn't contain uppercase."); Assert.IsTrue(alphaUpperNumeric.Any(ch => char.IsNumber(ch)), $"The string {alphaUpperNumeric} didn't contain a number."); Assert.AreEqual(10, alphaUpperNumeric.Length, "The string length wasn't 10."); } [TestMethod] public void AlphaLowerUpperNumericTest() { var alphaLowerUpperNumeric = DataRandomizer.CreateString(DataRandomizer.DataType.AlphaLowerUpperNumeric, 10); Assert.IsTrue(alphaLowerUpperNumeric.Any(ch => char.IsUpper(ch)), $"The string {alphaLowerUpperNumeric} didn't contain uppercase."); Assert.IsTrue(alphaLowerUpperNumeric.Any(ch => char.IsLower(ch)), $"The string {alphaLowerUpperNumeric} didn't contain lowercase."); Assert.IsTrue(alphaLowerUpperNumeric.Any(ch => char.IsNumber(ch)), $"The string {alphaLowerUpperNumeric} didn't contain a number."); Assert.AreEqual(10, alphaLowerUpperNumeric.Length, "The string length wasn't 10."); } [TestMethod] public void NumericTest() { var numeric = DataRandomizer.CreateString(DataRandomizer.DataType.Numeric, 10); Assert.IsTrue(numeric.All(ch => char.IsNumber(ch)), $"The string {numeric} didn't contain all numbers."); Assert.AreEqual(10, numeric.Length, "The string length wasn't 10."); } } }
using System; using System.Collections.Generic; using System.Text; namespace Task_1_2._0_ { class CompGlagolit { public string compglagolit(string text) // Методы с большой, переменные с маленькой { Console.Clear(); Console.Write("Write your text: "); text = Console.ReadLine(); Console.WriteLine("Laptop says: " + text); Console.ReadLine(); return text; } } }
using Gpx; using OxyPlot.Axes; 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 PPO1 { public partial class ElevationGraph : Form { private Controller control; private Route route; private List<double> _DistanceValue = new List<double>(); private List<double> _ElevationValue = new List<double>(); public ElevationGraph() { InitializeComponent(); } public ElevationGraph(Controller control, Route route) { InitializeComponent(); this.control = control; this.route = route; MakeElevationLists(route); var plot = new OxyPlot.PlotModel(); var lines = GetLines(_DistanceValue,_ElevationValue); plot.Series.Add(lines); //plot.Series.Add(new OxyPlot.Series.FunctionSeries(Math.Sin, 0, 10, 0.1, "sin(x)")); plot1.Model = plot; Console.WriteLine("all good now"); plot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "Расстояние" }); plot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "Высота" }); } private OxyPlot.Series.Series GetLines(List<double> distanceValue, List<double> elevationValue) { OxyPlot.Series.LineSeries lines = new OxyPlot.Series.LineSeries(); for (int i = 0; i < distanceValue.Count; i++) lines.Points.Add(new OxyPlot.DataPoint(distanceValue[i], elevationValue[i])); return lines; } private void MakeElevationLists(Route route) { double CurrentDistance=0; int i = 1; GeoPoint newPoint = new GeoPoint(); foreach (RoutePoint routepoint in route.Points) { GeoPoint curPoint = new GeoPoint(); curPoint.Longitude = routepoint.Longitude; curPoint.Latitude = routepoint.Latitude; curPoint.Elevation = routepoint.Elevation; if (i >= 2) { CurrentDistance += newPoint.GetDistance(curPoint).Meters; Console.WriteLine(CurrentDistance); } _DistanceValue.Add(CurrentDistance); _ElevationValue.Add(curPoint.Elevation); i++; newPoint = curPoint; } Console.WriteLine("finished "); } } }
using ShopDAL.Interfaces; using ShopDAL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShopDAL.Repositories { public class CategoryRepository : ShopRepository<Category>, IRepository<Category> //IRepository<Category>// { public CategoryRepository(MyDBContext ctx) : base(ctx) { } //List<Category> list; //public CategoryRepository() //{ // list = new List<Category> // { // new Category{Id=1,Name="a1111111111"}, // new Category{Id=2,Name="b2222222222"}, // new Category{Id=3,Name="c3333333333"} // }; //} //public IEnumerable<Category> GetAll() //{ // return list; //} //public Category GetById(int id) //{ // throw new NotImplementedException(); //} } }
namespace Vapoteur.Migrations { using System; using System.Data.Entity.Migrations; public partial class Test2 : DbMigration { public override void Up() { RenameTable(name: "dbo.Boxes", newName: "TestBoxes"); RenameColumn(table: "dbo.Accumulateurs", name: "Box_Id", newName: "TestBox_Id"); RenameIndex(table: "dbo.Accumulateurs", name: "IX_Box_Id", newName: "IX_TestBox_Id"); DropColumn("dbo.TestBoxes", "Discriminator"); } public override void Down() { AddColumn("dbo.TestBoxes", "Discriminator", c => c.String(nullable: false, maxLength: 128)); RenameIndex(table: "dbo.Accumulateurs", name: "IX_TestBox_Id", newName: "IX_Box_Id"); RenameColumn(table: "dbo.Accumulateurs", name: "TestBox_Id", newName: "Box_Id"); RenameTable(name: "dbo.TestBoxes", newName: "Boxes"); } } }
using System; namespace Calculadora { class Program //Clase principal de nuestro proyecto { static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Black; //Fondo Console.ForegroundColor = ConsoleColor.Cyan; //Texto //Declarar Variables decimal num1 = 0, num2 = 0, resultado = 0; int n = 1; char operacion = '0'; string valor = ""; //Cuando son el mismo tipo de dato se pueden poner seguidos con , //No es necesario inicializarlo (= 0) pero es mejor try { //Bucle for para que no se termine después de un cálculo for (int i = 0; i < n; i++) { //Interactuamos con el usuario Console.WriteLine("~~~ Bienvenido a la Calculadora ~~~" + "\n" + "¿Desea realizar alguna operación? <S/N>"); valor = Console.ReadLine(); if (valor.ToUpper() == "S") { Console.WriteLine("Introduce el primer número");//Pedir el número num1 = Convert.ToDecimal(Console.ReadLine()); //Leer el número (Lo convertimos a un entero) Console.WriteLine("Introduce el segundo número"); num2 = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("Elije la operación: +, -, *, /");//Pedir la operación operacion = Convert.ToChar(Console.ReadLine()); //Condicionales // SWITCH: switch (operacion) { case '+': resultado = num1 + num2; Console.WriteLine("El resultado de la suma es: " + resultado); break; case '-': resultado = num1 - num2; Console.WriteLine("El resultado de la resta es: " + resultado); break; case '*': resultado = num1 * num2; Console.WriteLine("El resultado de la multiplicación es: " + resultado); break; case '/': resultado = num1 / num2; Console.WriteLine("El resultado de la división es: " + resultado); if (num2 == 0) { throw new ArgumentException("No se puede dividir un número por 0"); } break; default: Console.WriteLine("La opción elegida no es válida"); break; } /* IF ELSE: if (operacion == '+') { resultado = num1 + num2; Console.WriteLine("El resultado de la suma es:" + resultado); } else if (operacion == '-') { resultado = num1 - num2; Console.WriteLine("El resultado de la resta es:" + resultado); } else if (operacion == '*') { resultado = num1 * num2; Console.WriteLine("El resultado de la multiplicación es:" + resultado); } else if (operacion == '/') { resultado = num1 / num2; Console.WriteLine("El resultado de la división es:" + resultado); } else { Console.WriteLine("La opción elegida no es válida"); } */ n++; } else if (valor.ToUpper() == "N") { Console.WriteLine("Pulse cualquier tecla para salir de la calculadora"); Console.ReadKey(); } else { Console.WriteLine("La opción elegida no es válida"); n++; } Console.WriteLine("\n" + "Calculadora utilizada " + (i+1) + " veces" + "\n"); } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("Ha ocurrido un error, contacte con el soporte." + ex); throw; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyWeapon : MonoBehaviour { public BulletType bulletType; public int damage; public float speed; public float projectileLife = 3f; public Projectile projectile; public Transform spawnPoint; // Update is called once per frame public void ShootProjectile(Vector3 playerPos) // public Function to instantiate our projectile and set it parameters { //Projectile obj = Instantiate(projectile, spawnPoint.position, Quaternion.identity) as Projectile; Projectile obj = BulletPooler.instance.ReuseObject(bulletType,spawnPoint.position,spawnPoint.rotation); // Spawn VFX if(bulletType != BulletType.OwlBullet) { VFXPooler.instance.ReuseObject(VFXType.MuzzleFlashEnemy, spawnPoint.position,transform.rotation); } playerPos = playerPos + Vector3.up * 0.1f; obj.OnProjectileSpawn((playerPos - spawnPoint.position).normalized, speed, damage, projectileLife, transform.gameObject); } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace Caserraria.Projectiles { public class PhantomDaggerProj : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Phantom Dagger Proj"); //The English name of the projectile } public override void SetDefaults() { projectile.CloneDefaults(ProjectileID.MagicDagger); projectile.tileCollide = false; projectile.penetrate = -1; projectile.alpha = 50; projectile.timeLeft = 120; aiType = ProjectileID.VampireKnife; } public override void AI() { } } }
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using GalaSoft.MvvmLight.Views; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace MvvmLightSample { public class MainViewModel : ViewModelBase { private string title; public string Title { get { return title; } set { Set(ref title, value); } } public ICommand ChangeTitleCommand { get; set; } public ICommand GotoNextCommand { get; set; } public MainViewModel() { Title = "Hello World"; ChangeTitleCommand = new RelayCommand(ChangeTitle); GotoNextCommand = new RelayCommand(GotoNext); } private void GotoNext() { var navigationService = SimpleIoc.Default.GetInstance<INavigationService>(); navigationService.NavigateTo("PageTwo"); } private void ChangeTitle() { Title = "Hello MvvmLight"; } } }
using Exiled.API.Interfaces; namespace WebSiteOfFacilityManager { public class Config : IConfig { public bool IsEnabled { get; set; } = true; public static string WebSiteDataPath { get; set; } = "site/"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using DigitalFormsSteamLeak.Entity.IModels; using DigitalFormsSteamLeak.Entity.Models; namespace DigitalFormsSteamLeak.Entity.Models { [Table("T_Leak_Details")] public class LeakDetails : ILeakDetails { [Key] [Column("Leak_Details_Id")] public Guid LeakDetailsId { get; set; } [Column("User_Id")] public Guid UserId { get; set; } [Column("Unit_Id")] public Guid UnitId { get; set; } [Column("Leak_Type_Id")] public Guid LeakTypeId { get; set; } [Required] [Column("Leak_Number")] public int LeakNumber { get; set; } [Required] [Column("Scooped_Date")] public DateTime ScoopedDate { get; set; } [Required] [Column("Notification_Number")] public int NotificationNumber { get; set; } [Required] [Column("Date_Notification_Received")] public DateTime DateNotificationReceived { get; set; } [Required] [Column("Work_Order_Number")] public int WorkOrderNumber { get; set; } [Required] [Column("Date_Work_Order_Received")] public DateTime DateWorkOrderReceived { get; set; } [Required] [Column("Work_Order_Description")] public string WorkOrderDescription { get; set; } [Required] [Column("SST_Description")] public string SSTDescription { get; set; } [Required] [Column("Identified_By")] public string IdentifiedBy { get; set; } [Required] [Column("Decible_reading")] public float DecibelReading { get; set; } [Required] [Column("Height_From_Grade")] public float HeightFromGrade { get; set; } [Required] [Column("Height_From_Leak")] public float HeightFromLeak { get; set; } [Required] [Column("Existing_Hearing_Protection")] public string ExistingHearingProtection { get; set; } [Required] [Column("Populate")] public string Populate { get; set; } [Required] [Column("Plume_Size")] public float PlumeSize { get; set; } [Required] [Column("Temperature")] public float Temperature { get; set; } [Required] [Column("Orifice_Size")] public float OrificeSize { get; set; } [Required] [Column("LOC_Reading")] public float LOCReading { get; set; } [Required] [Column("LOC_Rate")] public float LOCRate { get; set; } [Required] [Column("Is_Plan_With_Process_Required")] public string IsPlanWithProcessReqired { get; set; } [Required] [Column("Is_FEWA_Required")] public string IsFEWARequired { get; set; } //[Required] //[Column("Is_Attach2_Required")] //public string IsAttach2Required { get; set; } [Required] [Column("Is_MOC_Required")] public string IsMOCRequired { get; set; } [Required] [Column("Is_Remove_Insulation_Required")] public string IsRemoveInsulationRequired { get; set; } [Required] [Column("Is_Reinstall_Insulation_Required")] public string IsReinstallInsulationRequired { get; set; } [Required] [Column("Is_ReScope_Required")] public string IsReScopeRequired { get; set; } [Required] [Column("Job_Pack_Status")] public string JobPackStatus { get; set; } [Required] [Column("Leak_Status")] public string LeakStatus { get; set; } [Required] [Column("Leak_Comments")] public string LeakComments { get; set; } public virtual LeakUser LeakUser { get; set; } public virtual LocationUnit Unit { get; set; } public virtual LeakType Leaktype { get; set; } //public virtual ICollection<IsolationSession> Isolation { get; set; } //public virtual ICollection<MalfunctionSession> Malfunction { get; set; } //public virtual ICollection<ScaffoldSession> scaffold { get; set; } //public virtual ICollection<PortalInsulationRemoveSession> Remove { get; set; } //public virtual ICollection<PortalInsulationReInstallSession> ReInstall { get; set; } //public virtual ICollection<CommentsSession> Comments { get; set; } //public virtual ICollection<MOCSession> MOC { get; set; } //public virtual ICollection<PlanWithProcessSession> Plan { get; set; } //public virtual ICollection<WorkOrderStatusSession> WorkOrder { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chapter03_02 { class CPoint4i { public int theX; public int theY; public int theZ; public int theW; public CPoint4i() { theX = 0; theY = 0; theZ = 0; theW = 0; } public int this[int aIndex] { get { if (aIndex == 0) return (theX); if (aIndex == 1) return (theY); if (aIndex == 2) return (theZ); if (aIndex == 3) return (theW); return (0); } set { if (aIndex == 0) { theX = value; } if (aIndex == 1) { theY = value; } if (aIndex == 2) { theZ = value; } if (aIndex == 3) { theW = value; } } } public int this[string aStr] { get { if (aStr.Equals("X")== true) return (theX); if (aStr.Equals("Y") == true) return (theY); if (aStr.Equals("Z") == true) return (theZ); if (aStr.Equals("W") == true) return (theW); return (0); } set { if (aStr.Equals("X") == true) { theX = value; } if (aStr.Equals("Y") == true) { theY = value; } if (aStr.Equals("Z") == true) { theZ = value; } if (aStr.Equals("W") == true) { theW = value; } } } } }
using UnityEngine; public class AudioSpecturmMeter : MonoBehaviour { [Range(10, 500)] public float value = 100.0f; // Start is called before the first frame update private void Start() { spectrumDatas = new float[windowSize]; spectrumDatasBuffer = new float[windowSize]; specturnBandTexture = new Texture2D(windowSize, 1, TextureFormat.R8, false) { filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp }; Shader.SetGlobalTexture("_SpecturmDataTex", specturnBandTexture); } private void OnDestroy() { if (specturnBandTexture != null) Destroy(specturnBandTexture); specturnBandTexture = null; } // Update is called once per frame private void Update() { AudioListener.GetSpectrumData(spectrumDatas, 0, FFTWindow.Rectangular); for (int i = 0; i < windowSize; ++i) { float a = Mathf.Atan(i * 0.05f); if (spectrumDatas[i] > spectrumDatasBuffer[i]) { spectrumDatasBuffer[i] = spectrumDatas[i]; } else { spectrumDatasBuffer[i] *= 0.98f; if (spectrumDatasBuffer[i] < 0) spectrumDatasBuffer[i] = 0; } specturnData.r = spectrumDatasBuffer[i] * value * a; specturnBandTexture.SetPixel(i, 0, specturnData); } specturnBandTexture.Apply(); //for (int x = 0; x < 4; ++x) //{ // float f = 0f; // for (int y = 0; y < 32; ++y) // f += spectrumDatasBuffer[x * 32 + y] * value; // specturnData.r = f / 32f; // specturnBandTexture.SetPixel(x, 0, specturnData); //} //specturnBandTexture.Apply(); } private int windowSize = 64; private Color specturnData; private Texture2D specturnBandTexture; private float[] spectrumDatas; private float[] spectrumDatasBuffer; }
namespace Crystal.Plot2D.Charts { public class UnroundingLabelProvider : LabelProvider<double> { } }