text
stringlengths
13
6.01M
using Anywhere2Go.DataAccess; using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess.Object; using log4net; using log4net.Repository.Hierarchy; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.Business.Master { public class CarDamageLogic { private static readonly ILog logger = LogManager.GetLogger(typeof(CarDamageLogic)); MyContext _context = null; public CarDamageLogic() { _context = new MyContext(); } public CarDamageLogic(MyContext context) { _context = context; } public BaseResult<bool?> DeleteCarDamage(int carDamageId, string accId) { BaseResult<bool?> resultDelete = new BaseResult<bool?>(); try { var req = new Repository<CarDamage>(_context); var accObj = new AccountProfileLogic(_context).getAccountProfileById(accId); string updateBy = accObj.first_name + " " + accObj.last_name; var carDamage = req.Find(t => t.CarDamageId == carDamageId && (t.IsActive.HasValue && t.IsActive.Value)).FirstOrDefault(); if (carDamage != null) { carDamage.IsActive = false; carDamage.UpdateDate = DateTime.Now; carDamage.UpdateBy = updateBy; req.SaveChanges(); resultDelete.Result = true; } else { resultDelete.StatusCode = Constant.ErrorCode.ExistingData; resultDelete.Message = Constant.ErrorMessage.ExistingData; } } catch (Exception ex) { resultDelete.StatusCode = Constant.ErrorCode.SystemError; resultDelete.Message = Constant.ErrorMessage.SystemError; resultDelete.SystemErrorMessage = ex.Message; } return resultDelete; } } }
using System; using System.Collections.Generic; using System.Linq; // ReSharper disable UseDeconstructionOnParameter // ReSharper disable once CheckNamespace namespace Microsoft.OpenApi.Models { public static class OpenApiPathItemExtensions { public static bool IsPathStartingSegmentName(this KeyValuePair<string, OpenApiPathItem> urlPath, string segmentName) { if (segmentName == null) { throw new ArgumentNullException(nameof(segmentName)); } var urlPathKey = urlPath.Key.Replace("-", string.Empty, StringComparison.Ordinal); return urlPathKey.StartsWith(segmentName, StringComparison.OrdinalIgnoreCase) || urlPathKey.StartsWith($"/{segmentName}", StringComparison.OrdinalIgnoreCase); } public static bool HasParameters(this OpenApiPathItem openApiOperation) { if (openApiOperation == null) { throw new ArgumentNullException(nameof(openApiOperation)); } return openApiOperation.Parameters.Any(); } } }
using SnowBLL.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SnowBLL.Service.Interfaces { public interface IBLService { ErrorResult GenerateError(Exception ex); } }
using System; using System.Globalization; namespace Simple.Expressions { // todo: extract common code in Add, Multiply // todo: add tests for Multiply.Reduce public class Multiply : IExpression<int> { private readonly IExpression<int> left; private readonly IExpression<int> right; public IExpression<int> Left { get { return left; } } public IExpression<int> Right { get { return right; } } public Multiply(IExpression<int> left, IExpression<int> right) { this.left = left; this.right = right; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "{0} * {1}", Left, Right); } public bool IsReducible { get { return true; } } public IExpression<int> Reduce(IEnvironment environment) { if (left.IsReducible) return new Multiply(left.Reduce(environment), right); if (right.IsReducible) return new Multiply(left, right.Reduce(environment)); return new Number(left.Value * right.Value); } public int Value { get { throw new InvalidOperationException("Multiply needs to be reduced before the value can be obtained"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace University.Data.CustomEntities { public class CardTransactionDetailsMappings { public bool IsPaid { get; set; } public decimal VideoRate { get; set; } public int CTMID { get; set; } public Nullable<decimal> UserID { get; set; } public Nullable<decimal> CategoryID { get; set; } public Nullable<decimal> ProductID { get; set; } public string TransactionID { get; set; } public Nullable<decimal> VideoID { get; set; } public Nullable<bool> IsDeleted { get; set; } public Nullable<System.DateTime> CreatedDate { get; set; } public Nullable<decimal> CreatedBy { get; set; } public Nullable<decimal> DeletedBy { get; set; } } }
using Microsoft.AspNetCore.Razor.TagHelpers; using System.Threading.Tasks; namespace Wee.UI.Core.TagHelpers { [HtmlTargetElement("bootstrap-tab-pane")] public class TabsContentItemTagHelper : TagHelper { [HtmlAttributeName("active")] public bool Active { get; set; } [HtmlAttributeName("class")] public string Class { get; set; } public TabsContentItemTagHelper() { } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { string tabPaneClass = "tab-pane"; TagHelperContent childContentAsync = await output.GetChildContentAsync(); output.Content.AppendHtml(childContentAsync.GetContent()); output.Attributes.SetAttribute("role", (object) "tabpanel"); if (this.Class.Length > 0) tabPaneClass = tabPaneClass + " " + this.Class; if (this.Active) tabPaneClass += " active"; output.Attributes.SetAttribute("class", (object) tabPaneClass); // ISSUE: reference to a compiler-generated method } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; using Selenio.Core.CustomPageFactory; using Selenio.Core.Reporting; using System; using System.Configuration; namespace Selenio.Core.SUT { public class SUTDriver { public static IWebDriver Driver; public static IReporter Reporter { get; private set; } public static void InitDriver<T>(IReporter reporter) where T : IWebDriver { Driver = Activator.CreateInstance<T>(); Reporter = reporter; } public static void InitDriver<T>(IReporter reporter, DriverOptions options) where T : IWebDriver { Driver = (T)Activator.CreateInstance(typeof(T), options); Reporter = reporter; } private static void EnsureDriver() { if (Driver == null) throw new Exception("Make sure you initialize the WebDriver using the 'InitDriver<T>()' method"); } public static T GetPage<T>() where T : PageObject { EnsureDriver(); var pageObjectInstance = Activator.CreateInstance<T>(); pageObjectInstance.Driver = Driver; double waitTimeout = double.Parse(ConfigurationManager.AppSettings["WaitTime"]?.ToString() ?? "10"); pageObjectInstance.Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(waitTimeout)); //PageFactory.InitElements(Driver, instance); PageFactory.InitElements(Driver, pageObjectInstance, new SimplePageObjectDecorator(Reporter)); return pageObjectInstance; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; namespace Ricky.Infrastructure.Core { /// <summary> /// Email helpers functionality /// </summary> public class EmailHelper { private readonly object _emailLock = new Object(); /// <summary> /// Send email /// </summary> /// <param name="to"></param> /// <param name="from"></param> /// <param name="subject"></param> /// <param name="body"></param> public void SendEmail(string to, string from, string subject, string body) { var message = new MailMessage(From(from), To(to)) { IsBodyHtml = true, Subject = subject, Body = body }; lock (_emailLock) { using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = true; smtpClient.Send(message); } } } /// <summary> /// Send email /// </summary> /// <param name="to"></param> /// <param name="from"></param> /// <param name="subject"></param> /// <param name="body"></param> /// <param name="attachment"></param> /// <param name="fileName"></param> /// <param name="mimeType"></param> public void SendEmail(string to, string from, string subject, string body, Stream attachment, string fileName, string mimeType) { var message = new MailMessage(From(from), To(to)) { IsBodyHtml = true, Subject = subject, Body = body }; if (attachment != null) { message.Attachments.Add(new Attachment(attachment, fileName, mimeType)); } lock (_emailLock) { using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = false; smtpClient.Send(message); } } } /// <summary> /// Send email /// </summary> /// <param name="to"></param> /// <param name="from"></param> /// <param name="mailSubject"></param> /// <param name="mailContent"></param> /// <param name="files"></param> /// <param name="fileNames"></param> /// <param name="mailCCs"></param> /// <returns></returns> public bool SendEmail(string to, string from, string mailSubject, string mailContent, IList<Byte[]> files, IList<string> fileNames, IList<string> mailCCs) { if (string.IsNullOrWhiteSpace(from) || string.IsNullOrWhiteSpace(to)) { return false; } var message = new MailMessage(From(from), To(to)) { IsBodyHtml = true, Subject = mailSubject, Body = mailContent }; // Mail CCs if (mailCCs != null && mailCCs.Any()) { foreach (var mailCc in mailCCs) message.CC.Add(mailCc); } // Attachment if (files != null && fileNames != null) { for (var i = 0; i < files.Count; i++) { if (fileNames[i] == null) continue; var fileName = Path.GetFileName(fileNames[i]); message.Attachments.Add(new Attachment(new MemoryStream(files[i]), fileName)); } } lock (_emailLock) { using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = false; smtpClient.Send(message); } } return true; } /// <summary> /// Send email /// </summary> /// <param name="to"></param> /// <param name="from"></param> /// <param name="mailSubject"></param> /// <param name="mailContent"></param> /// <param name="file"></param> /// <param name="fileName"></param> /// <param name="mailCCs"></param> /// <returns></returns> public bool SendEmail(string to, string from, string mailSubject, string mailContent, Byte[] file, string fileName, IList<string> mailCCs) { if (string.IsNullOrWhiteSpace(from) || string.IsNullOrWhiteSpace(to)) { return false; } var message = new MailMessage(From(from), To(to)) { IsBodyHtml = true, Subject = mailSubject, Body = mailContent }; // Mail CCs if (mailCCs != null && mailCCs.Any()) { foreach (var mailCc in mailCCs) message.CC.Add(mailCc); } // Attachment if (file != null && !string.IsNullOrWhiteSpace(fileName)) { fileName = Path.GetFileName(fileName); message.Attachments.Add(new Attachment(new MemoryStream(file), fileName)); } lock (_emailLock) { using (var smtpClient = new SmtpClient()) { smtpClient.EnableSsl = false; smtpClient.Send(message); } } return true; } /// <summary> /// Get from mail address /// </summary> /// <param name="fromEmail"></param> /// <returns></returns> public MailAddress From(string fromEmail) { return new MailAddress(fromEmail, "Beaute App"); } /// <summary> /// Get to mail address /// </summary> /// <param name="toEmail"></param> /// <returns></returns> public MailAddress To(string toEmail) { return new MailAddress(toEmail); } /// <summary> /// Get display name /// </summary> /// <returns></returns> public string GetDisplayName() { //var configurationProvider = new ConfigurationProvider(); //return configurationProvider.Sender ?? "STS Identity"; return "Beaute App"; } } }
using HelloWorld.Contracts; using HelloWorld.DAL; using System; using System.Collections.Generic; using System.Configuration; using System.Web.Http; namespace HelloWorld.API.Controllers { public class ValuesController : ApiController { private Lazy<IMessageDM> DM { get; set; } public ValuesController() { string connStr = ConfigurationManager.ConnectionStrings["cnStringSQL"].ConnectionString; if (string.IsNullOrWhiteSpace(connStr)) throw new NullReferenceException("Connection string is not set properly"); DM = new Lazy<IMessageDM>(() => new MessageDM(connStr)); } public ValuesController(IMessageDM dm) { DM = new Lazy<IMessageDM>(() => dm); } // GET api/values public string Get() { Message item = DM.Value.GetMessage(); return item.MessageString; } // GET api/values/5 public string Get(int id) { IList<Message> list = DM.Value.GetMessages(null, id); if (list?.Count > 0) return list[0].MessageString; else return null; } // POST api/values public void Post([FromBody]string value) { Message item = new Message { MessageString = value }; DM.Value.Insert(item); } // PUT api/values/5 public void Put(int id, [FromBody]string value) { Message item = new Message { ID = id, MessageString = value }; DM.Value.Update(item); } // DELETE api/values/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Text; namespace GenericDataAcessLayer { [DatabaseTableName("Person")] public class Person { public int Id { get; set; } [DatabaseColumn("fName")] [DatabaseSearchSelect] public string FirstName { get; set; } [DatabaseColumn("sName")] [DatabaseSearchSelect] public string LastName { get; set; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace todoApp.Models { public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : IBaseEntity { public Task Add(TEntity entity) { throw new NotImplementedException(); } public int Count() { throw new NotImplementedException(); } public Task<IEnumerable<TEntity>> FindAllAsync() { throw new NotImplementedException(); } public Task<TEntity> FindAsync(string id) { throw new NotImplementedException(); } public Task Remove(TEntity entity) { throw new NotImplementedException(); } public Task Update(TEntity entity) { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace HeliSimPack.MFD { public class SpeedDialBehavior : BaseMfdRenderer { [SerializeField] [Tooltip("Neelde indicating the airspeed")] RectTransform needle; [SerializeField] [Tooltip("Needle rotation (in degrees) at 0 knots")] float rotationAt0; [SerializeField] [Tooltip("Needle rotation (in degrees) at 20 knots")] float rotationAt20; [SerializeField] [Tooltip("Needle rotation (in degrees) at 40 knots")] float rotationAt40; [SerializeField] [Tooltip("Needle rotation (in degrees) at 60 knots")] float rotationAt60; [SerializeField] [Tooltip("Needle rotation (in degrees) at 80 knots")] float rotationAt80; [SerializeField] [Tooltip("Needle rotation (in degrees) at 100 knots")] float rotationAt100; [SerializeField] [Tooltip("Needle rotation (in degrees) at 120 knots")] float rotationAt120; [SerializeField] [Tooltip("Needle rotation (in degrees) at 140 knots")] float rotationAt140; [SerializeField] [Tooltip("Needle rotation (in degrees) at 160 knots")] float rotationAt160; [SerializeField] [Tooltip("Needle rotation (in degrees) at 180 knots")] float rotationAt180; [SerializeField] [Tooltip("Needle rotation (in degrees) at 200 knots")] float rotationAt200; [SerializeField] [Tooltip("The units of the speed's rolling readout")] RectTransform rollingOnes; [SerializeField] [Tooltip("Translation of rolling readout units for every 1 KTS")] float translationPer1Kts; [SerializeField] [Tooltip("The tens of the speed's rolling readout")] RectTransform rollingTens; [SerializeField] [Tooltip("Translation of rolling readout tens for every 10 KTS")] float translationPer10Kts; [SerializeField] [Tooltip("The hundreds of the speed's rolling readout")] RectTransform rollingHundreds; [SerializeField] [Tooltip("Translation of rolling readout hundreds for every 100 KTS")] float translationPer100Kts; Rigidbody rb; override public void updateRender() { // get horizontal speed as a first approximation if (null != rb) { // get horizontal speed float heading = rb.rotation.eulerAngles.y; Vector3 velocityInPlane = new Vector3(rb.velocity.x, 0, rb.velocity.z); // get forward speed from horiontal speed and heading velocityInPlane = Quaternion.AngleAxis(-heading, Vector3.up) * velocityInPlane; float SpeedMeterperSec = velocityInPlane.z > 0 ? velocityInPlane.z : 0; // convert to Knots float Ias = SpeedMeterperSec * 1.94384f; // calculate needle rotation float rotation = 0; if (Ias < 20) { rotation = rotationAt0 + (Ias - 0) / (20 - 0) * (rotationAt20 - rotationAt0); } else if (Ias < 40) { rotation = rotationAt20 + (Ias - 20) / (40 - 20) * (rotationAt40 - rotationAt20); } else if (Ias < 60) { rotation = rotationAt40 + (Ias - 40) / (60 - 40) * (rotationAt60 - rotationAt40); } else if (Ias < 80) { rotation = rotationAt60 + (Ias - 60) / (80 - 60) * (rotationAt80 - rotationAt60); } else if (Ias < 100) { rotation = rotationAt80 + (Ias - 80) / (100 - 80) * (rotationAt100 - rotationAt80); } else if (Ias < 120) { rotation = rotationAt100 + (Ias - 100) / (120 - 100) * (rotationAt120 - rotationAt100); } else if (Ias < 140) { rotation = rotationAt120 + (Ias - 120) / (140 - 120) * (rotationAt140 - rotationAt120); } else if (Ias < 160) { rotation = rotationAt140 + (Ias - 140) / (160 - 140) * (rotationAt160 - rotationAt140); } else if (Ias < 180) { rotation = rotationAt160 + (Ias - 160) / (180 - 160) * (rotationAt180 - rotationAt160); } else if (Ias <= 200) { rotation = rotationAt180 + (Ias - 180) / (200 - 180) * (rotationAt200 - rotationAt180); } // apply rotation needle.localEulerAngles = new Vector3(0, 0, rotation); // calculate and apply rolling readout units translation float onesTranslation = (Ias % 10.0f) * translationPer1Kts; rollingOnes.localPosition = new Vector3(0, onesTranslation, 0); // calculate and apply rolling readout tens translation float tensTranslation = Mathf.Floor((Ias % 100.0f) / 10.0f) * translationPer10Kts; if ((Ias % 10.0f) > 9.0f) { tensTranslation += (Ias % 10.0f - 9.0f) * translationPer10Kts; } rollingTens.localPosition = new Vector3(0, tensTranslation, 0); // calculate and apply rolling readout hundreds translation float hundredsTranslation = Mathf.Floor((Ias % 1000.0f) / 100.0f) * translationPer100Kts; if ((Ias % 100.0f) > 99.0f) { hundredsTranslation += (Ias % 100.0f - 99.0f) * translationPer100Kts; } rollingHundreds.localPosition = new Vector3(0, hundredsTranslation, 0); } } override public void setHcSetup(HelicopterSetup iHcSetup) { rb = iHcSetup.gameObject.GetComponent<Rigidbody>(); } } }
using GDS.BLL; using GDS.Comon; using GDS.Entity; using GDS.Entity.Constant; using GDS.Entity.Result; using GDS.Query; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using GDS.WebApi.Models; namespace GDS.WebApi.Controllers { public class SupplierInfoController : BaseController { // GET: SupplierInfo public ActionResult Index() { return View(); } [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetSupplierInfoList() { try { var queryParams = new NameValueCollection(); if (!ParamHelper.CheckParaQ(ref queryParams)) { return Json(new ResponseEntity<int>(RegularFunction.RegularSqlRegexText), JsonRequestBehavior.AllowGet); } var query = new SupplierInfoQuery(queryParams); var sqlCondition = new StringBuilder(); sqlCondition.Append("ISNULL(IsDelete,0)!=1"); PageRequest preq = new PageRequest { TableName = " [SupplierInfo] ", Where = sqlCondition.ToString(), Order = " Id DESC ", IsSelect = true, IsReturnRecord = true, PageSize = query.PageSize, PageIndex = query.PageIndex, FieldStr = "*" }; var result = new SupplierInfoBLL().GetDataByPage(preq); var response = new ResponseEntity<object>(true, string.Empty, new DataGridResultEntity<SupplierInfo> { TotalRecords = preq.Out_AllRecordCount, DisplayRecords = preq.Out_PageCount, ResultData = result }); return Json(response, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new ResponseEntity<object>(-999, string.Empty, ""), JsonRequestBehavior.AllowGet); } } [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetSupplierInfoById(int Id) { var result = new SupplierInfoBLL().GetDataById(Id); if (result != null) { var response = new ResponseEntity<SupplierInfo>(true, ConstantDefine.TipQuerySuccess, result); return Json(response, JsonRequestBehavior.AllowGet); } else { var response = new ResponseEntity<SupplierInfo>(ConstantDefine.TipQueryFail); return Json(response, JsonRequestBehavior.AllowGet); } } [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveSupplierInfo(SupplierInfo entity) { ResponseEntity<int> response; if (entity.Id == 0) { entity.IsDelete = 0; entity.CreateBy = ""; entity.CreateTime = DateTime.Now; entity.UpdateBy = ""; entity.UpdateTime = DateTime.Now; var result = new SupplierInfoBLL().InsertSupplierInfo(entity); response = new ResponseEntity<int>(result.Success, result.Message, result.Data); new LogBLL().LogEvent(CurrenUserInfo.LoginName, GDS.Entity.Constant.ConstantDefine.ModuleBaseData, GDS.Entity.Constant.ConstantDefine.TypeAdd, GDS.Entity.Constant.ConstantDefine.ActionSaveSupplier, $"{result.Data}"); } else { entity.UpdateBy = ""; entity.UpdateTime = DateTime.Now; var result = new SupplierInfoBLL().UpdateSupplierInfo(entity); response = new ResponseEntity<int>(result.Success, result.Message, result.Data); new LogBLL().LogEvent(CurrenUserInfo.LoginName, GDS.Entity.Constant.ConstantDefine.ModuleBaseData, GDS.Entity.Constant.ConstantDefine.TypeUpdate, GDS.Entity.Constant.ConstantDefine.ActionUpdateSupplier, $"{entity.Id}"); } return Json(response, JsonRequestBehavior.AllowGet); } [AcceptVerbs(HttpVerbs.Get)] public ActionResult DeleteSupplierInfo(int Id) { var result = new SupplierInfoBLL().DeleteDataById(Id); var response = new ResponseEntity<int>(result.Success, result.Message, result.Data); new LogBLL().LogEvent(CurrenUserInfo.LoginName, GDS.Entity.Constant.ConstantDefine.ModuleBaseData, GDS.Entity.Constant.ConstantDefine.TypeDelete, GDS.Entity.Constant.ConstantDefine.ActionDeleteSupplier, $"{Id}"); return Json(response, JsonRequestBehavior.AllowGet); } } }
using System.Diagnostics; using MeetMuch.Web.Alerts; using MeetMuch.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace MeetMuch.Web.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [AllowAnonymous] public IActionResult ErrorWithMessage(string message, string debug) { return View("Index").WithError(message, debug); } } }
using System; using System.Drawing; using System.Windows.Forms; using WindowsUpdateNotifier.Resources; namespace WindowsUpdateNotifier { public class SystemTrayIcon : IDisposable { private readonly NotifyIcon mNotifyIcon; private readonly Timer mAnimationTimer; private readonly BalloonTipHelper mBallonTipHelper; private int mSearchIconIndex; public SystemTrayIcon(IApplication application) { mNotifyIcon = new NotifyIcon { Icon = UpdateState.NoUpdatesAvailable.GetIcon(), Visible = true }; mNotifyIcon.MouseUp += (s, e) => application.OpenMenuDialog(); mNotifyIcon.BalloonTipClicked += (s, e) => application.OpenWindowsUpdateControlPanel(); mAnimationTimer = new Timer { Interval = 250 }; mAnimationTimer.Tick += (x, y) => _RefreshSearchIcon(); mBallonTipHelper = new BalloonTipHelper(mNotifyIcon); } public void Dispose() { mNotifyIcon.Visible = false; mNotifyIcon.Dispose(); mAnimationTimer.Enabled = false; mAnimationTimer.Dispose(); } public void SetupToolTip(string toolTip) { mNotifyIcon.Text = _GetStringWithMaxLength(toolTip, 60); } private string _GetStringWithMaxLength(string text, int length) { return text.Length > length ? text.Substring(0, length) : text; } public void SetIcon(UpdateState state, int availableUpdates = 0) { mSearchIconIndex = 1; mNotifyIcon.Icon = state.GetIcon(availableUpdates); mNotifyIcon.Visible = (state != UpdateState.UpdatesAvailable && AppSettings.Instance.HideIcon) == false; mAnimationTimer.Enabled = state == UpdateState.Searching && AppSettings.Instance.HideIcon == false; } public void ShowBallonTip(string title, string message, UpdateState state) { mBallonTipHelper.ShowBalloon(title, message, 15000, state.GetPopupIcon()); } private void _RefreshSearchIcon() { var icon = (Icon)ImageResources.ResourceManager.GetObject(string.Format("WindowsUpdateSearching{0}", mSearchIconIndex)); mNotifyIcon.Icon = icon; mSearchIconIndex = mSearchIconIndex == 4 ? 1 : ++mSearchIconIndex; } } }
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference Listener of type `IntPair`. Inherits from `AtomEventReferenceListener&lt;IntPair, IntPairEvent, IntPairEventReference, IntPairUnityEvent&gt;`. /// </summary> [EditorIcon("atom-icon-orange")] [AddComponentMenu("Unity Atoms/Listeners/IntPair Event Reference Listener")] public sealed class IntPairEventReferenceListener : AtomEventReferenceListener< IntPair, IntPairEvent, IntPairEventReference, IntPairUnityEvent> { } }
namespace A4CoreBlog.Data.ViewModels { public class UserProfileViewModel : UserBaseViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string Profession { get; set; } } }
using System; using System.Collections.Generic; using com.Sconit.Entity.INV; using com.Sconit.Entity.ORD; using com.Sconit.Entity.SCM; using com.Sconit.Entity.VIEW; using com.Sconit.Entity.MD; using com.Sconit.Entity.Exception; namespace com.Sconit.Service { public interface IContainerMgr { IList<ContainerDetail> CreateContainer(string containerCode, int qty); // Hu CloneContainer(ContainerDetail oldContainerDetail, int qty); } }
namespace SpeedSlidingTrainer.Application.Services.Solver { public enum SolutionStepStatus { NotSteppedYet, Stepped, Misstepped } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities; using DataAccessLayer; namespace BLL { public class WorkBusiness : IBusiness<Work> { UnitOfWork _uof; Employee emp; public WorkBusiness(Employee employee) { emp = employee; _uof = new UnitOfWork(); } public bool Add(Work item) { if (item!=null) { if (item.Name==null) { throw new Exception("Çalışan adı mutlaka girilmelidir"); } if (item.Description==null) { throw new Exception("Tanımlama adı mutlaka girilmelidir"); } if (item.StartDate==null) { throw new Exception("Giriş Tarihi mutlaka girilmelidir."); } if (item.EndDate==null) { throw new Exception("Bitiş Tarihi mutlaka girilmelidir."); } if (true) { _uof.WorkRepository.Add(item); return _uof.ApplyChanges(); } } return false; } public bool Remove(Work item) { if (item != null) { _uof.WorkRepository.Remove(item); return _uof.ApplyChanges(); } return false; } public bool Update(Work item) { if (item != null) { if (item.Name == null) { throw new Exception("Çalışan adı mutlaka girilmelidir"); } if (item.Description == null) { throw new Exception("Tanımlama adı mutlaka girilmelidir"); } if (item.StartDate == null) { throw new Exception("Giriş Tarihi mutlaka girilmelidir."); } if (item.EndDate == null) { throw new Exception("Bitiş Tarihi mutlaka girilmelidir."); } if (true) { _uof.WorkRepository.Update(item); return _uof.ApplyChanges(); } } return false; } public Work Get(int id) { if (id > 0) { return _uof.WorkRepository.Get(id); } else { throw new Exception("Id'nin 0 dan büyük olması gerekmektedir"); } } public ICollection<Work> GetAll() { return _uof.WorkRepository.GetAll(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class TestJson { public string equipment_number { get; set; } public string equipment_name { get; set; } public string equipment_level { get; set; } public string equipment_type { get; set; } public string attack_bonus { get; set; } public string defense_bonus { get; set; } public string health_bonus { get; set; } public string equipment_description { get; set; } public string rarity { get; set; } } public class TestJsonRoot { /// <summary> /// /// </summary> public List<TestJson> TestData { get; set; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Description résumée de Fournisseur /// </summary> public class Fournisseur { private int id; private String siret; private String siren; private String nom; public int Id { get { return id; } set { id = value; } } public string Siret { get { return siret; } set { siret = value; } } public string Siren { get { return siren; } set { siren = value; } } public string Nom { get { return nom; } set { nom = value; } } public Fournisseur() { // // TODO: Add constructor logic here // } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.BaseAtoms.Editor { /// <summary> /// Event property drawer of type `Collision`. Inherits from `AtomDrawer&lt;CollisionEvent&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(CollisionEvent))] public class CollisionEventDrawer : AtomDrawer<CollisionEvent> { } } #endif
using System; namespace AppStore.Infra.Data.Integration.Gateway { internal class PaymentGatewayMock { internal CreateSaleResponse Process(CreditCardTransaction transaction) { return new CreateSaleResponse { InstantBuyKey = Guid.NewGuid(), TransactionReference = Guid.NewGuid().ToString() }; } } }
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; public class CheckOnCollisions : MonoBehaviour { [SerializeField] private UnityEvent _eventCollisionAsteroid; public void OnTriggerEnter2D(Collider2D collision) { _eventCollisionAsteroid.Invoke(); } }
using IWorkFlow.Host;// BaseDataHandler引用 using IWorkFlow.ORM;// 表属性 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json;// Json转换 using System.Data; using BizService.Common;// namespace BizService.Services.Para_BizTypeDictionarySvc { // created by zhoushing // Para_BizTypeDictionary class Para_BizTypeDictionarySvc : BaseDataHandler { public override string Key { get { return "Para_BizTypeDictionarySvc"; } } [DataAction("GetData", "content")] public string GetData(string content) { try { var data = new GetDataModel();// 获取数据 Para_BizTypeDictionary sourceList = new Para_BizTypeDictionary(); data.sourceList = Utility.Database.QueryList(sourceList); // 初始化一空行 data.sourceListEdit = new Para_BizTypeDictionary(); data.sourceListEdit.sfqy = "1"; data.sourceListEdit.cjsj = DateTime.Now; return JsonConvert.SerializeObject(data); } catch (Exception ex) { ComBase.Logger(ex); return Utility.JsonMsg(false, ex.Message); } } //保存 [DataAction("Save", "content")] public string Save(string content) { try { SaveDataModel data = JsonConvert.DeserializeObject<SaveDataModel>(content); StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT TOP 1 1 FROM Para_BizTypeDictionary WHERE id = " + Convert.ToInt32(data.baseInfo.id)); DataTable dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count <= 0) { //新增 strSql = new StringBuilder(); strSql.Append("SELECT TOP 1 1 FROM Para_BizTypeDictionary WHERE lx = '" + data.baseInfo.lx + "'"); dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) return Utility.JsonMsg(false, "字典类型:" + data.baseInfo.lx + " 已存在!"); strSql = new StringBuilder(); strSql.Append("SELECT TOP 1 1 FROM Para_BizTypeDictionary WHERE mc = '" + data.baseInfo.mc + "'"); dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) return Utility.JsonMsg(false, "字典名称:" + data.baseInfo.mc + " 已存在!"); } else { //修改 strSql = new StringBuilder(); strSql.Append("SELECT TOP 1 1 FROM Para_BizTypeDictionary WHERE lx = '" + data.baseInfo.lx + "' AND id <> " + Convert.ToInt32(data.baseInfo.id)); dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) return Utility.JsonMsg(false, "字典类型:" + data.baseInfo.lx + " 已存在!"); strSql = new StringBuilder(); strSql.Append("SELECT TOP 1 1 FROM Para_BizTypeDictionary WHERE mc = '" + data.baseInfo.mc + "' AND id <> " + Convert.ToInt32(data.baseInfo.id)); dt = Utility.Database.ExcuteDataSet(strSql.ToString()).Tables[0]; if (dt.Rows.Count > 0) return Utility.JsonMsg(false, "字典名称:" + data.baseInfo.mc + " 已存在!"); } SaveData(data); return GetData(""); } catch (Exception ex) { ComBase.Logger(ex); return Utility.JsonMsg(false, "保存失败:" + ex.Message.Replace(":", " ")); } } //保存数据 public void SaveData(SaveDataModel data) { // 获取参数值 data.baseInfo.Condition.Add("id=" + data.baseInfo.id); if (Utility.Database.Update<Para_BizTypeDictionary>(data.baseInfo) <= 0) { Utility.Database.Insert<Para_BizTypeDictionary>(data.baseInfo); } } [DataAction("DeleteData", "content")] public string DeleteData(string content) { var delEnt = new Para_BizTypeDictionary(); delEnt.Condition.Add("id=" + content); if (Utility.Database.Delete(delEnt) > 0) return GetData(""); else return Utility.JsonMsg(false, "删除失败"); } } /// <summary> /// 获取数据模型 /// </summary> public class GetDataModel { public Para_BizTypeDictionary baseInfo; public List<Para_BizTypeDictionary> sourceList; public Para_BizTypeDictionary sourceListEdit; } /// <summary> /// 保存数据模型 /// </summary> public class SaveDataModel { public Para_BizTypeDictionary baseInfo; public KOGridEdit<Para_BizTypeDictionary> sourceList; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { class cajamodel { public int CajaFinal { get; set; } public int CajaInicio { get; set; } public DateTime Fecha { get; set; } public int idLocal { get; set; } } }
using Predictr.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Predictr.Interfaces { public interface IFixtureRepository { Task<List<Fixture>> GetAll(); Task<Fixture> GetSingleFixture(int? id); void Add(Fixture fixture); void Delete(Fixture fixture); Boolean FixtureExists(int id); Task SaveChanges(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace Paint { //Wenn am Panel neue sachen gemacht werden ganzes namespace auskommentieren //im Form1.cs [Design] Zeile 32 auf ... ändern // this.panel1 = new System.Windows.Forms.Panel(); public class TPanel : Panel { public TPanel() { this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.UserPaint, true); } private void InitializeComponent() { this.SuspendLayout(); this.ResumeLayout(false); } } public partial class Form1 : Form { //Variablen int x = -1; int y = -1; bool bewegung = false; Pen pen; Bitmap surface; Graphics graph; Image File; public Form1() { InitializeComponent(); surface = new Bitmap(panel1.Height, panel1.Width); panel1.BackgroundImage = surface; panel1.BackgroundImageLayout = ImageLayout.None; graph = Graphics.FromImage(surface); graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; pen = new Pen(Color.Black, 5); pen.StartCap = pen.EndCap = System.Drawing.Drawing2D.LineCap.Round; } private void panel1_MouseDown(object sender, MouseEventArgs e) { bewegung = true; x = e.X; y = e.Y; panel1.Cursor = Cursors.Cross; panel1.Invalidate(); } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (bewegung && x!=-1 && y!=-1) { graph.DrawLine(pen, new Point(x, y), e.Location); x = e.X; y = e.Y; panel1.Invalidate(); } } private void panel1_MouseUp(object sender, MouseEventArgs e) { bewegung = false; x = -1; y = -1; panel1.Cursor = Cursors.Default; panel1.Invalidate(); } private void btnsave_Click(object sender, EventArgs e) { //surface.Save(s,System.Drawing.Imaging.ImageFormat.Png); //s = "drawing"+i; //i++; SaveFileDialog s = new SaveFileDialog(); s.Filter = "JPG(*.JPG)|*.jpg"; if (s.ShowDialog() == DialogResult.OK) { surface.Save(s.FileName); } } private void pictureBox1_Click_1(object sender, EventArgs e) { PictureBox p = (PictureBox)sender; pen.Color = p.BackColor; pen.Width = 5; } private void pictureBox5_Click(object sender, EventArgs e) { PictureBox p = (PictureBox)sender; pen.Color = p.BackColor; pen.Width = 50; } private void btnOpen_Click(object sender, EventArgs e) { OpenFileDialog f = new OpenFileDialog(); f.Filter = "JPG(*.JPG)|*.jpg"; if (f.ShowDialog() == DialogResult.OK) { Bitmap loadfile = new Bitmap(f.FileName); surface = loadfile; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Handlers; using OrchardCore.ContentManagement.Metadata; using OrchardCore.Data; using YesSql.Indexes; using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Models.Indexes; using DFC.ServiceTaxonomy.GraphSync.Models; using DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Extensions; using System.Diagnostics.CodeAnalysis; namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Indexes { public class JobProfileIndexProvider : ContentHandlerBase, IScopedIndexProvider { private readonly IServiceProvider _serviceProvider; private readonly HashSet<string> _partRemoved = new HashSet<string>(); private IContentDefinitionManager? _contentDefinitionManager; public JobProfileIndexProvider(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override Task UpdatedAsync(UpdateContentContext context) { var part = context.ContentItem.As<JobProfile>(); // Validate that the content definition contains this part, this prevents indexing parts // that have been removed from the type definition, but are still present in the elements. if (part != null) { // Lazy initialization because of ISession cyclic dependency. _contentDefinitionManager ??= _serviceProvider.GetRequiredService<IContentDefinitionManager>(); // Search for this part. var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(context.ContentItem.ContentType); if (!contentTypeDefinition.Parts.Any(ctpd => ctpd.Name == nameof(JobProfile))) { context.ContentItem.Remove<JobProfile>(); _partRemoved.Add(context.ContentItem.ContentItemId); } } return Task.CompletedTask; } public string? CollectionName { get; set; } public Type ForType() => typeof(ContentItem); public void Describe(IDescriptor context) => Describe((DescribeContext<ContentItem>)context); [return: MaybeNull] public void Describe(DescribeContext<ContentItem> context) { context.For<JobProfileIndex>() .When(contentItem => contentItem.Has<JobProfile>() || _partRemoved.Contains(contentItem.ContentItemId)) .Map(contentItem => { // Remove index records of soft deleted items. if (!contentItem.Published && !contentItem.Latest) { return default!; } var part = contentItem.Content.JobProfile; if (part == null) { return default!; } var jobProfileIndex = new JobProfileIndex { ContentItemId = contentItem.ContentItemId, GraphSyncPartId = contentItem.As<GraphSyncPart>().ExtractGuid().ToString(), JobProfileTitle = contentItem.DisplayText }; jobProfileIndex.DynamicTitlePrefix = GetContentItemListAsCsv(part.DynamicTitlePrefix); jobProfileIndex.JobProfileSpecialism = GetContentItemListAsCsv(part.JobProfileSpecialism); jobProfileIndex.JobProfileCategory = GetContentItemListAsCsv(part.JobProfileCategory); jobProfileIndex.RelatedCareerProfiles = GetContentItemListAsCsv(part.Relatedcareerprofiles); jobProfileIndex.SOCCode = GetContentItemListAsCsv(part.SOCCode); jobProfileIndex.HiddenAlternativeTitle = GetContentItemListAsCsv(part.HiddenAlternativeTitle); jobProfileIndex.WorkingHoursDetail = GetContentItemListAsCsv(part.WorkingHoursDetails); jobProfileIndex.WorkingPatterns = GetContentItemListAsCsv(part.WorkingPattern); jobProfileIndex.WorkingPatternDetail = GetContentItemListAsCsv(part.WorkingPatternDetails); jobProfileIndex.UniversityEntryRequirements = GetContentItemListAsCsv(part.UniversityEntryRequirements); jobProfileIndex.UniversityRequirements = GetContentItemListAsCsv(part.RelatedUniversityRequirements); jobProfileIndex.UniversityLinks = GetContentItemListAsCsv(part.RelatedUniversityLinks); jobProfileIndex.CollegeEntryRequirements = GetContentItemListAsCsv(part.CollegeEntryRequirements); jobProfileIndex.CollegeRequirements = GetContentItemListAsCsv(part.RelatedCollegeRequirements); jobProfileIndex.CollegeLink = GetContentItemListAsCsv(part.RelatedCollegeLinks); jobProfileIndex.ApprenticeshipEntryRequirements = GetContentItemListAsCsv(part.ApprenticeshipEntryRequirements); jobProfileIndex.ApprenticeshipRequirements = GetContentItemListAsCsv(part.RelatedApprenticeshipRequirements); jobProfileIndex.ApprenticeshipLink = GetContentItemListAsCsv(part.RelatedApprenticeshipLinks); jobProfileIndex.Registration = GetContentItemListAsCsv(part.RelatedRegistrations); jobProfileIndex.DigitalSkills = GetContentItemListAsCsv(part.DigitalSkills); jobProfileIndex.RelatedSkills = GetContentItemListAsCsv(part.Relatedskills); jobProfileIndex.Location = GetContentItemListAsCsv(part.RelatedLocations); jobProfileIndex.Environment = GetContentItemListAsCsv(part.RelatedEnvironments); jobProfileIndex.Uniform = GetContentItemListAsCsv(part.RelatedUniforms); jobProfileIndex.Restriction = GetContentItemListAsCsv(part.Relatedrestrictions); return jobProfileIndex; }); } private string? GetContentItemListAsCsv(dynamic contentItemIdField) { if(contentItemIdField == null || contentItemIdField?.ContentItemIds == null) { return null; } var contentItemIds = contentItemIdField?.ContentItemIds.ToObject<IList<string>>() as IList<string>; return contentItemIds.ConvertListToCsv(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelManager : MonoBehaviour { [SerializeField] private GameObject[] tilePrefabs; [SerializeField] Grid grid; public void CreateLevel() { string[] mapData = ReadLevelText(); // char length of first index int mapX = mapData[0].ToCharArray().Length; // array length int mapY = mapData.Length; // set worldStart topleft Vector3 worldStart = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height)); // y axis for (int y = 0; y < mapY; y++) { // separate numbers one by one char[] newTiles = mapData[y].ToCharArray(); // x axis for (int x = 0; x < mapX; x++) { PlaceTile(newTiles[x].ToString(), x, y, worldStart); } } } void PlaceTile(string tileType, int x, int y, Vector3 worldStart) { int tileIndex = int.Parse(tileType); GameObject newTile = Instantiate(tilePrefabs[tileIndex], gameObject.transform); // 0.5 offset so snake moves on the center of tiles newTile.transform.position = new Vector3(worldStart.x + x + 0.5f, worldStart.y - y - 0.5f, 0f); // wall tile if (tileIndex == 6) { grid.ChangeWalkableValue(newTile, false); } } private string[] ReadLevelText() { // get a txt file from Resources folder TextAsset bindData = Resources.Load(SceneManager.GetActiveScene().name) as TextAsset; // replace newline to empty //string data = bindData.text.Replace(Environment.NewLine, string.Empty); string data = bindData.text.Replace("\n", string.Empty); // split data using - and return the split data return data.Split('-'); } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using TMPro; [ExecuteInEditMode] public class Week8Bonus : MonoBehaviour { /* * Create a function that gives the most optimal guesses for solving the "guess the number I'm thinking of between * one and some number", if the player has to tell you if your guess is higher than the target, lower than the * target, or correct. * * This function has two inputs: * - The maximum guess (maximum) * - The number I'm thinking of (target) * * Return the guesses as an array of ints. * * You can only guess whole integers, and 0.5 rounds up to 1. * * Most optimal strategy: https://en.wikipedia.org/wiki/Binary_search_algorithm. * * For Example: * - OptimalGuesses(100, 40) ➞ [50, 25, 38, 44, 41, 39, 40] * - OptimalGuesses(10, 5) ➞ [5] * - OptimalGuesses(300, 187) ➞ [150, 225, 187] * */ private int[] OptimalGuesses(int maximum, int target) { return new int[0]; } // =========================== DON'T EDIT BELOW THIS LINE =========================== // public TextMeshProUGUI optimalGuessesText; private void Update() { optimalGuessesText.text = "Optimal Guesses Assignment\n<align=left>\n"; optimalGuessesText.text += Success(Enumerable.SequenceEqual(OptimalGuesses(100, 40), new int[]{50, 25, 38, 44, 41, 39, 40})) + " correct for 100 | 40.\n"; optimalGuessesText.text += Success(Enumerable.SequenceEqual(OptimalGuesses(10, 5), new int[]{5})) + " correct for 10 | 5.\n"; optimalGuessesText.text += Success(Enumerable.SequenceEqual(OptimalGuesses(300, 187), new int[]{150, 225, 187})) + " correct for 300 | 187.\n"; } private string Success(bool test) { return test ? "<color=\"green\">PASS</color>" : "<color=\"red\">FAIL</color>"; } }
namespace GTFO.Custom.Rundown.CRundown { public class CRundown { public CRundownManifest Manifest { get; private set; } public static CRundown CreateFromFolder(string path) { return null; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using CIPMSBC; using System.Data.SqlClient; using System.IO; using System.Drawing; public partial class ExcelExport : System.Web.UI.Page { private SrchCamperDetails _objCamperDet = new SrchCamperDetails(); private General _objGen = new General(); string destFile = ConfigurationManager.AppSettings["ExcelDestinationFile"].ToString(); string excelClientFile = ConfigurationManager.AppSettings["ExcelClientFile"].ToString(); private byte[] StreamFile(string filename) { FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); // Create a byte array of file stream length byte[] ImageData = new byte[fs.Length]; //Read block of bytes from stream into the byte array fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length)); //Close the File Stream fs.Close(); return ImageData; //return the byte data } protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) GetAllCampYears(); } private void GetAllCampYears() { DataSet dsYears = new DataSet(); dsYears = _objGen.GetAllCampYears(); ddlCampYear.DataSource = dsYears; ddlCampYear.DataValueField = "ID"; ddlCampYear.DataTextField = "CampYear"; ddlCampYear.DataBind(); ddlCampYear.Items.Insert(0, new ListItem("--All Years--", "0")); } protected void btnSubmit_Click(object sender, EventArgs e) { //Additional logic for FJC admin string FederationID = string.Empty; try { FederationID = Session["FedId"].ToString(); } catch { }; if (FederationID == string.Empty) { try { byte[] returnValue; string FileName = excelClientFile + (ddlCampYear.SelectedIndex > 0 ? ddlCampYear.SelectedItem.Text + "-" : "") + String.Format("{0:M/d/yyyy}", DateTime.Now) + ".xls"; if (ddlCampYear.SelectedIndex > 0) destFile = destFile.Replace(excelClientFile.Substring(0,excelClientFile.Length-1), ddlCampYear.SelectedItem.Text); returnValue = StreamFile(destFile); if (returnValue.Length < 100000) { PopulateGrid(); return; } Response.Buffer = true; Response.Clear(); Response.ContentType = "Excel"; Response.AddHeader("content-disposition", "attachment ; filename=" + FileName); Response.BinaryWrite(returnValue); Response.Flush(); Response.End(); } catch (System.Threading.ThreadAbortException) { //string test = "debug"; // do nothing } catch (Exception ex) { PopulateGrid(); } } else { PopulateGrid(); } } private void PopulateGrid() { string Federation = "Federations: All"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); CIPDataAccess dal = new CIPDataAccess(); DataSet dsExport; string FederationID = string.Empty; try { FederationID = Session["FedId"].ToString(); SqlParameter[] param = new SqlParameter[2]; if (FederationID.Trim() == string.Empty) { param[0] = new SqlParameter("@FederationID", null); } else { Federation = "Federation: " + Session["FedName"].ToString(); param[0] = new SqlParameter("@FederationID", FederationID); } if(ddlCampYear.SelectedIndex == 0) param[1] = new SqlParameter("@Year", null); else param[1] = new SqlParameter("@Year", ddlCampYear.SelectedItem.Text); dsExport = dal.getDataset("[usp_GetViewDump]", param); string FileName = excelClientFile + (ddlCampYear.SelectedIndex > 0 ? ddlCampYear.SelectedItem.Text + "-" : "") + String.Format("{0:M/d/yyyy}", DateTime.Now) + ".xls"; Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1255"); Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName); if (dsExport.Tables[0].Rows.Count == 0) { this.Controls.Remove(gvExport); Response.Write("No matching records found."); Response.End(); } else { for(int i=0;i<dsExport.Tables[0].Rows.Count;i++) { dsExport.Tables[0].Rows[i]["Zip"] = "'" + dsExport.Tables[0].Rows[i]["Zip"]; } gvExport.DataSource = dsExport; gvExport.DataBind(); gvExport.Visible = true; hw.WriteLine("<table><tr><td><b><font size='3'>" + "Campers Data Export" + "</font></b></td></tr>"); hw.WriteLine("<tr><td><font size='2'>" + Federation + "</font></td></tr>"); hw.WriteLine("<tr><td><font size='2'>" + "Export Date: " + String.Format("{0:M/d/yyyy hh:mm tt}", DateTime.Now) + "</font></td></tr></table>"); HtmlForm form1 = (HtmlForm) Master.FindControl("form1"); form1.Controls.Clear(); form1.Controls.Add(gvExport); form1.RenderControl(hw); this.EnableViewState = false; Response.Write(tw.ToString()); Response.End(); } } catch(Exception ex) { } } protected void gvWrkQ_SelectedIndexChanged(object sender, EventArgs e) { } protected void gvExport_DataBound(object sender, EventArgs e) { } protected void gvExport_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Label mylabel = e.Row.FindControl("lblFJCID") as Label; mylabel.Text = "=TEXT(" + mylabel.Text + ",\"#\")"; Label lblAmount = e.Row.FindControl("lblAmount") as Label; lblAmount.Text = "$" + lblAmount.Text; Label lblFJCMatch = e.Row.FindControl("lblFJCMatch") as Label; lblFJCMatch.Text = "$" + lblFJCMatch.Text; Label lblDateOfBirth = e.Row.FindControl("lblDateOfBirth") as Label; lblDateOfBirth.Text = String.IsNullOrEmpty(lblDateOfBirth.Text)?lblDateOfBirth.Text:DateTime.Parse(lblDateOfBirth.Text).ToShortDateString(); Label lblCreatedDate = e.Row.FindControl("lblCreatedDate") as Label; lblCreatedDate.Text = String.IsNullOrEmpty(lblCreatedDate.Text)?lblCreatedDate.Text:DateTime.Parse(lblCreatedDate.Text).ToShortDateString(); Label lblSubmitDate = e.Row.FindControl("lblSubmitDate") as Label; lblSubmitDate.Text = String.IsNullOrEmpty(lblSubmitDate.Text)?lblSubmitDate.Text:DateTime.Parse(lblSubmitDate.Text).ToShortDateString(); } } //This is used to create additional header row on the top spanning multiple columns (Grouping columns) protected void GridView_Merge_Header_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { //Build custom header. GridView oGridView = (GridView)sender; GridViewRow oGridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert); //Add Header 1 TableCell oTableCell = new TableCell(); oGridViewRow.Cells.Add(CreateTableCellForGridView("Program Information", 11, Color.Black, Color.FromArgb(204, 153, 255))); //Add Header 2 oGridViewRow.Cells.Add(CreateTableCellForGridView("Camp Information", 5, Color.Black, Color.FromArgb(0, 255, 255))); //Add Header 3 oGridViewRow.Cells.Add(CreateTableCellForGridView("Basic Camper Information", 8, Color.Black, Color.FromArgb(255, 153, 204))); //Add Header 4 oGridViewRow.Cells.Add(CreateTableCellForGridView("Camper Contact Information", 5, Color.Black, Color.FromArgb(204, 255, 204))); //Add Header 5 oGridViewRow.Cells.Add(CreateTableCellForGridView("Parent Contact Information", 14, Color.Black, Color.FromArgb(255, 255, 153))); //Add Header 6 oGridViewRow.Cells.Add(CreateTableCellForGridView("Application Information", 3, Color.Black, Color.FromArgb(192, 192, 192))); //Add Header 7 oGridViewRow.Cells.Add(CreateTableCellForGridView("Marketing Source", 8, Color.Black, Color.FromArgb(255, 204, 153))); //Add Header 8 oGridViewRow.Cells.Add(CreateTableCellForGridView("Demographic Information",16,Color.Black, Color.FromArgb(153,204,255))); oGridView.Controls[0].Controls.AddAt(0, oGridViewRow); } } private TableCell CreateTableCellForGridView(string cellText, int columnSpan, Color foreColor, Color backColor) { TableCell oTableCell = new TableCell(); oTableCell.Text = cellText; oTableCell.ColumnSpan = columnSpan; oTableCell.ForeColor = foreColor; oTableCell.BackColor = backColor; oTableCell.HorizontalAlign = HorizontalAlign.Center; return oTableCell; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Support.V7.App; using Android.Telephony; using Android.Views; using Android.Webkit; using Android.Widget; using App1.Database; using App1.Model; using Java.Interop; using static Android.Telecom.Call; namespace App1.Function { class WebviewBridge : Java.Lang.Object { public string GetAddress() { return address; } public bool GetKakaoLoginResult() { return kakaoLoginResult; } [Export("SetAddress")] [JavascriptInterface] public void SetAddress(string address) { this.address = address; commonFunc.hideAddress(webView, confirmAddressText, resetAddressBtn); confirmAddressText.Text = address; addressDoneBtn.Text = "주소 설정하기"; } } }
using System; using System.Collections.Generic; using System.Linq; using ILogging; using ServiceDeskSVC.DataAccess; using ServiceDeskSVC.DataAccess.Models; using ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tickets; namespace ServiceDeskSVC.Managers.Managers { public class HelpDeskTicketCommentManager:IHelpDeskTicketCommentManager { private readonly IHelpDeskTicketCommentRepository _helpDeskTicketCommentRepository; private readonly ILogger _logger; private readonly INSUserRepository _nsUserRepository; private readonly IHelpDeskTicketRepository _helpDeskTicketRepository; public HelpDeskTicketCommentManager(IHelpDeskTicketCommentRepository helpDeskCommentRepository, INSUserRepository nsUserRepository, IHelpDeskTicketRepository helpDeskTicketRepository, ILogger logger) { _helpDeskTicketCommentRepository = helpDeskCommentRepository; _logger = logger; _nsUserRepository = nsUserRepository; _helpDeskTicketRepository = helpDeskTicketRepository; } public List<HelpDesk_TicketComments_vm> GetAllTicketComments(int ticketNumber) { if(ticketNumber == 0) { throw new ArgumentOutOfRangeException("TicketId cannot be 0."); } HelpDesk_Tickets relatedTicket = _helpDeskTicketRepository.GetTicketByID(ticketNumber); var allComments = _helpDeskTicketCommentRepository.GetAllTicketComments(relatedTicket.Id); if(allComments == null) { _logger.Warn("There are no comments for the ticket."); } return allComments.Select(mapEntityToViewModelTicketComments).ToList(); } public bool DeleteTicketCommentById(int id) { if(id == 0) { throw new ArgumentOutOfRangeException("Id cannot be 0."); } return _helpDeskTicketCommentRepository.DeleteTicketCommentById(id); } public int CreateTicketComment(int ticketId, HelpDesk_TicketComments_vm comment) { if(ticketId == 0) { throw new ArgumentOutOfRangeException("TicketId cannot be 0."); } return _helpDeskTicketCommentRepository.CreateTicketComment(ticketId, mapViewModelToEntityTicketComments(comment)); } public int EditTicketCommentById(int id, HelpDesk_TicketComments_vm comment) { if(id == 0) { throw new ArgumentOutOfRangeException("Id cannot be 0."); } return _helpDeskTicketCommentRepository.EditTicketCommentById(id, mapViewModelToEntityTicketComments(comment)); } private HelpDesk_TicketComments_vm mapEntityToViewModelTicketComments(HelpDesk_TicketComments EFTicketComment) { return new HelpDesk_TicketComments_vm { Id = EFTicketComment.Id, Comment = EFTicketComment.Comment, CommentDateTime = EFTicketComment.CommentDateTime, CommentTypeID = EFTicketComment.CommentTypeID, TicketID = EFTicketComment.TicketID, AuthorUserName = EFTicketComment.ServiceDesk_Users == null ? null : EFTicketComment.ServiceDesk_Users.UserName, AuthorUser = EFTicketComment.ServiceDesk_Users == null ? null : new Comment_User() { UserName = EFTicketComment.ServiceDesk_Users.UserName, DisplayName = EFTicketComment.ServiceDesk_Users.FirstName + " " + EFTicketComment.ServiceDesk_Users.LastName } }; } private HelpDesk_TicketComments mapViewModelToEntityTicketComments(HelpDesk_TicketComments_vm VMTicketComment) { ServiceDesk_Users assignedTo = _nsUserRepository.GetUserByUserName(VMTicketComment.AuthorUserName); HelpDesk_Tickets relatedTicket = _helpDeskTicketRepository.GetTicketByID(VMTicketComment.TicketID); return new HelpDesk_TicketComments { Id = VMTicketComment.Id, Author = assignedTo.Id, Comment = VMTicketComment.Comment, CommentDateTime = DateTime.UtcNow, CommentTypeID = VMTicketComment.CommentTypeID, TicketID = relatedTicket.Id }; } } }
using EntityLayer.FixDeposit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace EntityLayer.LoanRepository { public interface IFixedDepositService { Task CreatAysnc(FixedDeposit fixedDeposit); IEnumerable<FixedDeposit> GetAll(); FixedDeposit GetById(int fixedDepositId); Task UpdateAysnc(FixedDeposit fixedDeposit); Task UpdateAsync(int fixedDepositId); Task Delete(int fixedDepositId); } }
namespace Breeze.Screens { public enum BindType { OneWay, TwoWay } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OcTur.View; using OcTur.Control; namespace OcTur.View { public partial class FrmControlePermissao : Form { public FrmControlePermissao() { InitializeComponent(); } /// <summary> /// Verificar no Banco Papel Selecionado /// </summary> /// <returns>true se houver papel selecionado</returns> public string VerificarPapelPermissao() { return "papel"; } /// <summary> /// Verificar Quais Permissões foram selecionadas /// </summary> /// <returns></returns> public List<string> VerificarPermissoesSelecionadas() { return new List<string>(); } private void btnCancelar_Click(object sender, EventArgs e) { //FrmAutenticacao voltarAutenticacao = new FrmAutenticacao(); //this.Close(); //voltarAutenticacao.Show(); if (MessageBox.Show("Dejesa Cancelar Edição do Funcionário", "Permissão de Funcionários", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) this.Close(); FrmConfiguracao frmConfiguracao = new FrmConfiguracao(); this.Text = "Configuração"; } private void btnSalvar_Click(object sender, EventArgs e) { // Salvar } private void clbPapeis_SelectedIndexChanged(object sender, EventArgs e) { //evento Papel Selecionado } private void clbPermissoes_SelectedIndexChanged(object sender, EventArgs e) { // Evento Permissao Selecionado } } }
using System; using System.Collections.Generic; namespace PlayingCardGame { class Program { public static void Main(string[] args) { var game = new PlayingGame(); game.VisaMeny(); } } }
using Microsoft.EntityFrameworkCore; using System.Reflection; namespace ShapeUpp.Infrastructure { public class ActivityContext : DbContext { public ActivityContext(DbContextOptions<ActivityContext> options) : base(options) { //Database.EnsureDeleted(); //Database.EnsureCreated(); } protected override void OnModelCreating(ModelBuilder modelBuilder) { //modelBuilder.ApplyConfigurationsFromAssembly(typeof(ActivityContext).Assembly); modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace test_automation_useful_features.Helpers { public static class EnumHelpers { public static string GetEnumOptionDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : value.ToString(); } public static Dictionary<string, string> GetEnumOptionsDescriptionsAsDict<T>() where T : Enum { Dictionary<string, string> enumValList = new Dictionary<string, string>(); foreach (object value in Enum.GetValues(typeof(T))) { FieldInfo fieldInfo = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); enumValList.Add(value.ToString(), attributes.Length > 0 ? attributes[0].Description : string.Empty); } return enumValList; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XH.Infrastructure.Domain.Models { /// <summary> /// Auditable entity interface /// </summary> public interface IAuditable { /// <summary> /// Created on /// </summary> DateTime UtcCreatedOn { get; set; } /// <summary> /// Created by user id /// </summary> string CreatedBy { get; set; } /// <summary> /// Modified on /// </summary> DateTime? UtcModifiedOn { get; set; } /// <summary> /// Modified by user id /// </summary> string ModifiedBy { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Descripción breve de SubMenu /// </summary> public abstract class SubMenu { /// <summary> /// Variables generales /// </summary> #region variables_generales private String nombre; private String clase; private String redirect; #endregion /// <summary> /// CONSTRUCTOR POR DEFECTO /// </summary> #region constructor_defecto public SubMenu(){ } #endregion /// <summary> /// CONSTRUCTOR CON PARÁMETROS /// </summary> /// <param name="nombre"></param> /// <param name="clase"></param> /// <param name="redirect"></param> #region constructor_parámetros public SubMenu(String nombre,String clase,String redirect) { this.nombre = nombre; this.clase = clase; this.redirect = redirect; } #endregion /// <summary> /// VARIABLES SET/GET /// </summary> /// <returns></returns> #region variables_get_set public String getRedirect() { return redirect; } public void setRedirect(String redirect) { this.redirect = redirect; } public String getClase() { return clase; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void setClase(String clase) { this.clase = clase; } #endregion /// <summary> /// VARIABLES ABSTRACTA MOSTRAR /// </summary> /// <returns></returns>} #region variable_mostrar public abstract String mostrar(); #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Globalization; using System.IO; using System.Xml; namespace WindowsFA { public partial class FormCFLO : FormFA { static int MAXC = 20; private CashFlow cf = new CashFlow(MAXC); private System.Windows.Forms.Panel[] panel = new Panel[MAXC]; private System.Windows.Forms.Panel[] cfi = new Panel[MAXC]; private System.Windows.Forms.Label[] label = new Label[MAXC]; private System.Windows.Forms.MaskedTextBox[] nj = new MaskedTextBox[MAXC]; private System.Windows.Forms.MaskedTextBox[] cj = new MaskedTextBox[MAXC]; // Microsoft.VisualBasic.DueDate duedate = Microsoft.VisualBasic.DueDate.EndOfPeriod; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); Boolean xmlHasChanged = false; string xmlFilename = ""; string xmloutput = ""; NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; public FormCFLO() { InitializeComponent(); #region Manually Initialize Components // for (int i = 0; i < MAXC; i++) { label[i] = new System.Windows.Forms.Label(); label[i].AutoSize = true; label[i].Location = new System.Drawing.Point(3, 11); label[i].Name = "label" + i.ToString(); label[i].Size = new System.Drawing.Size(52, 13); label[i].TabIndex = 0; label[i].Text = "Period " + i.ToString(); if (i == 0) { label[i].Text = "Initial " + i.ToString(); } // cj[i] = new System.Windows.Forms.MaskedTextBox(); cj[i].Location = new System.Drawing.Point(61, 8); cj[i].Name = "cj" + i.ToString(); cj[i].Size = new System.Drawing.Size(100, 20); cj[i].Text = "0.0"; cj[i].TabIndex = 1; cj[i].TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // nj[i] = new System.Windows.Forms.MaskedTextBox(); nj[i].Location = new System.Drawing.Point(168, 8); nj[i].Name = "nj" + i.ToString(); nj[i].Size = new System.Drawing.Size(42, 20); nj[i].Text = "1"; nj[i].TabIndex = 2; nj[i].TextAlign = System.Windows.Forms.HorizontalAlignment.Right; if (i == 0) { nj[i].ReadOnly = true; } // panel[i] = new System.Windows.Forms.Panel(); panel[i].Location = new System.Drawing.Point(3, 3); panel[i].Name = "panel" + i.ToString(); panel[i].Size = new System.Drawing.Size(271, 24); panel[i].TabIndex = 1; panel[i].Controls.Add(label[i]); panel[i].Controls.Add(cj[i]); panel[i].Controls.Add(nj[i]); panel[i].SuspendLayout(); panel[i].ResumeLayout(false); panel[i].PerformLayout(); // leftcentr2.Controls.Add(panel[i]); cfi[i] = new System.Windows.Forms.Panel(); cfi[i] = panel[i]; } setformTitle("Uneven Cashflow Calculator"); this.Text = formTitle; #endregion } private void FormCFLO_Load(object sender, EventArgs e) { } private void recalc() { try { MaskedTextBox tf = (MaskedTextBox)cfi[0].Controls[1]; Double dc0 = (Double.Parse(tf.Text)); CFData d1 = new CFData(dc0, 1.0); cf.setCFData(d1, 0); for (int cj = 1; cj < cfi.Length; ++cj) { System.Windows.Forms.Panel c1 = (Panel)(cfi[cj]); MaskedTextBox tf1 = (MaskedTextBox)c1.Controls[1]; Double dc1 = (Double.Parse(tf1.Text)); MaskedTextBox tf2 = (MaskedTextBox)c1.Controls[2]; Double dc2 = (Double.Parse(tf2.Text)); CFData d2 = new CFData(dc1, dc2); cf.setCFData(d2, cj); } cf.setSafeI(Double.Parse(S.Text) / 100.0); S.Text = (cf.getSafeI() * 100.0).ToString("N", nfi); cf.setRiskI(Double.Parse(R.Text) / 100.0); R.Text = (cf.getRiskI() * 100.0).ToString("N", nfi); double dnpv1 = cf.getNPV(); npvchar.Text = Math.Round(dnpv1, 2).ToString("C", nfi); double dmirr1 = cf.getMIRR() * 100.0; mirrchar.Text = Math.Round(dmirr1, 2).ToString() + "%"; try { double dirr1 = cf.getIRR() * 100.0; irrchar.Text = Math.Round(dirr1, 2).ToString() + "%"; } catch (ArgumentException){ irrchar.Text = "No Solution"; } } catch (FormatException) { MessageBox.Show("One or more cash flow contains invalid character.\nCheck the cash flows entered before continuing.", "Input Error"); } xmlHasChanged = true; } private void button1_Click(object sender, EventArgs e) { recalc(); } public override void SaveXml(bool confirm) { if (xmlHasChanged) { if (confirm) { if (MessageBox.Show("Do you want to save the changes you made to your worksheet?", "Finance Advisor Calculator - Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes) { return; } } if (xmlFilename == "") { mainSaveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); mainSaveFileDialog.Filter = "CFLO Files (*.cfo)|*.cfo|TVM Files (*.tvm)|*.tvm|All Files (*.*)|*.*"; if (mainSaveFileDialog.ShowDialog() == DialogResult.OK) { xmlFilename = mainSaveFileDialog.FileName; } else { return; } } using (StreamWriter sw = new StreamWriter(xmlFilename, false, Encoding.Unicode)) { StringBuilder stringb = new StringBuilder(); XmlWriterSettingsLibrary settings = new XmlWriterSettingsLibrary(); using (XmlWriter writer = XmlWriter.Create(stringb, settings.maindocxmlsettings)) { /* * Sample document * <?xml version="1.0" encoding="utf-16"?> <FA> <CFLO> <SafeI>5.00</SafeI> <RiskI>10.00</RiskI> <CF id="0"> <C>-100000</C> <N>1</N> </CF> <CF id="1"> <C>100000</C> <N>5</N> </CF> <CF id="2"> <C>-100000</C> <N>5</N> </CF> </CFLO> </FA> */ // Write XML data. writer.WriteStartElement("FA"); writer.WriteStartElement("CFLO"); writer.WriteStartElement("SafeI"); writer.WriteString(S.Text); writer.WriteEndElement(); writer.WriteStartElement("RiskI"); writer.WriteString(R.Text); writer.WriteEndElement(); for (int i = 0; i < MAXC; i++) { writer.WriteStartElement("CF"); writer.WriteAttributeString("id", i.ToString()); writer.WriteStartElement("C"); writer.WriteString(cj[i].Text); writer.WriteEndElement(); writer.WriteStartElement("N"); writer.WriteString(nj[i].Text); writer.WriteEndElement(); writer.WriteEndElement(); //CF } writer.WriteEndElement(); //CFLO writer.WriteEndElement(); //FA writer.Flush(); } xmloutput = stringb.ToString(); sw.WriteLine(xmloutput); } this.Text = formTitle + " - " + xmlFilename; xmlHasChanged = false; } } public override void OpenFile(object sender, EventArgs e) { if (xmlHasChanged) { SaveXml(true); } OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); openFileDialog.Filter = "CFLO Files (*.cfo)|*.cfo|TVM Files (*.tvm)|*.tvm|All Files (*.*)|*.*"; if (openFileDialog.ShowDialog(this) == DialogResult.OK) { try { xmlFilename = openFileDialog.FileName; xmlHasChanged = true; doc.Load(xmlFilename); XmlNode root = doc.DocumentElement; XmlNodeList fa_cflo_safei = doc.GetElementsByTagName("SafeI"); XmlNodeList fa_cflo_riski = doc.GetElementsByTagName("RiskI"); XmlNodeList fa_cflo_cf = doc.GetElementsByTagName("CF"); S.Text = fa_cflo_safei[0].InnerText; R.Text = fa_cflo_riski[0].InnerText; for (int i=0; i<MAXC; i++){ cj[i].Text = doc.GetElementsByTagName("C")[i].InnerText; nj[i].Text = doc.GetElementsByTagName("N")[i].InnerText; } recalc(); /* * Sample document * <?xml version="1.0" encoding="utf-16"?> <FA> <CFLO> <SafeI>5.00</SafeI> <RiskI>10.00</RiskI> <CF id="0"> <C>-100000</C> <N>1</N> </CF> <CF id="1"> <C>100000</C> <N>5</N> </CF> <CF id="2"> <C>-100000</C> <N>5</N> </CF> </CFLO> </FA> */ this.Text = formTitle + " - " + xmlFilename; xmlHasChanged = false; } catch (XmlException) { MessageBox.Show("Invalid file.\nThe file you have opened is not valid for this application.", "Invalid file"); } } } public override void saveToolStripMenuItem_Click(object sender, EventArgs e) { SaveXml(false); } public override void SaveAsToolStripMenuItem_Click(object sender, EventArgs e) { xmlFilename = ""; xmlHasChanged = true; SaveXml(false); } public override void ExitToolsStripMenuItem_Click(object sender, EventArgs e) { if (xmlHasChanged) { SaveXml(true); } Application.Exit(); } } }
namespace Pobs.Comms { internal class TagAwaitingApprovalEmailMessage : IEmailMessage { private readonly string _tagSlug; private readonly string _tagName; internal TagAwaitingApprovalEmailMessage(string tagSlug, string tagName) { _tagSlug = tagSlug; _tagName = tagName; } public string From => "noreply@honestq.com"; public string Subject => $"Tag awaiting approval!"; public string BodyHtml => $@"<h1>Tag awaiting approval!</h1> <p>{_tagName}</p> <p><a href=""https://www.honestq.com/admin/edit/tags/{_tagSlug}"">Link</a></p>"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProyectoPP.Models { //Esta clase contiene los modelos de AspNetRoles, Permisos, dos clases que también se utilizan en la interfaz de Administación de roles. public class Roles { // Esta clase contiene los roles con sus permisos asociados si existe un objeto con un rol y un permiso entonces significa que el //rol tiene ese permiso, se usa para cargar la interfaz de administación de roles. public class Asociaciones { //Constructor de la clase public Asociaciones(string rolParam, string permisoParam) { this.rol = rolParam; this.permiso = permisoParam; } //Set y get de rol public string rol { get; set; } //Set y get de permiso public string permiso { get; set; } } //Esta clase contiene todos los roles y todos los permisos, si "existe" es verdadero entonces significa que el rol tiene asignado ese //permiso. public class GuardarAux { //Constructor de la clase public GuardarAux(string rolParam, int permisoParam, bool existeParam) { this.rol = rolParam; this.permiso = permisoParam; this.existe = existeParam; } //Constructor de la clase public GuardarAux() { } //Set y get de rol public string rol { get; set; } //Set y get de permiso public int permiso { get; set; } //Set y get de existe public bool existe { get; set; } } public List<GuardarAux> ListaGuardar { get; set; } public permisos ModeloPermisos { get; set; } public AspNetRoles ModeloNetRoles { get; set; } public List<permisos> ListaPermisos { get; set; } public List<AspNetRoles> ListaRoles { get; set; } public List<Asociaciones> ListaAscociaciones { get; set; } } }
 namespace Phonebook { using System; using System.Collections.Generic; using System.Text; public class PhonebookEntry : IComparable<PhonebookEntry> { private string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } public SortedSet<string> PhoneNumbers; public override string ToString() { StringBuilder fullEntry = new StringBuilder(); fullEntry.Append('['); fullEntry.Append(FirstName); bool hasPhone = true; foreach (var phone in PhoneNumbers) { if (hasPhone) { fullEntry.Append(": "); hasPhone = false; } else { fullEntry.Append(", "); } fullEntry.Append(phone); } fullEntry.Append(']'); return fullEntry.ToString(); } public int CompareTo(PhonebookEntry other) { return this.FirstName.CompareTo(other.FirstName); //return String.Compare(lastName, other.lastName, System.StringComparison.Ordinal); } } }
using UnityEngine; using System.Collections; public class GamePhaseState : MonoBehaviour { public enum GamePhaseType { NULL = 0, WELCOME, LEVEL_PLAY, LEVEL_END, GAME_OVER, REAL_ANGUS, INFO, CAT_FACES, PENDING, }; public GamePhaseType gamePhase { get; private set; } public GamePhaseType previousGamePhase { get; private set; } public GamePhaseType pendingPhase { get; private set; } private float pendingPhaseTimeout; private bool shouldCheckForPhaseTransition = false; public int instancesFinishedThisSession { get; private set; } public int instancesFinishedEver { get; private set; } public delegate void GameInstanceChangedEventHandler(); public event GameInstanceChangedEventHandler GameInstanceChanged; public delegate void GamePhaseChangedEventHandler(); public event GamePhaseChangedEventHandler GamePhaseChanged; public static GamePhaseState instance { get; private set; } GamePhaseUI [] gameUIs; void Awake() { instance = this; gamePhase = GamePhaseType.NULL; previousGamePhase = GamePhaseType.NULL; } void Start() { instancesFinishedEver = PersistentStorage.instance.GetIntValue ("instancesFinishedEver", 0); } // Update is called once per frame void Update () { if (shouldCheckForPhaseTransition) { CheckForPhaseTransition (); } } public bool IsPlaying() { return (gamePhase == GamePhaseType.LEVEL_PLAY); } public void RestartGame() { gamePhase = GamePhaseType.NULL; previousGamePhase = GamePhaseType.NULL; if (GameInstanceChanged != null) { GameInstanceChanged (); } if (CrossSceneState.instance.didWelcome) { TransitionToPhase (GamePhaseType.LEVEL_PLAY); } else { TransitionToPhase (GamePhaseType.WELCOME); } } IEnumerator SetupPendingPhase() { pendingPhaseTimeout = Time.time + TweakableParams.playOverPendingPause; yield return new WaitForSeconds(TweakableParams.playOverPendingPause); if (gamePhase == GamePhaseType.PENDING) { shouldCheckForPhaseTransition = true; } } public void TransitionWithPause(GamePhaseType phase) { pendingPhase = phase; TransitionToPhase (GamePhaseType.PENDING); } void CheckForPhaseTransition() { if (gamePhase == GamePhaseType.PENDING) { if (pendingPhaseTimeout <= Time.time) { TransitionToPhase (pendingPhase); } } shouldCheckForPhaseTransition = false; } bool IsLegalTransition(GamePhaseType oldPhase, GamePhaseType newPhase) { switch (oldPhase) { case GamePhaseType.NULL: return (newPhase == GamePhaseType.WELCOME || newPhase == GamePhaseType.LEVEL_PLAY); case GamePhaseType.WELCOME: return (newPhase == GamePhaseType.LEVEL_PLAY || newPhase == GamePhaseType.CAT_FACES); case GamePhaseType.LEVEL_PLAY: return (newPhase == GamePhaseType.PENDING); case GamePhaseType.PENDING: return (newPhase == GamePhaseType.GAME_OVER || newPhase == GamePhaseType.LEVEL_END); case GamePhaseType.LEVEL_END: return (newPhase == GamePhaseType.LEVEL_PLAY); case GamePhaseType.GAME_OVER: return (newPhase == GamePhaseType.REAL_ANGUS || newPhase == GamePhaseType.INFO || newPhase == GamePhaseType.CAT_FACES); case GamePhaseType.INFO: return (newPhase == GamePhaseType.GAME_OVER); case GamePhaseType.CAT_FACES: return (newPhase == GamePhaseType.WELCOME || newPhase == GamePhaseType.GAME_OVER); case GamePhaseType.REAL_ANGUS: return (newPhase == GamePhaseType.GAME_OVER); } return false; } //------------------------------------ // // Public functions // //------------------------------------ public void TransitionToPhase(GamePhaseType newPhase) { if (!IsLegalTransition (gamePhase, newPhase)) { // FIXME(dbanks) // Throw an error. return; } previousGamePhase = gamePhase; gamePhase = newPhase; if (GamePhaseState.instance.gamePhase == GamePhaseState.GamePhaseType.GAME_OVER) { instancesFinishedThisSession += 1; instancesFinishedEver += 1; PersistentStorage.instance.SetIntValue("instancesFinishedEver", instancesFinishedEver); } if (newPhase == GamePhaseType.PENDING) { StartCoroutine(SetupPendingPhase ()); } if (GamePhaseChanged != null) { GamePhaseChanged (); } } }
using EmberKernel.Plugins; using EmberKernel.Services.UI.Mvvm.Dependency; using EmberKernel.Services.UI.Mvvm.Dependency.Configuration; using System; using System.Collections.ObjectModel; using System.ComponentModel; namespace EmberKernel.Services.UI.Mvvm.ViewModel.Configuration { public class ConfigurationModelManager : ObservableCollection<object>, INotifyPropertyChanged, IConfigurationModelManager, IDisposable { public new event PropertyChangedEventHandler PropertyChanged; private IViewModelManager Manager { get; } public ConfigurationModelManager(IViewModelManager manager) { this.Manager = manager; this.Manager.Register(this); base.PropertyChanged += DependencyObject_PropertyChanged; } public void Add<TPlugin, TOptions>(ConfigurationDependencySet<TPlugin, TOptions> dependencyObject) where TPlugin : Plugin where TOptions : class, new() { dependencyObject.PropertyChanged += DependencyObject_PropertyChanged; base.Add(dependencyObject); } private void DependencyObject_PropertyChanged(object sender, PropertyChangedEventArgs e) { PropertyChanged?.Invoke(sender, e); } public void Remove<TPlugin, TOptions>(ConfigurationDependencySet<TPlugin, TOptions> dependencyObject) where TPlugin : Plugin where TOptions : class, new() { dependencyObject.PropertyChanged -= DependencyObject_PropertyChanged; base.Remove(dependencyObject); } public DependencySet GetDependency(string name) { foreach (object dependency in this) { if (dependency is DependencySet dc) { if (dc.GetType().GetGenericName(1) == name) { return dc; } } } return null; } public void Dispose() { Manager.Unregister<ConfigurationModelManager>(); } } }
using UnityEngine; using System.Collections; [System.Serializable] public class ItemObject : ScriptableObject { public string itemName = "Item Name Here"; public int itemCost = 50; public string itemDesc; public GameObject itemPrefab; // this will hold the main core of the item and it's abilities (sprite, animator etc..) // change these based on what you want your characters to do public float fireRate = .5f; public int damage = 10; public float range = 100; }
using C1.Win.C1FlexGrid; using Clients.Promotions; using Common; using Common.Extensions; using Common.Log; using Common.Presentation; using Entity; using LFP.Printing; using SessionSettings; using System; using System.Collections.Generic; using System.Data; using System.ServiceModel; using System.Threading; using System.Windows.Forms; namespace Promotions { public partial class MovieInfoForm : SkinnableFormBase { #region Private Fields private string mConnectionString = String.Empty; private string mDepartment = String.Empty; private bool mIsDirty = false; private int mProjectId = -1; private PromotionsProxy mProxy = null; private string mTaskName = String.Empty; private string mType = String.Empty; private Users mUserData = null; private string mUserName = String.Empty; #endregion #region Delegates and Events internal delegate void IdPassEventHandler(int id); internal event IdPassEventHandler IdPass; #endregion #region Constructors public MovieInfoForm(Form owner) : base() { InitializeComponent(); owner.AddOwnedForm(this); } public MovieInfoForm(int projectId, string type, string taskName, Form owner) : this(owner) { mUserData = Settings.User; mConnectionString = Settings.ConnectionString; mUserName = mUserData.UserName; mDepartment = mUserData.Department; mClientPresentation = new ClientPresentation(); mParameters = Settings.User.ToParameterStruct(); mProjectId = projectId; mType = type; mTaskName = taskName; Logging.ConnectionString = mConnectionString; } #endregion #region Public Methods public void ShowMovies(int projectIdValue) { projectId.LabelText = mProjectId.ToString(); type.LabelText = mType; taskName.LabelText = mTaskName; Cursor = Cursors.AppStarting; idGrid.BeginUpdate(); idGrid.Redraw = false; idGrid.AutoResize = false; OpenProxy(); try { List<Tuple<int, string, int>> movies = mProxy.GetMovies(projectIdValue); foreach (Tuple<int, string, int> movie in movies) { Row row = idGrid.Rows.Add(); int movieId = movie.Item1; idGrid.SetData(row.Index, 0, movieId); idGrid.SetData(row.Index, 1, movie.Item2); string rating = mProxy.GetRating(movie.Item3); idGrid.SetData(row.Index, 2, rating); using (DataTable table = mProxy.GetMovieData(projectIdValue, movieId)) { idGrid.SetCellCheck(row.Index, 3, CheckEnum.Unchecked); idGrid.SetCellCheck(row.Index, 4, CheckEnum.Unchecked); idGrid.SetCellCheck(row.Index, 5, CheckEnum.Unchecked); idGrid.SetCellCheck(row.Index, 6, CheckEnum.Unchecked); if (table.HasRows()) { DataRow dr = table.Rows[0]; if (dr["archive"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(dr["archive"]) == 1) idGrid.SetCellCheck(row.Index, 3, CheckEnum.Checked); } if (dr["digital_delivery"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(dr["digital_delivery"]) == 1) idGrid.SetCellCheck(row.Index, 4, CheckEnum.Checked); } if (dr["beta"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(dr["beta"]) == 1) idGrid.SetCellCheck(row.Index, 5, CheckEnum.Checked); } if (dr["tencom"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(dr["tencom"]) == 1) idGrid.SetCellCheck(row.Index, 6, CheckEnum.Checked); } if (dr["create_date"].GetType() != typeof(DBNull)) idGrid.SetData(row.Index, 7, dr["create_date"]); if (dr["fullname"].GetType() != typeof(DBNull)) idGrid.SetData(row.Index, 8, dr["fullname"]); } } } idGrid.Cols[0].AllowEditing = idGrid.Cols[1].AllowEditing = idGrid.Cols[2].AllowEditing = false; idGrid.Cols[7].AllowEditing = idGrid.Cols[8].AllowEditing = false; } catch(Exception e) { mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e, "Promotions", "MovieInfoForm.ShowMovies"); } finally { idGrid.Redraw = true; idGrid.AutoResize = true; idGrid.EndUpdate(); CloseProxy(); mIsDirty = false; Cursor = Cursors.Default; } } #endregion #region Protected Methods /// <summary> /// Sets the size of the form as specified by the user. /// </summary> protected override void SetFormSize() { base.SetFormSize(); FormSize formSize = Settings.GetFormSize(mConnectionString, mUserName, this.Name); //Create a default size for the Project Info form in case the user is not in the database. //Use the MinimumSize set in the designer. if (formSize == null) { formSize = new FormSize() { Form_Left = 0, Form_Top = 0, Form_Width = MinimumSize.Width, Form_Height = MinimumSize.Height }; } Left = formSize.Form_Left.Value; Top = formSize.Form_Top.Value; Width = formSize.Form_Width.Value; Height = formSize.Form_Height.Value; WindowState = FormWindowState.Normal; } #endregion #region Private Methods private void CleanUpResources() { if (mProxy != null && mProxy.State != CommunicationState.Closed) CloseProxy(); mProxy = null; } private void Clear_Click(object sender, EventArgs e) { DoClear(); } private void CloseProxy() { if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted) { Thread.Sleep(30); mProxy.Close(); } mProxy = null; } private void DoClear() { Console.Beep(); if (MessageBox.Show("Are you sure you want to clear this data?", "Clear Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; //Clear the checkboxes. for (int i = 1; i < idGrid.Rows.Count; i++) { for (int j = 3; j < 7; j++) { idGrid.SetCellCheck(i, j, CheckEnum.Unchecked); } } mIsDirty = true; } private void DoPrint() { using (FlexGridPrintDocument doc = new FlexGridPrintDocument(idGrid)) { doc.PrintHeader = doc.PrintFooter = true; doc.HeaderText = "Movie IDs - " + projectId.LabelText + " " + type.LabelText + " " + taskName.LabelText; doc.FooterText = "Page /p/"; doc.Print(); } } private void DoSave() { if (Settings.UserIsReadOnly()) return; Cursor = Cursors.AppStarting; OpenProxy(); try { idGrid.Cols[7].AllowEditing = true; idGrid.Cols[8].AllowEditing = true; string fullName = Settings.GetUserFullName(); int projectIdValue = Convert.ToInt32(projectId.LabelText); for (int i = 1; i < idGrid.Rows.Count; i++) { object data = idGrid.GetData(i, 0); if (data == null) continue; int movieId = Convert.ToInt32(data); bool isNew = false; PromotionsProjectMovies movie = mProxy.CheckMovieRecordExists(projectIdValue, movieId); if (movie == null) { isNew = true; movie = new PromotionsProjectMovies(); movie.Project_ID = projectIdValue; movie.Movie_ID = movieId; } movie.Archive = (idGrid.GetCellCheck(i, 3) == CheckEnum.Checked ? 1 : 0); movie.Digital_Delivery = (idGrid.GetCellCheck(i, 4) == CheckEnum.Checked ? 1 : 0); movie.Beta = (idGrid.GetCellCheck(i, 5) == CheckEnum.Checked ? 1 : 0); movie.TENCom = (idGrid.GetCellCheck(i, 6) == CheckEnum.Checked ? 1 : 0); movie.Create_Date = DateTime.Now; movie.Username = mUserName; if (mProxy.AddUpdateMovie(movie, isNew)) { idGrid.SetData(i, 7, DateTime.Now); idGrid.SetData(i, 8, fullName); } } idGrid.Cols[7].AllowEditing = false; idGrid.Cols[8].AllowEditing = false; } catch (Exception e) { mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e, "Promotions", "MovieInfoForm.DoSave"); } finally { mIsDirty = false; CloseProxy(); Cursor = Cursors.Default; } } private void IdGrid_CellChecked(object sender, RowColEventArgs e) { if (e.Row < 1) return; if (e.Col >= 3 && e.Col < 7) mIsDirty = true; } private void IdGrid_DoubleClick(object sender, EventArgs e) { HitTestInfo hti = idGrid.HitTest(idGrid.PointToClient(MousePosition)); if (hti.Row > 0 && hti.Column == 0) { object data = idGrid.GetData(hti.Row, hti.Column); if (data != null) { //TODO: This needs to be listened to by the main form. if (IdPass != null) IdPass(Convert.ToInt32(data)); } } } private void MovieInfoForm_FormClosing(object sender, FormClosingEventArgs e) { if (mIsDirty) { Console.Beep(); if (MessageBox.Show("You have not saved the data. Are you sure you want to close this window?", "Movie IDs", MessageBoxButtons.YesNo) == DialogResult.No) e.Cancel = true; return; } CleanUpResources(); FormSize formSize = new FormSize() { Form_Height = this.Height, Form_Width = this.Width, Form_Left = this.Left, Form_Top = this.Top, Form_Name = this.Name, Username = mUserName }; if (!Settings.SaveFormSize(mConnectionString, formSize)) mClientPresentation.ShowError("Unable to save Promotions Movie Info form size."); } private void MovieInfoForm_Load(object sender, EventArgs e) { if (DesignMode) return; SetUpForm(); } /// <summary> /// Creates the synchronous proxy. /// </summary> private void OpenProxy() { if (mProxy == null || mProxy.State == CommunicationState.Closed || mProxy.State == CommunicationState.Faulted) { mProxy = new PromotionsProxy(Settings.Endpoints["Promotions"]); mProxy.Open(); mProxy.CreatePromotionsMethods(Settings.ConnectionString, Settings.UserName); } } private void Print_Click(object sender, EventArgs e) { DoPrint(); } private void Save_Click(object sender, EventArgs e) { DoSave(); } private void SetUpForm() { DetachableTabControl.TabPages.RemoveByKey("add"); detachPage.Text = "MOVIE IDS"; ApplySkin(mParameters); SetTitle("Project Info - Movie IDs"); SetFormSize(); } #endregion } }
using System; using System.Collections.Generic; namespace Microsoft.UnifiedPlatform.Service.Common.Models { public class Log { public string LogType { get; set; } public string Message { get; set; } public double Duration { get; set; } public Dictionary<string, string> Properties { get; set; } public DateTimeOffset Time { get; set; } public string Error { get; set; } } }
using UnityEngine; using System.Collections; public class Appevent : MonoBehaviour { Appmain appmain; Appdoc appdoc; Appnet appnet; Appimg appimg; public bool isButtonDown; public bool isDrag; public Vector3 startPoint; public Vector3 endPoint; public Vector3 dragDist; public bool isMakedExitPopup; // Use this for initialization void Start () { appmain = (Appmain)FindObjectOfType(typeof(Appmain)); appdoc = (Appdoc)FindObjectOfType(typeof(Appdoc)); appnet = (Appnet)FindObjectOfType(typeof(Appnet)); appimg = (Appimg)FindObjectOfType<Appimg>(); isMakedExitPopup = false; } // Update is called once per frame void Update () { } void LateUpdate () { eventMain(); } private void eventMain() { if(Input.GetMouseButtonDown(0)) { isButtonDown = true; isDrag = true; } if(isDrag == true) { } if(Input.GetMouseButtonUp(0)) { this.isButtonDown = false; this.isDrag = false; } if(Input.GetKeyDown(KeyCode.Escape)) { switch(Appmain.gameStatus) { case GAME_STATUS.GS_TITLE: case GAME_STATUS.GS_MENU: if(Appmain.appmain.isPlayVideo == false) { if(isMakedExitPopup == false) { PopupBox.Create(DEFINE.POPUP_EXIT_QUSTION, DEFINE.POPUP_EXIT_TITLE, POPUPBOX_ACTION_TYPE.YESNO, this.gameObject, "OnConformExit"); isMakedExitPopup = true; }else { } }else { Appmain.appimg._nowFullCtl.OnClickButtonExit(); } break; } } if(Appmain.havePopupCnt > 0) { return; } switch(Appmain.gameStatus) { case GAME_STATUS.GS_TITLE: #if _TAE_ { int i = (int)XOBX_ONE_BUTTON.BUTTON_A; string tmp = string.Format("joystick button {0}", i); if(Input.GetKeyDown(tmp) == true || Input.GetKeyDown(KeyCode.Return)) { appdoc.setGameStatus(GAME_STATUS.GS_MENU); } } #endif break; case GAME_STATUS.GS_MENU: if(Appmain.appmain.isPlayVideo == false) { if(appimg.imgMainMenu != null) { appimg.imgMainMenu._LateUpdate(); } } break; } } public void OnConformExit(POPUPBOX_RETURN_TYPE rtn) { if(rtn == POPUPBOX_RETURN_TYPE.YES) { #if UNITY_EDITOR Debug.LogWarning("에디터 플레이를 중단합니다."); UnityEditor.EditorApplication.ExecuteMenuItem("Edit/Play"); #else Application.Quit(); #endif Appmain.appsound.playEffect(SOUND_EFFECT_TYPE.Button_Exit); }else { isMakedExitPopup = false; Appmain.appsound.playEffect(SOUND_EFFECT_TYPE.Button_Click); } } }
using SnowDAL.DBModels; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace SnowDAL.Repositories.Interfaces { public interface IEntityBaseRepository<T> where T : IEntityBase { Task<IEnumerable<T>> GetAll(); int Count(); T GetSingle(int id); Task<T> GetSingle(Expression<Func<T, bool>> predicate); void Add(T entity); void Update(T entity); void Delete(T entity); Task Commit(); } }
using System; using System.Collections.Generic; using Atc.OpenApi.Tests.XUnitTestData; using FluentAssertions; using Microsoft.OpenApi.Models; using Xunit; namespace Atc.OpenApi.Tests.Extensions { public class OpenApiSchemaExtensionsTests { [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasDataTypeOfListItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasDataTypeOfList(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasDataTypeOfList(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfUuidItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfUuid(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfUuid(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfByteItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfByte(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfByte(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfDateItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfDate(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfDate(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfDateTimeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfDateTime(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfDateTime(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfTimeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfTime(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfTime(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfTimestampItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfTimestamp(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfTimestamp(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfInt32ItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfInt32(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfInt32(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfInt64ItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfInt64(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfInt64(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfEmailItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfEmail(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfEmail(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeOfUriItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeOfUri(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeOfUri(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeFromSystemNamespaceItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeFromSystemNamespace(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasFormatTypeFromSystemNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeFromSystemNamespaceListItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeFromSystemNamespace_List(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeFromSystemNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasDataTypeFromSystemCollectionGenericNamespaceItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasDataTypeFromSystemCollectionGenericNamespace(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasDataTypeFromSystemCollectionGenericNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasDataTypeFromSystemCollectionGenericNamespaceListItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasDataTypeFromSystemCollectionGenericNamespace_List(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasDataTypeFromSystemCollectionGenericNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeFromDataAnnotationsNamespaceItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeFromDataAnnotationsNamespace(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasFormatTypeFromDataAnnotationsNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeFromDataAnnotationsNamespaceListItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeFromDataAnnotationsNamespace_List(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeFromDataAnnotationsNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatType(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasFormatType(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasAnyPropertiesItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasAnyProperties(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasAnyProperties(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasAnyPropertiesFormatTypeBinaryItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasAnyPropertiesFormatTypeBinary(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasAnyPropertiesFormatTypeBinary(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasAnyPropertiesFormatTypeFromSystemNamespaceItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasAnyPropertiesFormatTypeFromSystemNamespace(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasAnyPropertiesFormatTypeFromSystemNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasAnyPropertiesFormatTypeFromSystemNamespaceWithComponentSchemasItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasAnyPropertiesFormatTypeFromSystemNamespaceWithComponentSchemas(bool expected, OpenApiSchema openApiSchema, IDictionary<string, OpenApiSchema> componentSchemas) { // Act var actual = openApiSchema.HasAnyPropertiesFormatTypeFromSystemNamespace(componentSchemas); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasAnyPropertiesFormatFromSystemCollectionGenericNamespaceItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasAnyPropertiesFormatFromSystemCollectionGenericNamespace(bool expected, OpenApiSchema openApiSchema, IDictionary<string, OpenApiSchema> componentSchemas) { // Act var actual = openApiSchema.HasAnyPropertiesFormatFromSystemCollectionGenericNamespace(componentSchemas); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeFromAspNetCoreHttpNamespaceItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeFromAspNetCoreHttpNamespace(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.HasFormatTypeFromAspNetCoreHttpNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.HasFormatTypeFromAspNetCoreHttpNamespaceListItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void HasFormatTypeFromAspNetCoreHttpNamespace_List(bool expected, IList<OpenApiSchema> openApiSchemas) { // Act var actual = openApiSchemas.HasFormatTypeFromAspNetCoreHttpNamespace(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsDataTypeOfListItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsDataTypeOfList(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsDataTypeOfList(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfUuidItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfUuid(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfUuid(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfDateItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfDate(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfDate(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfTimeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfTime(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfTime(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfTimestampItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfTimestamp(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfTimestamp(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfDateTimeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfDateTime(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfDateTime(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfByteItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfByte(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfByte(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfBinaryItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfBinary(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfBinary(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfInt32ItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfInt32(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfInt32(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfInt64ItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfInt64(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfInt64(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfEmailItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfEmail(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfEmail(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsFormatTypeOfUriItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsFormatTypeOfUri(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsFormatTypeOfUri(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsSimpleDataTypeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsSimpleDataType(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsSimpleDataType(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsObjectReferenceTypeDeclaredItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsObjectReferenceTypeDeclared(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsObjectReferenceTypeDeclared(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsArrayReferenceTypeDeclaredItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsArrayReferenceTypeDeclared(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsArrayReferenceTypeDeclared(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsItemsOfSimpleDataTypeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsItemsOfSimpleDataType(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsItemsOfSimpleDataType(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsSchemaEnumItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsSchemaEnum(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsSchemaEnum(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsSchemaEnumOrPropertyEnumItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsSchemaEnumOrPropertyEnum(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsSchemaEnumOrPropertyEnum(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsSharedContractItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsSharedContract(bool expected, OpenApiSchema openApiSchema, OpenApiComponents openApiComponents) { // Act var actual = openApiSchema.IsSharedContract(openApiComponents); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetModelNameItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetModelName(string expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.GetModelName(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetModelNameEnsureFirstCharacterToUpperItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetModelName_EnsureFirstCharacterToUpper(string expected, OpenApiSchema openApiSchema, bool ensureFirstCharacterToUpper) { // Act var actual = openApiSchema.GetModelName(ensureFirstCharacterToUpper); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetModelTypeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetModelType(string expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.GetModelType(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetDataTypeItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetDataType(string expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.GetDataType(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetTitleFromPropertyByPropertyKeyItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetTitleFromPropertyByPropertyKey(string expected, OpenApiSchema openApiSchema, string propertyKey) { // Act var actual = openApiSchema.GetTitleFromPropertyByPropertyKey(propertyKey); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetEnumSchemaItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetEnumSchema(Tuple<string, int> expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.GetEnumSchema(); // Assert Assert.Equal(expected.Item1, actual.Item1); Assert.Equal(expected.Item2, actual.Item2.Enum.Count); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsRuleValidationStringItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsRuleValidationString(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsRuleValidationString(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.IsRuleValidationNumberItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void IsRuleValidationNumber(bool expected, OpenApiSchema openApiSchema) { // Act var actual = openApiSchema.IsRuleValidationNumber(); // Assert Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(TestMemberDataForOpenApiSchemaExtensions.GetSchemaByModelNameItemData), MemberType = typeof(TestMemberDataForOpenApiSchemaExtensions))] public void GetSchemaByModelName(OpenApiSchema expected, IDictionary<string, OpenApiSchema> componentSchemas, string modelName) { // Act var actual = componentSchemas.GetSchemaByModelName(modelName); // Assert actual .Should() .NotBeNull() .And .BeEquivalentTo(expected); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CapaDatos; using System.Data; namespace CapaNegocio { public class PaisBL:Interfaces.iPais { private Datos datos = new DatosSQL(); private String mensaje; public String Mensaje { get { return mensaje; } set { mensaje = value; } } public System.Data.DataSet Listar() { return datos.TraerDataSet("uspListarPais"); } public bool Agregar(CapaEntidades.PaisEntidad pais) { DataRow fila = datos.TraerDataRow("uspAgregarPais",pais.CodPais,pais.Nombre); mensaje = fila["Mensaje"].ToString(); byte codError = Convert.ToByte(fila["CodError"]); if (codError == 0) return true; else return false; } public bool Eliminar(string codPais) { DataRow fila = datos.TraerDataRow("uspEliminarPais", codPais); mensaje = fila["Mensaje"].ToString(); byte codError = Convert.ToByte(fila["CodError"]); if (codError == 0) return true; else return false; } public bool Actualizar(CapaEntidades.PaisEntidad pais) { throw new NotImplementedException(); } public System.Data.DataSet Buscar(string codPais) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVP { public interface IView { event EventHandler Calc; string Input1Text { get; } string Input2Text { get; } string ResultText { set; } void ShowMessage(); } }
using AutoMapper; using DotNetCoreIdentity.Application; using DotNetCoreIdentity.Application.BlogServices; using DotNetCoreIdentity.Application.BlogServices.Dtos; using DotNetCoreIdentity.Application.CategoryServices.Dtos; using DotNetCoreIdentity.Application.Shared; using DotNetCoreIdentity.EF.Context; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace DotNetCoreIdentity.Test { public class PostServiceShould { #region CreatePostHelpers // verileri kayit ederken db ayarlarinin ayni dbname icerisinde olduguna dikkat edin, eger db nameler farkliysa test verileri farkli veri tabanlarina kayit olur. tum test metotlarinda(Fact'lerde) ayri dbName'ler verilmesinin sebebi budur. public async Task<List<ApplicationResult<PostDto>>> CreatePost(List<CreatePostInput> fakePostList, string postDbName) { var options = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; MapperConfiguration mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); ApplicationResult<CategoryDto> result = new ApplicationResult<CategoryDto>(); using (var inMemoryContext = new ApplicationUserDbContext(options)) { CategoryServiceShould categoryShould = new CategoryServiceShould(); result = await categoryShould.CreateCategory(inMemoryContext, mapper); await categoryShould.AssertCreatedCategory(inMemoryContext, result); } List<ApplicationResult<PostDto>> createdPostResulList = new List<ApplicationResult<PostDto>>(); using (var inMemoryContext = new ApplicationUserDbContext(options)) { var service = new PostService(inMemoryContext, mapper); foreach (var item in fakePostList) { item.CategoryId = result.Result.Id; createdPostResulList.Add(await service.Create(item)); } } return createdPostResulList; } async Task AssertCreatedPostAsync(ApplicationUserDbContext inMemoryContext, List<ApplicationResult<PostDto>> resultList, List<CreatePostInput> fakePostList) { // burasi onemli Assert.Equal(fakePostList.Count, await inMemoryContext.Posts.CountAsync()); foreach (var fakePost in fakePostList) { ApplicationResult<PostDto> foundResult = resultList.Find(x => x.Result.Content == fakePost.Content && x.Result.Title == fakePost.Title && x.Result.UrlName == fakePost.UrlName && x.Result.CreatedBy == fakePost.CreatedBy && x.Result.CreatedById == fakePost.CreatedById ); Assert.True(foundResult.Succeeded); Assert.NotNull(foundResult.Result); var item = await inMemoryContext.Posts.FirstAsync(x => x.Content == fakePost.Content && x.Title == fakePost.Title && x.UrlName == fakePost.UrlName && x.CreatedBy == fakePost.CreatedBy && x.CreatedById == fakePost.CreatedById ); Assert.Equal(fakePost.CreatedBy, item.CreatedBy); Assert.Equal(fakePost.Title, item.Title); Assert.Equal(fakePost.UrlName, item.UrlName); Assert.Equal(fakePost.Content, item.Content); } } #endregion [Fact] public async Task CreateNewPost() { string postDbName = "postDbCreateNewPost"; var optionsPost = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; List<CreatePostInput> fakePostList = new List<CreatePostInput> { new CreatePostInput { Content = "Lorem Ipsum Dolor Sit Amet", Title = "Lorem Ipsum Dolor", UrlName = "lorem-ipsum-dolor", CreatedBy = "Tester1", CreatedById = Guid.NewGuid().ToString() } }; var resultList = await CreatePost(fakePostList, postDbName); using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { await AssertCreatedPostAsync(inMemoryContext, resultList, fakePostList); } } [Fact] public async Task UpdatePost() { string postDbName = "postDbUpdatePost"; var optionsPost = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; MapperConfiguration mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); List<CreatePostInput> fakePostList = new List<CreatePostInput> { new CreatePostInput { Content = "Lorem Ipsum Dolor Sit Amet", Title = "Lorem Ipsum Dolor", UrlName = "lorem-ipsum-dolor", CreatedBy = "Tester1", CreatedById = Guid.NewGuid().ToString() } }; ApplicationResult<PostDto> resultUpdatePost = new ApplicationResult<PostDto>(); List<ApplicationResult<PostDto>> resultList = await CreatePost(fakePostList, postDbName); using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { await AssertCreatedPostAsync(inMemoryContext, resultList, fakePostList); var item = await inMemoryContext.Posts.FirstOrDefaultAsync(); PostService service = new PostService(inMemoryContext, mapper); UpdatePostInput fakeUpdate = new UpdatePostInput { Id = item.Id, CreatedById = item.CreatedById, ModifiedById = Guid.NewGuid().ToString(), ModifiedBy = "Tester1 Updated", Content = "Lorem Ipsum Dolor Sit Amet Updated", Title = "Lorem Ipsum Dolor Updated", UrlName = "lorem-ipsum-dolor-updated" }; resultUpdatePost = await service.Update(fakeUpdate); } using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { Assert.Equal(1, await inMemoryContext.Posts.CountAsync()); Assert.True(resultUpdatePost.Succeeded); Assert.NotNull(resultUpdatePost.Result); var item = await inMemoryContext.Posts.FirstAsync(); Assert.Equal("Tester1", item.CreatedBy); Assert.Equal("Tester1 Updated", item.ModifiedBy); Assert.Equal("Lorem Ipsum Dolor Sit Amet Updated", item.Content); Assert.Equal("Lorem Ipsum Dolor Updated", item.Title); Assert.Equal("lorem-ipsum-dolor-updated", item.UrlName); Assert.Equal(resultUpdatePost.Result.ModifiedById, item.ModifiedById); } } [Fact] // Category alaninin null gelmesinin sebebi onun bilgisin baska bir veritabaninda tutulmasidir. Bu sebeple veritabani ismini ayni yaptik ve artik null gelmiyor. public async Task GetPost() { string postDbName = "postDbGetPost"; MapperConfiguration mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); var optionsPost = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; ApplicationResult<PostDto> resultGet = new ApplicationResult<PostDto>(); List<CreatePostInput> fakePostList = new List<CreatePostInput> { new CreatePostInput { Content = "Lorem Ipsum Dolor Sit Amet", Title = "Lorem Ipsum Dolor", UrlName = "lorem-ipsum-dolor", CreatedBy = "Tester1", CreatedById = Guid.NewGuid().ToString() } }; var resultList = await CreatePost(fakePostList, postDbName); using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { await AssertCreatedPostAsync(inMemoryContext, resultList, fakePostList); } using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { var service = new PostService(inMemoryContext, mapper); resultGet = await service.Get(resultList[0].Result.Id); } using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { // get servis dogru calisti mi kontrolu Assert.True(resultGet.Succeeded); Assert.NotNull(resultGet.Result); Assert.Equal("Lorem Ipsum Dolor Sit Amet", resultGet.Result.Content); Assert.Equal("Lorem Ipsum Dolor", resultGet.Result.Title); Assert.Equal("lorem-ipsum-dolor", resultGet.Result.UrlName); var optionsCategory = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; using (var inMemoryContextCategory = new ApplicationUserDbContext(optionsCategory)) { Assert.Equal(1, await inMemoryContextCategory.Categories.CountAsync()); var item = await inMemoryContextCategory.Categories.FirstAsync(); Assert.Equal("Lorem Ipsum", item.Name); Assert.Equal("lorem-ipsum", item.UrlName); } } } [Fact] public async Task DeletePost() { string postDbName = "postDbDeletePost"; MapperConfiguration mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); var optionsPost = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; ApplicationResult resultDelete = new ApplicationResult(); List<CreatePostInput> fakePostList = new List<CreatePostInput> { new CreatePostInput { Content = "Lorem Ipsum Dolor Sit Amet", Title = "Lorem Ipsum Dolor", UrlName = "lorem-ipsum-dolor", CreatedBy = "Tester1", CreatedById = Guid.NewGuid().ToString() } }; var resultList = await CreatePost(fakePostList, postDbName); using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { await AssertCreatedPostAsync(inMemoryContext, resultList, fakePostList); } using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { var service = new PostService(inMemoryContext, mapper); resultDelete = await service.Delete(resultList[0].Result.Id); } using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { Assert.True(resultDelete.Succeeded); Assert.Null(resultDelete.ErrorMessage); Assert.Equal(0, await inMemoryContext.Posts.CountAsync()); } } [Fact] public async Task GetAllPosts() { string postDbName = "postDbGetAllPost"; MapperConfiguration mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); var optionsPost = new DbContextOptionsBuilder<ApplicationUserDbContext>().UseInMemoryDatabase(databaseName: postDbName).Options; List<CreatePostInput> fakePostList = new List<CreatePostInput> { new CreatePostInput { Content = "Lorem Ipsum Dolor Sit Amet", Title = "Lorem Ipsum Dolor", UrlName = "lorem-ipsum-dolor", CreatedBy = "Tester1", CreatedById = Guid.NewGuid().ToString() }, new CreatePostInput { Content = "Lorem Ipsum Dolor Sit Amet2", Title = "Lorem Ipsum Dolor2", UrlName = "lorem-ipsum-dolor2", CreatedBy = "Tester2", CreatedById = Guid.NewGuid().ToString() } }; var resultList = await CreatePost(fakePostList, postDbName); ApplicationResult<List<PostDto>> resultGetAll = new ApplicationResult<List<PostDto>>(); using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { await AssertCreatedPostAsync(inMemoryContext, resultList, fakePostList); var service = new PostService(inMemoryContext, mapper); resultGetAll = await service.GetAll(); } using (var inMemoryContext = new ApplicationUserDbContext(optionsPost)) { foreach (var fakePost in fakePostList) { PostDto foundResult = resultGetAll.Result.Find(x => x.Content == fakePost.Content && x.Title == fakePost.Title && x.UrlName == fakePost.UrlName && x.CreatedBy == fakePost.CreatedBy && x.CreatedById == fakePost.CreatedById ); Assert.NotNull(foundResult); } Assert.Equal(fakePostList.Count, await inMemoryContext.Posts.CountAsync()); Assert.True(resultGetAll.Succeeded); Assert.NotNull(resultGetAll.Result); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SmartHome.StatusWriters { class ConsoleStatusWriter : IStatusWriter { //this is the concrete class that implements the interface Observer and // its methods for update public void DeviceStatusChanged(Device device) { //only for console Console.WriteLine($"*{ device.Room }-{ device.DeviceType }* is { device.Status }*"); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; namespace Org.DAL.MySql { internal class EmployeeDesignContextFactory : IDesignTimeDbContextFactory<EmployeContext> { public EmployeContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<EmployeContext>(); var connectionString = "server=localhost;database=EmployePortal-Migration;allowuservariables=True;user id=root;password=Suriya@1998"; optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); return new EmployeContext(optionsBuilder.Options); } } }
using FunctionalProgramming.Monad.Outlaws; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FunctionalProgramming.Tests.MonadTests { [TestClass] public sealed class TaskTests { } }
using UnityEngine; /// <summary> /// Kontrol rotasi kamera dari gyroscope /// </summary> public class FakeCamController : MonoBehaviour { private bool gyroBool; private Gyroscope gyro; private Quaternion rotFix; public void Start() { Transform currentParent = transform.parent; GameObject camParent = new GameObject("GyroCamParent"); camParent.transform.position = transform.position; transform.parent = camParent.transform; GameObject camGrandparent = new GameObject("GyroCamGrandParent"); camGrandparent.transform.position = transform.position; camParent.transform.parent = camGrandparent.transform; camGrandparent.transform.parent = currentParent; #if UNITY_3_4 gyroBool = Input.isGyroAvailable; #else gyroBool = SystemInfo.supportsGyroscope; #endif if (gyroBool) { gyro = Input.gyro; gyro.enabled = true; if (Screen.orientation == ScreenOrientation.LandscapeLeft) { camParent.transform.eulerAngles = new Vector3(90, 180, 0); } else if (Screen.orientation == ScreenOrientation.Portrait) { camParent.transform.eulerAngles = new Vector3(90, 180, 0); } else if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) { camParent.transform.eulerAngles = new Vector3(90, 180, 0); } else if (Screen.orientation == ScreenOrientation.LandscapeRight) { camParent.transform.eulerAngles = new Vector3(90, 180, 0); } else { camParent.transform.eulerAngles = new Vector3(90, 180, 0); } if (Screen.orientation == ScreenOrientation.LandscapeLeft) { rotFix = new Quaternion(0, 0, 1, 0); } else if (Screen.orientation == ScreenOrientation.Portrait) { rotFix = new Quaternion(0, 0, 1, 0); } else if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) { rotFix = new Quaternion(0, 0, 1, 0); } else if (Screen.orientation == ScreenOrientation.LandscapeRight) { rotFix = new Quaternion(0, 0, 1, 0); } else { rotFix = new Quaternion(0, 0, 1, 0); } //Screen.sleepTimeout = 0; } else { #if UNITY_EDITOR print("NO GYRO"); #endif } } public void Update() { if (gyroBool) { Quaternion quatMap; #if UNITY_IPHONE quatMap = gyro.attitude; #elif UNITY_ANDROID quatMap = new Quaternion(gyro.attitude.x, gyro.attitude.y, gyro.attitude.z, gyro.attitude.w); #endif transform.localRotation = quatMap * rotFix; } } }
namespace Shouter.Web.Views.Home { using System.IO; using SimpleMVC.Interfaces.Generic; using ViewModels; public class Signed : IRenderable<SignedViewModel> { public SignedViewModel Model { get; set; } public string Render() { string template = File.ReadAllText(Constants.ContantPath + "feed-signed.html"); var format = string.Format(template, this.Model); return format; } } }
using System; using System.Collections.Generic; using System.Text; namespace DSSLib { public class Case : NotifyObj { public event Action OnChanceChanged; public override string ToString() => $"Случай \"{Name}\""; public string Name { get => name; set { name = value; OnPropertyChanged(); } } private string name; public double Chance { get => chance; set { double old = chance; chance = value; OnChanceChanged?.Invoke(); OnPropertyChanged(); } } private double chance; public Case() : this("") { } public Case(string name, double chance = 0) { Name = name; Chance = chance; } } }
namespace MyStore.Helpers { public class DataProvider { public MyStoreEntities database { get; set; } private static string _connectionString; private static DataProvider _instance; public static DataProvider instance { get { return _instance == null ? _instance = new DataProvider(_connectionString) : _instance; } set { _instance = value; } } public DataProvider(string connectionString) { _connectionString = connectionString; database = new MyStoreEntities(_connectionString); } } }
using UnityEngine; using System.Collections; public class Spielende : MonoBehaviour { private bool gameOver = false; void Update() { if (gameOver) Application.Quit(); } void OnTriggerEnter2D( Collider2D other) { if (Debug.isDebugBuild) Debug.Log("TriggerEnter!"); gameOver = true; } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Windows.Devices.Geolocation; using Windows.Devices.Geolocation.Geofencing; using Windows.Media.DialProtocol; namespace PizzaBezorgApp.Models { public class Bestelling { public string besteller { get; set; } public int aantal { get; set; } public BasicGeoposition Position { get; set; } public Geofence fence { get; set; } public string soort { get; set; } public string stad { get; set; } public string adres { get; set; } public Bestelling(string besteller, string soort, string stad , string adres) { this.besteller = besteller; this.aantal = 1; this.soort = soort; this.stad = stad; this.adres = adres; AddFence(); GetGeopoint(); } public void AddFence() { // Replace if it already exists for this maneuver key var oldFence = GeofenceMonitor.Current.Geofences.Where(p => p.Id == soort.ToString()).FirstOrDefault(); if (oldFence != null) { GeofenceMonitor.Current.Geofences.Remove(oldFence); } Geocircle geocircle = new Geocircle(Position, 25); bool singleUse = true; MonitoredGeofenceStates mask = 0; mask |= MonitoredGeofenceStates.Entered; mask |= MonitoredGeofenceStates.Exited; var geofence = new Geofence(soort.ToString(), geocircle, mask, singleUse, TimeSpan.FromSeconds(1)); GeofenceMonitor.Current.Geofences.Add(geofence); fence = geofence; } private async Task<string> GetAdres() { string url = "http://dev.virtualearth.net/REST/v1/Locations?countryRegion=NL&locality=" + stad + "&addressLine=" + adres + "&key=" + AppGlobal.LOCAL_SETTINGS.Values["BingKey"]; using (HttpClient httpcl = new HttpClient()) { var response = await httpcl.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } public async void GetGeopoint() { string cmd = await GetAdres(); JObject allInfo = JObject.Parse(cmd); var info = allInfo["resourceSets"].First["resources"].First["point"]["coordinates"]; var lati = info.First.ToString(); var longi = info.Last.ToString(); Position = new BasicGeoposition { Latitude = Convert.ToDouble(lati), Longitude = Convert.ToDouble(longi) }; } } }
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.PowershellCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.IaasCmdletInfo.Extensions.Common { public class SetAzureVMExtensionCmdletInfo: CmdletsInfo { public SetAzureVMExtensionCmdletInfo(IPersistentVM vm, string extensionName, string publisher, string version = null, string referenceName = null, string publicConfiguration = null, string privateConfiguration = null,string publicConfigPath = null,string privateConfigPath = null, bool disable = false) { cmdletName = Utilities.SetAzureVMExtensionCmdletName; cmdletParams.Add(new CmdletParam("VM", vm)); cmdletParams.Add(new CmdletParam("ExtensionName", extensionName)); cmdletParams.Add(new CmdletParam("Publisher", publisher)); if (!string.IsNullOrEmpty(version)) { cmdletParams.Add(new CmdletParam("Version", version)); } if (!string.IsNullOrEmpty(referenceName)) { cmdletParams.Add(new CmdletParam("ReferenceName", referenceName)); } if (!string.IsNullOrEmpty(publicConfiguration)) { cmdletParams.Add(new CmdletParam("PublicConfiguration", publicConfiguration)); } if (!string.IsNullOrEmpty(privateConfiguration)) { cmdletParams.Add(new CmdletParam("PrivateConfiguration", privateConfiguration)); } if (disable) { cmdletParams.Add(new CmdletParam("Disable")); } if (!string.IsNullOrEmpty(publicConfigPath)) { cmdletParams.Add(new CmdletParam("PublicConfigPath", publicConfigPath)); } if (!string.IsNullOrEmpty(privateConfigPath)) { cmdletParams.Add(new CmdletParam("PrivateConfigPath", privateConfigPath)); } } } }
using EddiDataDefinitions; using System; using Utilities; namespace EddiEvents { [PublicAPI] public class CommodityEjectedEvent : Event { public const string NAME = "Commodity ejected"; public const string DESCRIPTION = "Triggered when you eject a commodity from your ship or SRV"; public const string SAMPLE = "{\"timestamp\":\"2016-06-10T14:32:03Z\",\"event\":\"EjectCargo\",\"Type\":\"agriculturalmedicines\",\"Count\":2,\"Abandoned\":true}"; [PublicAPI("The name of the commodity ejected")] public string commodity => commodityDefinition?.localizedName; [PublicAPI("The amount of commodity ejected")] public int amount { get; } [PublicAPI("True if the cargo has been abandoned")] public bool abandoned { get; } [PublicAPI("ID of the mission-related commodity, if applicable")] public long? missionid { get; } // Not intended to be user facing public CommodityDefinition commodityDefinition { get; } public CommodityEjectedEvent(DateTime timestamp, CommodityDefinition commodity, int amount, long? missionid, bool abandoned) : base(timestamp, NAME) { this.commodityDefinition = commodity; this.amount = amount; this.missionid = missionid; this.abandoned = abandoned; } } }
namespace ConsoleApplication1.Models { public class MakelaarDomainModel { public string Id { get; set; } public string Naam { get; set; } public int TotaalAantalObjecten { get; set; } } }
using System; using System.Text.RegularExpressions; class Program { static void Main() { string[] tickets = Console.ReadLine().Split(new [] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); string regex = @"(\@{6,}|\${6,}|\^{6,}|\#{6,})"; for (int i = 0; i < tickets.Length; i++) { if (tickets[i].Length == 20) { var leftSide = tickets[i].Substring(0, 10); var rightSide = tickets[i].Substring(10); Match matchLeftSide = Regex.Match(leftSide, regex); Match matchRightSide = Regex.Match(rightSide, regex); if (matchLeftSide.Success && matchRightSide.Success) { var ticketChar = matchLeftSide.Value[0]; if (matchLeftSide.Length == matchRightSide.Length) { if (matchLeftSide.Length >= 6 && matchLeftSide.Length <= 9) { Console.WriteLine($"ticket {'"' + tickets[i] + '"'} - {matchLeftSide.Length}{ticketChar}"); } else if (matchLeftSide.Length == 10) { Console.WriteLine($"ticket {'"' + tickets[i] + '"'} - {matchLeftSide.Length}{ticketChar} Jackpot!"); } } } else { Console.WriteLine($"ticket {'"' + tickets[i] + '"'} - no match"); } } else { Console.WriteLine("invalid ticket"); } } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ApiSGCOlimpiada.Data.AcompanhamentoDAO; using ApiSGCOlimpiada.Data.EscolaDAO; using ApiSGCOlimpiada.Data.GrupoDAO; using ApiSGCOlimpiada.Data.LogDAO; using ApiSGCOlimpiada.Data.OcupacaoDAO; using ApiSGCOlimpiada.Data.OcupacaoSolicitacaoCompraDAO; using ApiSGCOlimpiada.Data.OrcamentoDAO; using ApiSGCOlimpiada.Data.ProdutoDAO; using ApiSGCOlimpiada.Data.ProdutoPedidoOrcamentoDAO; using ApiSGCOlimpiada.Data.ResponsavelDAO; using ApiSGCOlimpiada.Data.SolicitacaoCompraDAO; using ApiSGCOlimpiada.Data.StatusDAO; using ApiSGCOlimpiada.Data.TipoCompraDAO; using ApiSGCOlimpiada.Data.UsuarioDAO; using ApiSGCOlimpiada.Data.ProdutoSolicitacoesDAO; using ApiSGCOlimpiada.Data.EmailDAO; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; using Coravel; using System.Globalization; namespace ApiSGCOlimpiada { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //CultureInfo.CurrentCulture = new CultureInfo("pt-BR"); services.AddMailer(this.Configuration); services.AddTransient<IUsuarioDAO, UsuarioDAO>(); services.AddTransient<IFuncaoDAO, FuncaoDAO>(); services.AddTransient<IAcompanhamentoDAO, AcompanhamentoDAO>(); services.AddTransient<IEscolaDAO, EscolaDAO>(); services.AddTransient<IGrupoDAO, GrupoDAO>(); services.AddTransient<ILogDAO, LogDAO>(); services.AddTransient<IOcupacaoDAO, OcupacaoDAO>(); services.AddTransient<IOcupacaoSolicitacaoCompraDAO, OcupacaoSolicitacaoCompraDAO>(); services.AddTransient<IResponsavelDAO, ResponsavelDAO>(); services.AddTransient<IProdutoDAO, ProdutoDAO>(); services.AddTransient<IProdutoPedidoOrcamentoDAO, ProdutoPedidoOrcamentoDAO>(); services.AddTransient<IOrcamentoDAO, OrcamentoDAO>(); services.AddTransient<ISolicitacaoCompraDAO, SolicitacaoCompraDAO>(); services.AddTransient<IStatusDAO, StatusDAO>(); services.AddTransient<ITipoCompraDAO, TipoCompraDAO>(); services.AddTransient<IProdutoSolicitacoesDAO, ProdutoSolicitacoesDAO>(); services.AddTransient<IEmailDAO, EmailDAO>(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ApiSGCOlimpiada", Version = "v1" }); }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(opt => { opt.SaveToken = true; opt.RequireHttpsMetadata = false; opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sistema-compras-olimpiadas-validacao-autenticacao")), ValidIssuer = "ApiSGCOlimpiada", ValidAudience = "ServerDino", }; opt.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { Console.WriteLine("Token Inválido " + context.Exception.Message); return Task.CompletedTask; }, OnTokenValidated = context => { Console.WriteLine("Token Válido " + context.SecurityToken); return Task.CompletedTask; } }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiSGCOlimpiada v1")); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseStaticFiles(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using UnityEngine; using System.IO; using System.Collections.Generic; public class SaveManager : MonoBehaviour { public static SaveManager instance; // save path string savePath; void Awake () { instance = this; // save path savePath = Path.Combine(Application.persistentDataPath, "hellblusserSavefile.txt"); // clear? if (Application.isEditor) { //ClearFile(); } } public void StoreLastLevelData ( ref SetupManager.RunData _dataTo ) { _dataTo.playerHealthOnStartOfLevel = _dataTo.playerHealthCur; _dataTo.playerFireOnStartOfLevel = _dataTo.playerFireCur; _dataTo.coinsOnStartOfLevel = _dataTo.curRunCoinsCollected; _dataTo.tearsOnStartOfLevel = _dataTo.curRunTearsCollected; _dataTo.usedSecondChanceOnStartOfLevel = _dataTo.usedSecondChance; _dataTo.runTimeOnStartOfLevel = _dataTo.runTime; _dataTo.ringEquipmentIndexOnStartOfLevel = _dataTo.curRingEquipmentIndex; _dataTo.braceletEquipmentIndexOnStartOfLevel = _dataTo.curBraceletEquipmentIndex; _dataTo.bodyEquipmentIndexOnStartOfLevel = _dataTo.curBodyEquipmentIndex; _dataTo.weaponEquipmentIndexOnStartOfLevel = _dataTo.curWeaponEquipmentIndex; _dataTo.blessingsClaimedOnStartOflevel = new List<int>(); if (_dataTo.blessingsClaimed != null) { for (int i = 0; i < _dataTo.blessingsClaimed.Count; i++) { _dataTo.blessingsClaimedOnStartOflevel.Add(_dataTo.blessingsClaimed[i]); } } } public void GetLastLevelData ( ref SetupManager.RunData _dataFrom ) { _dataFrom.playerHealthCur = _dataFrom.playerHealthOnStartOfLevel; _dataFrom.playerFireCur = _dataFrom.playerFireOnStartOfLevel; _dataFrom.curRunCoinsCollected = _dataFrom.coinsOnStartOfLevel; _dataFrom.curRunTearsCollected = _dataFrom.tearsOnStartOfLevel; _dataFrom.usedSecondChance = _dataFrom.usedSecondChanceOnStartOfLevel; _dataFrom.runTime = _dataFrom.runTimeOnStartOfLevel; _dataFrom.curRingEquipmentIndex = _dataFrom.ringEquipmentIndexOnStartOfLevel; _dataFrom.curBraceletEquipmentIndex = _dataFrom.braceletEquipmentIndexOnStartOfLevel; _dataFrom.curBodyEquipmentIndex = _dataFrom.bodyEquipmentIndexOnStartOfLevel; _dataFrom.curWeaponEquipmentIndex = _dataFrom.weaponEquipmentIndexOnStartOfLevel; _dataFrom.blessingsClaimed = new List<int>(); if (_dataFrom.blessingsClaimedOnStartOflevel != null) { for (int i = 0; i < _dataFrom.blessingsClaimedOnStartOflevel.Count; i++) { _dataFrom.blessingsClaimed.Add(_dataFrom.blessingsClaimedOnStartOflevel[i]); } } // log //Debug.LogError("get last level data || weapon index: " + + Time.time.ToString()); } public void WriteToFile(SetupManager.ProgressData _newData) { if (SetupManager.instance == null || (SetupManager.instance != null && !SetupManager.instance.aboutToDeleteSave)) { bool fileExists = CheckIfFileExists(); string json = JsonUtility.ToJson(_newData); File.WriteAllText(savePath, json); //Debug.LogError("writing to file, file exists: " + fileExists + " || " + Time.time.ToString()); } } public SetupManager.ProgressData LoadFromFile () { SetupManager.ProgressData saveDataReturn = new SetupManager.ProgressData(); bool fileExists = CheckIfFileExists(); if (fileExists) { string json = File.ReadAllText(savePath); saveDataReturn = JsonUtility.FromJson<SetupManager.ProgressData>(json); // create new run because we died last turn? if (saveDataReturn.normalRunData.playerDead) { saveDataReturn.normalRunData = CreateNewRunData(); saveDataReturn.normalRunData.runSeed = 0; saveDataReturn.normalRunData.curBodyEquipmentIndex = (int)EquipmentDatabase.Equipment.BlueCloak; saveDataReturn.normalRunData.curWeaponEquipmentIndex = (int)EquipmentDatabase.Equipment.IronSword; StoreLastLevelData(ref saveDataReturn.normalRunData); } if (saveDataReturn.normalRunData.curLevelIndex >= (saveDataReturn.normalRunData.curFloorData.locationCount)) { saveDataReturn.normalRunData.curFloorIndex++; saveDataReturn.normalRunData.curLevelIndex = 0; saveDataReturn.normalRunData.encountersHad = 0; } if (saveDataReturn.endlessRunData.playerDead) { saveDataReturn.endlessRunData = CreateNewRunData(); saveDataReturn.endlessRunData.runSeed = Mathf.RoundToInt(TommieRandom.instance.RandomRange(-1000000f, 1000000f)); // start endless run with white cloak saveDataReturn.endlessRunData.curBodyEquipmentIndex = (int)EquipmentDatabase.Equipment.WhiteCloak; StoreLastLevelData(ref saveDataReturn.endlessRunData); } if (saveDataReturn.endlessRunData.curLevelIndex >= (saveDataReturn.endlessRunData.curFloorData.locationCount)) { saveDataReturn.endlessRunData.curFloorIndex++; saveDataReturn.endlessRunData.curLevelIndex = 0; saveDataReturn.endlessRunData.encountersHad = 0; } } return saveDataReturn; } public void ClearFile() { bool fileExists = CheckIfFileExists(); if (fileExists) { File.Delete(savePath); } // log //Debug.LogError("wants to clear file || fileExists: " + fileExists + " || " + Time.time.ToString()); } public bool CheckIfFileExists () { return File.Exists(savePath); } public SetupManager.ProgressData CreateNewData () { Debug.LogError("create new global data || " + Time.time.ToString()); SetupManager.ProgressData newData = new SetupManager.ProgressData(); SetupManager.PersistentData newPersistentData = new SetupManager.PersistentData(); newPersistentData.sawIntro = false; newPersistentData.sawOutro = false; newPersistentData.unlockedEndless = false; newPersistentData.inNormalRun = false; newPersistentData.inEndlessRun = false; newPersistentData.playTime = 0f; newPersistentData.sawCombatPopup = false; newPersistentData.sawFirePopup = false; newPersistentData.sawFireCollectPopup = false; newPersistentData.sawKickPopup = false; newPersistentData.sawTearPopup = false; newPersistentData.sawDonutPopup = false; newPersistentData.sawCoinPopup = false; newPersistentData.sawShopPopup = false; newPersistentData.sawFountainPopup = false; newPersistentData.sawKeyPopup = false; newPersistentData.sawRestPopup = false; newPersistentData.sawEndlessPopup = false; newPersistentData.sawMaxFirePopup = false; newPersistentData.normalHighestLoopIndex = 0; newPersistentData.normalHighestFloorIndex = 0; newPersistentData.normalHighestLevelIndex = 0; newPersistentData.endlessHighestLoopIndex = 0; newPersistentData.endlessHighestFloorIndex = 0; newPersistentData.endlessHighestLevelIndex = 0; newData.persistentData = newPersistentData; newData.normalRunData = CreateNewRunData(); newData.normalRunData.runSeed = 0; newData.endlessRunData = CreateNewRunData(); newData.endlessRunData.runSeed = Mathf.RoundToInt(TommieRandom.instance.RandomRange(-1000000f,1000000f)); // hack newData.endlessRunData.curBodyEquipmentIndex = (int)EquipmentDatabase.Equipment.WhiteCloak; //newData.endlessRunData.curBraceletEquipmentIndex = (int)EquipmentDatabase.Equipment.SilverBracelet; //newData.endlessRunData.curRingEquipmentIndex = (int)EquipmentDatabase.Equipment.SilverRing; //newData.endlessRunData.curWeaponEquipmentIndex = (int)EquipmentDatabase.Equipment.BasicWand; // settings SetupManager.SettingsData newSettingsData = new SetupManager.SettingsData(); int maxResolutionIndex = (Screen.resolutions.Length - 1); newSettingsData.resolutionIndex = maxResolutionIndex; newSettingsData.fullscreen = 1; newSettingsData.sfxVolIndex = 0; newSettingsData.musicVolIndex = 0; newSettingsData.lookSensitivityX = 0; newSettingsData.lookSensitivityY = 0; newSettingsData.invertY = 0; newSettingsData.wobbleEffect = 1; newSettingsData.cameraMotion = 1; newSettingsData.endlessFilter = 1; newData.settingsData = newSettingsData; return newData; } public SetupManager.RunData CreateNewRunData () { Debug.LogError("create new run || " + Time.time.ToString()); SetupManager.RunData newRunData = new SetupManager.RunData(); newRunData.runTime = 0f; newRunData.runSeed = 0; newRunData.playerReachedEnd = false; newRunData.playerHealthMax = (SetupManager.instance.playerStrong) ? 99 : 6; newRunData.playerHealthCur = newRunData.playerHealthMax; newRunData.playerFireMax = 3; newRunData.playerFireCur = 0; newRunData.curLoopIndex = 0; newRunData.curFloorIndex = 1; newRunData.curLevelIndex = 0; newRunData.encountersHad = 0; newRunData.blessingsClaimed = new List<int>(); /* if (Application.isEditor) { newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.SwiftStrikes); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.QuickFeet); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.GlassCannon); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.FireBurst); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Warrior); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Sorcerer); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Tank); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.SecondChance); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Lucky); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Mournful); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.WildFire); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.AgileJumper); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Acrobat); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Spray); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.FireRage); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Revenge); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Hungry); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Resilient); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Thrifty); newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.Drainer); //newRunData.blessingsClaimed.Add((int)BlessingDatabase.Blessing.HotFire); } */ newRunData.playerDead = false; newRunData.usedSecondChance = false; newRunData.curBodyEquipmentIndex = (int)(EquipmentDatabase.Equipment.BlueCloak); newRunData.curRingEquipmentIndex = -1;//(int)(EquipmentDatabase.Equipment.GoldRing);//-1; newRunData.curBraceletEquipmentIndex = -1;//(int)(EquipmentDatabase.Equipment.SilverBracelet);//-1; newRunData.curWeaponEquipmentIndex = (int)(EquipmentDatabase.Equipment.IronSword); // generate new floor data SetupManager.FloorData newFloorData = new SetupManager.FloorData(); int locationCount = 8; int levelsBeforeShop = 0; newFloorData.locationCount = locationCount; newFloorData.locationTypes = new List<SetupManager.LocationData>(); //newFloorData.locationTypes = new List<List<int>>(); newFloorData.locationVisitedIndex = new List<int>(); for (int i = 0; i < locationCount; i++) { SetupManager.LocationData newLocationData = new SetupManager.LocationData(); newFloorData.locationVisitedIndex.Add(-1); List<int> curLocationTypes = new List<int>(); if (levelsBeforeShop < 2) { curLocationTypes.Add((i == (locationCount - 1)) ? (int)SetupManager.LocationType.BossLevel : (int)SetupManager.LocationType.Level); levelsBeforeShop++; } else { curLocationTypes.Add((int)SetupManager.LocationType.Shop); curLocationTypes.Add((int)SetupManager.LocationType.Rest); levelsBeforeShop = 0; } newLocationData.types = curLocationTypes; newFloorData.locationTypes.Add(newLocationData); } newRunData.curFloorData = newFloorData; return newRunData; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BorrowedBookController : MonoBehaviour { public Text Title, Username, StartDate, EndDate; }
using System; using System.Linq; using DelftTools.Functions.Filters; using GeoAPI.Geometries; using GisSharpBlog.NetTopologySuite.Geometries; using NetTopologySuite.Extensions.Coverages; using NUnit.Framework; using SharpMap; using SharpMap.Layers; using SharpMapTestUtils; namespace NetTopologySuite.Extensions.Tests.Coverages { [TestFixture] public class DiscreteGridPointCoverageTest { [Test] public void Create() { var points = new IPoint[,] { {new Point(0.0, 1.0), new Point(0.0, 0.0)}, {new Point(0.5, 1.5), new Point(1.0, 0.0)}, {new Point(1.0, 2.0), new Point(2.0, 2.0)} }; var coverage = new DiscreteGridPointCoverage(3, 2, points.Cast<IPoint>()); var values = new[,] { {1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0} }; coverage.SetValues(values); /* var coverageLayer = new DiscreteGridPointCoverageLayer { Coverage = coverage, ShowFaces = true }; var map = new Map { Layers = { coverageLayer } }; MapTestHelper.Show(map); */ var value = coverage.Evaluate(points[1, 1].Coordinate); const double expectedValue = 4.0; Assert.AreEqual(expectedValue, value); Assert.IsTrue(coverage.Components[0].Values.Cast<double>().SequenceEqual(new [] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 })); Assert.AreEqual("new grid point coverage", coverage.Name); } [Test] public void CreateTimeDependent() { var points = new[,] { {new Point(0, 0), new Point(1, 0)}, {new Point(2, 1), new Point(3, 1.5)}, {new Point(1, 2), new Point(3, 3)} }; var coverage = new DiscreteGridPointCoverage(3, 2, points.Cast<IPoint>()) { IsTimeDependent = true }; var values = new[,] { {1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0} }; var t = DateTime.Now; coverage.SetValues(values, new VariableValueFilter<DateTime>(coverage.Time, t)); values = new[,] { {10.0, 20.0}, {30.0, 40.0}, {50.0, 60.0} }; coverage.SetValues(values, new VariableValueFilter<DateTime>(coverage.Time, t.AddYears(1))); var values1 = coverage.GetValues<double>(new VariableValueFilter<DateTime>(coverage.Time, t)); values1.Should().Have.SameSequenceAs(new[] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}); var values2 = coverage.GetValues<double>(new VariableValueFilter<DateTime>(coverage.Time, t.AddYears(1))); values2.Should().Have.SameSequenceAs(new[] { 10.0, 20.0, 30.0, 40.0, 50.0, 60.0 }); } [Test] public void Faces() { // create coverage var points = new IPoint[,] { {new Point(0, 0), new Point(1, 0)}, {new Point(2, 1), new Point(3, 1.5)}, {new Point(1, 2), new Point(3, 3)} }; var coverage = new DiscreteGridPointCoverage(3, 2, points.Cast<IPoint>()); var values = new[,] { {1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0} }; coverage.SetValues(values); // check faces coverage.Faces.Count .Should().Be.EqualTo(2); var geometry = coverage.Faces.First().Geometry; geometry.Coordinates[0] .Should().Be.EqualTo(points[0, 0].Coordinate); geometry.Coordinates[3] .Should().Be.EqualTo(points[1, 0].Coordinate); geometry.Coordinates[2] .Should().Be.EqualTo(points[1, 1].Coordinate); geometry.Coordinates[1] .Should().Be.EqualTo(points[0, 1].Coordinate); geometry.Coordinates[4] .Should().Be.EqualTo(points[0, 0].Coordinate); } } }
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { public int MaxPathSum(TreeNode root) { int res = int.MinValue; Helper(root, ref res); return res; } public int Helper(TreeNode root, ref int res) { if (root == null) return 0; int leftRes = Math.Max(Helper(root.left, ref res), 0); int rightRes = Math.Max(Helper(root.right, ref res), 0); res = Math.Max(res, leftRes + rightRes + root.val); return Math.Max(leftRes, rightRes) + root.val; } }
using UnityEngine; using UnityEngine.Events; namespace Action { /// <summary> /// Action rotate. /// </summary> public class ActionRotate : ActionBase { // Local rotation from Quaternion _from; // Local rotation to Quaternion _to; ActionRotate( GameObject target, float duration, Quaternion from, Quaternion to, UnityAction callback ) : base(target, duration, callback) { this._from = from; this._to = to; } /// <summary> /// Create a rotate action /// </summary> /// <param name="target">Target.</param> /// <param name="duration">Duration.</param> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <param name="callback">Callback.</param> public static ActionRotate Create( GameObject target, float duration, Quaternion from, Quaternion to, UnityAction callback = null ) { return new ActionRotate(target, duration, from, to, callback); } /// <summary> /// Step by delta time /// </summary> /// <param name="dt">Delta time.</param> protected override void Step(float dt) { this._target.transform.localRotation = Quaternion.Lerp(this._from, this._to, this._time / this._duration); } /// <summary> /// Finish this action. /// </summary> protected override void Finish() { this._target.transform.localRotation = this._to; base.Finish(); } } }
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.Input; using System.Windows.Media; namespace Views.ImageViewers { /// <summary> /// Zoom and Pan UI element /// </summary> public class UIZoomElement : Border { private Point origin; private Point start; private UIElement child = null; public override UIElement Child { get => base.Child; set { // new child if (value != null & value != this.Child) { this.Initialize(value); } base.Child = value; } } public void Initialize(UIElement element) { this.child = element; if (element == null) { return; } TransformGroup transformGroup = new TransformGroup(); transformGroup.Children.Add(new ScaleTransform()); // add scale transform transformGroup.Children.Add(new TranslateTransform()); // add translate transform child.RenderTransform = transformGroup; child.RenderTransformOrigin = new Point(0.0, 0.0); // enroll events this.MouseWheel += Child_MouseWheel; this.MouseLeftButtonDown += Child_MouseLeftButtonDown; this.MouseLeftButtonUp += Child_MouseLeftButtonUp; this.MouseMove += Child_MouseMove; this.PreviewMouseRightButtonDown += new MouseButtonEventHandler( Child_PreviewMouseRightButtonDown); } private TranslateTransform GetChildTranslateTransform() { if (this.child is null) { return null; } return (TranslateTransform)((TransformGroup)child.RenderTransform).Children.First(transform => transform is TranslateTransform); } private ScaleTransform GetChildScaleTransform() { if (this.child is null) { return null; } return (ScaleTransform)((TransformGroup)child.RenderTransform).Children.First(transform => transform is ScaleTransform); } public void Reset() { if (child is null) { return; } // reset zoom var scaleTransform = GetChildScaleTransform(); scaleTransform.ScaleX = 1.0; scaleTransform.ScaleY = 1.0; // reset pan var translateTransform = GetChildTranslateTransform(); translateTransform.X = 0.0; translateTransform.Y = 0.0; } #region Events private void Child_MouseWheel(object sender, MouseWheelEventArgs e) { if (child == null) { return; } // get transforms from child render. var scaleTransfrom = this.GetChildScaleTransform(); var translateTransform = this.GetChildTranslateTransform(); // delta check if (!(e.Delta > 0) && (scaleTransfrom.ScaleX < .4 || scaleTransfrom.ScaleY < .4)) return; double zoom = e.Delta > 0 ? 0.2 : -0.2; Point relative = e.GetPosition(child); double abosuluteX; double abosuluteY; abosuluteX = relative.X * scaleTransfrom.ScaleX + translateTransform.X; abosuluteY = relative.Y * scaleTransfrom.ScaleY + translateTransform.Y; scaleTransfrom.ScaleX += zoom; scaleTransfrom.ScaleY += zoom; translateTransform.X = abosuluteX - relative.X * scaleTransfrom.ScaleX; translateTransform.Y = abosuluteY - relative.Y * scaleTransfrom.ScaleY; } private void Child_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (child is null) { return; } child.ReleaseMouseCapture(); this.Cursor = Cursors.Arrow; } private void Child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (child is null) { return; } var translateTransform = GetChildTranslateTransform(); start = e.GetPosition(this); origin = new Point(translateTransform.X, translateTransform.Y); this.Cursor = Cursors.Hand; child.CaptureMouse(); } void Child_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { this.Reset(); } private void Child_MouseMove(object sender, MouseEventArgs e) { if (child is null) { return; } if (child.IsMouseCaptured) { var translateTransform = GetChildTranslateTransform(); Vector v = start - e.GetPosition(this); translateTransform.X = origin.X - v.X; translateTransform.Y = origin.Y - v.Y; } } #endregion } }
namespace Model.EF { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Document")] public partial class Document { public long ID { get; set; } [StringLength(50)] [Required(ErrorMessage = "Phải chọn loại văn bản")] public string DocumentTypeID { get; set; } [StringLength(50)] [Required(ErrorMessage = "Phải nhập số kí hiệu văn bản")] public string Number { get; set; } [StringLength(150)] [Required(ErrorMessage = "Phải nhập đơn vị ban hành")] public string DepartmentIssued { get; set; } [StringLength(500)] [Required(ErrorMessage = "Phải nhập trích yếu")] public string Summary { get; set; } public DateTime? DateIssued { get; set; } [StringLength(50)] public string Status { get; set; } [Column(TypeName = "ntext")] public string Opinion { get; set; } [StringLength(150)] public string ReceivingDepartment { get; set; } [StringLength(100)] [Required(ErrorMessage = "Phải có file văn bản")] public string AttachedFile { get; set; } [StringLength(50)] [Required(ErrorMessage = "Phải chọn sổ văn bản")] public string DocumentBookID { get; set; } [Required(ErrorMessage = "Phải nhập ngày đến")] public DateTime? DateArrived { get; set; } [StringLength(100)] public string ConfirmBy { get; set; } public bool OnlyView { get; set; } [StringLength(100)] public string To { get; set; } public DateTime? CreatedDate { get; set; } public DateTime? ModifiedDate { get; set; } [StringLength(100)] public string CreatedBy { get; set; } [StringLength(100)] public string ModifiedBy { get; set; } } }
namespace EddiDataDefinitions { public class MicroResourceCategory : ResourceBasedLocalizedEDName<MicroResourceCategory> { static MicroResourceCategory() { resourceManager = Properties.MicroResourceCategories.ResourceManager; resourceManager.IgnoreCase = false; missingEDNameHandler = (edname) => new MicroResourceCategory(edname); } public static readonly MicroResourceCategory Components = new MicroResourceCategory("Component"); public static readonly MicroResourceCategory Consumables = new MicroResourceCategory("Consumable"); public static readonly MicroResourceCategory Data = new MicroResourceCategory("Data"); public static readonly MicroResourceCategory Items = new MicroResourceCategory("Item"); public static readonly MicroResourceCategory Unknown = new MicroResourceCategory("Unknown"); // dummy used to ensure that the static constructor has run public MicroResourceCategory() : this("") { } private MicroResourceCategory(string edname) : base(edname, edname) { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace HotelManagement { public partial class DangNhap : Form { public DangNhap() { InitializeComponent(); } private String m_TenNguoiDung; public String lay_TenNguoiDung { get { return m_TenNguoiDung; } set { m_TenNguoiDung = value; } } public String m_MatKhau; public String lay_MatKhau { get { return m_MatKhau; } set { m_MatKhau = value; } } private void btDongY_Click(object sender, EventArgs e) { this.txtTenDangNhap.Focus(); m_TenNguoiDung = txtTenDangNhap.Text; m_MatKhau = txtMatKhau.Text; this.DialogResult = DialogResult.OK; } private void btHuyBo_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } private void DangNhap_Load(object sender, EventArgs e) { this.txtTenDangNhap.Text = ""; this.txtMatKhau.Text = ""; } private void btCancle_Click(object sender, EventArgs e) { this.Close(); } private void btLogin_Click(object sender, EventArgs e) { this.txtTenDangNhap.Focus(); m_TenNguoiDung = txtTenDangNhap.Text; m_MatKhau = txtMatKhau.Text; this.DialogResult = DialogResult.OK; } private void txtMatKhau_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.btLogin_Click(sender, e); } } private void txtTenDangNhap_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { this.btLogin_Click(sender, e); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace EmployeeManagament.Models { public class Department { [Key] public int DepartementID { get; set; } public string DepartementName { get; set; } } }
namespace Ach.Fulfillment.Nacha.Enumeration { public enum StandardEntryClassCode { /// <summary> /// Corporate credit or debit. Primarily used for business-to-business transactions. /// </summary> CCD, /// <summary> /// Prearranged payment and deposits. Used to credit or debit a consumer account. Popularly used for payroll direct deposits and preauthorized bill payments. /// </summary> PPD, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractsInterfaces { internal abstract class BaseL1 { protected int Num; public BaseL1(int n) { Set(n); } public abstract void Show(); public abstract void Set(int n); public abstract int Get(); } internal class AlphaL1 : BaseL1 { protected int Val; public AlphaL1(int n) : base(n) { Show(); } public override void Show() { Console.WriteLine("Alpha: {0}, {1}, and {2}", Num,Val,Get()); } public override void Set(int n) { Num = n; Val = n % 10; } public override int Get() { return Num / 10; } } internal class BravoL1 : BaseL1 { protected int Val; public BravoL1(int n): base(n) { Show(); } public override void Show() { Console.WriteLine("Bravo: {0}, {1}, and {2}", Num, Val, Get()); } public override void Set(int n) { Num = n; Val = n % 100; } public override int Get() { return Num / 100; } } internal class AbstractDemo { public static void Main01() { BaseL1 Obj1; AlphaL1 A = new AlphaL1(132); BravoL1 B = new BravoL1(321); Obj1 = A; Console.WriteLine("After using command Obj = A"); Obj1.Set(894); Obj1.Show(); Obj1 = B; Console.WriteLine("After using command Obj = B"); Obj1.Set(566); Obj1.Show(); } } }
using AutoFixture; using MediatR; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.Encoding; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Controllers; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; using SFA.DAS.ProviderUrlHelper; using System; using SFA.DAS.Authorization.Services; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Controllers.CohortControllerTests { [TestFixture] public class WhenPostingFileToDiscard { [Test] public void And_User_Selected_To_DiscardFile_Then_Redirect_To_FileDiscardSuccess_Page() { //Arrange var fixture = new WhenPostingFileToDiscardFixture(true); //Act var result = fixture.Act(); //Assert var redirect = result.VerifyReturnsRedirectToActionResult(); Assert.AreEqual("FileUploadReviewDelete", redirect.ActionName); } [Test] public void And_User_Selected_Not_To_DiscardFile_Then_Redirect_To_FileUploadCheck_Page() { //Arrange var fixture = new WhenPostingFileToDiscardFixture(false); //Act var result = fixture.Act(); //Assert var redirect = result.VerifyReturnsRedirectToActionResult(); Assert.AreEqual("FileUploadReview", redirect.ActionName); } } public class WhenPostingFileToDiscardFixture { private CohortController _sut { get; set; } private readonly Mock<IModelMapper> _modelMapper; private readonly FileDiscardViewModel _viewModel; public WhenPostingFileToDiscardFixture(bool fileDiscardConfirmed) { var fixture = new Fixture(); _viewModel = fixture.Create<FileDiscardViewModel>(); _viewModel.FileDiscardConfirmed = fileDiscardConfirmed; _modelMapper = new Mock<IModelMapper>(); _sut = new CohortController(Mock.Of<IMediator>(), _modelMapper.Object, Mock.Of<ILinkGenerator>(), Mock.Of<ICommitmentsApiClient>(), Mock.Of<IAuthorizationService>(), Mock.Of<IEncodingService>(), Mock.Of<IOuterApiService>()); } public IActionResult Act() => _sut.FileUploadDiscard(_viewModel); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Animal.GameStrategy.NPC { /// <summary> /// 角色 /// </summary> public class Role { /// <summary> /// 表示角色目前所持武器 /// </summary> public IAttackStrategy Weapon { get; set; } /// <summary> /// 攻击怪物 /// </summary> /// <param name="monster">被攻击的怪物</param> public void Attack(Monster monster) { this.Weapon.AttackTarget(monster); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DigitalFormsSteamLeak.Entity.IModels { public interface IWorkOrderStatusSession { Guid WorkOrderStatusId { get; set; } string WorkDoneBy { get; set; } string WorkOrderStatus { get; set; } string WorkOrderStatusComments { get; set; } DateTime WorkOrderCompletedDate { get; set; } Guid LeakDetailsId { get; set; } } }
using Cs_Notas.Dominio.Entities; using Cs_Notas.Dominio.Interfaces.Repositorios; using Cs_Notas.Dominio.Interfaces.Servicos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Dominio.Servicos { public class ServicoCensec: ServicoBase<Censec>, IServicoCensec { private readonly IRepositorioCensec _repositorioCensec; public ServicoCensec(IRepositorioCensec repositorioCensec) : base(repositorioCensec) { _repositorioCensec = repositorioCensec; } } }
using System.Web.UI; namespace DBTutorial.Account { public partial class ResetPasswordConfirmation : Page { } }
namespace Egret3DExportTools { using UnityEngine; public class StandardSpecularParser : StandardParser { protected override void StandardBegin() { // var roughness = this.GetFloat("_Glossiness", 0.0f); var roughness = 1.0f; var metalness = this.source.GetFloat("_Metallic", 0.0f); var emissive = this.source.GetColor("_EmissionColor", Color.black); this.data.values.SetColor3("emissive", emissive, Color.black); this.data.values.SetNumber("roughness", roughness, 0.5f); this.data.values.SetNumber("metalness", metalness, 0.5f); var specularMap = this.source.GetTexture("_SpecGlossMap", null); if (specularMap != null) { this.data.values.SetTexture("specularMap", specularMap); } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Engine.Events; public class BaseGameUIPanelResultsCollectionSafety : GameUIPanelResultsBase { public static GameUIPanelResultsCollectionSafety Instance; public static bool isInst { get { if(Instance != null) { return true; } return false; } } public virtual void Awake() { } public override void OnEnable() { base.OnEnable(); Messenger<string>.AddListener(ButtonEvents.EVENT_BUTTON_CLICK, OnButtonClickEventHandler); } public override void OnDisable() { base.OnDisable(); Messenger<string>.RemoveListener(ButtonEvents.EVENT_BUTTON_CLICK, OnButtonClickEventHandler); } public override void Start() { Init(); } public override void Init() { base.Init(); loadData(); } public override void OnButtonClickEventHandler(string buttonName) { base.OnButtonClickEventHandler(buttonName); //Debug.Log("OnButtonClickEventHandler: " + buttonName); } public override void UpdateDisplay(GamePlayerRuntimeData runtimeData, float timeTotal) { base.UpdateDisplay(runtimeData, timeTotal); } public override void loadData() { base.loadData(); StartCoroutine(loadDataCo()); } public override IEnumerator loadDataCo() { base.loadDataCo(); yield return new WaitForSeconds(1f); } }
using ND.FluentTaskScheduling.Model; using ND.FluentTaskScheduling.Model.request; using ND.FluentTaskScheduling.Model.response; using ND.FluentTaskScheduling.TaskInterface; //********************************************************************** // // 文件名称(File Name): // 功能描述(Description): // 作者(Author): // 日期(Create Date): 2017-04-07 10:56:43 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期: 2017-04-07 10:56:43 // 修改理由: // // R2: // 修改作者: // 修改日期: 2017-04-07 10:56:43 // 修改理由: // //********************************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ND.FluentTaskScheduling.Domain.interfacelayer { public interface ITaskRepository:IRepository<tb_task> { /// <summary> /// 添加任务并返回自增id /// </summary> /// <param name="task"></param> /// <returns></returns> int AddTask(tb_task task); /// <summary> /// 根据id 更新 /// </summary> /// <param name="ids"></param> /// <param name="fileds"></param> void UpdateById(List<int> ids, Dictionary<string, string> fileds); /// <summary> /// 载入任务分页列表 /// </summary> /// <param name="totalCount"></param> /// <param name="req"></param> /// <param name="orderby"></param> /// <returns></returns> List<TaskListDto> LoadTaskPageList(out int totalCount, LoadTaskListRequest req, System.Linq.Expressions.Expression<Func<tb_task,string>> orderby = null); } }
namespace Alabo.Domains.Query.Dto { /// <summary> /// Api接口类 /// </summary> public class ApiOutputDto { } }
using System; using System.Collections.Generic; using System.Reflection; using TraceWizard.Entities; using TraceWizard.Analyzers; using TraceWizard.Classification.Classifiers.J48; using TraceWizard.Classification.Classifiers.Null; using TraceWizard.Classification.Classifiers.Leak; using TraceWizard.Classification.Classifiers.OneRulePeak; using TraceWizard.Classification.Classifiers.RepTree; using TraceWizard.Classification.Classifiers.FixtureList; using TraceWizard.Environment; namespace TraceWizard.Classification { public static class TwClassifiers { public static bool CanLoad(Classifier classifier) { if (classifier is Classification.Classifiers.NearestNeighbor.NearestNeighborClassifier && !System.IO.File.Exists(TwEnvironment.TwExemplars)) return false; return true; } public static List<Classifier> CreateClassifiers() { var classifiers = new List<Classifier>(); classifiers.Add(new TraceWizard.Classification.Classifiers.J48.J48Classifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.FixtureList.FixtureListClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.J48.J48ClothesWasherFrontClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.J48.J48ClothesWasherTopClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.J48.J48IndoorClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.J48.J48IsolatedLeakClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.NearestNeighbor.NearestNeighborv15p18d25m18Classifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.Null.NullClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.Leak.LeakClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.OneRulePeak.OneRulePeakClassifier()); classifiers.Add(new TraceWizard.Classification.Classifiers.RepTree.RepTreeClassifier()); return classifiers; } } public abstract class Classifier : Analyzer { public Analysis Analysis { get; set; } public Classifier() { } public Classifier(Analysis analysis) { Analysis = analysis; } public string GetName() { return Name; } public string GetDescription() { return Description; } public abstract string Name { get; } public abstract string Description { get; } public virtual void PreClassify() { } public abstract FixtureClass Classify(Event @event); public Analysis Classify(Analysis analysis) { Analysis = analysis; return Classify(); } public virtual Analysis Classify() { Analysis.ClearFirstCycle(); Analysis.ClearManuallyClassified(); foreach (Event @event in Analysis.Events) { @event.FixtureClass = Classify(@event); } return Analysis; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Index : System.Web.UI.Page { Dictionary<string, bool> UserList = new Dictionary<string, bool>(); protected void Page_Load(object sender, EventArgs e) { string clearSessionFlag = "0"; if (Request.QueryString["ClearSessionFlag"] != null) { clearSessionFlag = Request.QueryString["ClearSessionFlag"].ToString(); if (clearSessionFlag == "1") { Session.Clear(); } } } protected void btnLogin_Click(object sender, EventArgs e) { using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString)) { cn.Open(); string username = txtUser.Text; string password = txtPass.Text; SqlCommand cmd = new SqlCommand("proc_AllCashReport_Login", cn); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@UserName", username)); cmd.Parameters.Add(new SqlParameter("@Password", password)); SqlDataAdapter da = new SqlDataAdapter(cmd); int ret = 0; ret = Convert.ToInt32(cmd.ExecuteScalar()); if (ret == 1) { if (UserList.Count > 0 && UserList.All(x => x.Key != username)) { UserList.Add(username, true); } else { UserList.Add(username, true); } Session["AllCashReportLogin"] = UserList; Response.Redirect("~/AllCashReport_V2.aspx"); } else { ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "showValidateMsg();", true); if (UserList.Count > 0 && UserList.All(x => x.Key != username)) { UserList.Add(username, false); } else { UserList.Add(username, false); } Session["AllCashReportLogin"] = UserList; } cn.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutomationAnywhere { class Program { static void Main(string[] args) { MyClassTest obj = new MyClassTest(); obj.DoStuff(); Console.WriteLine("\nNumbers of Pages: "); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using Aquamonix.Mobile.Lib.Utilities; namespace Aquamonix.Mobile.Lib.Domain { public static class StringLiterals { public const string Alerts = "Alerts"; public const string Stations = "Stations"; public const string Programs = "Programs"; public const string Schedules = "Schedules"; public const string Circuits = "Circuits"; public const string Disabled = "Disabled"; public const string DismissAll = "DismissAll"; public const string Error = "Error"; public const string Update = "Update"; public const string Start = "Start"; public const string Stop = "Stop"; public const string UserSettingsTitle = "Settings"; public const string LogoutButtonText = "Logout"; public const string SupportButtonText = "Contact Support"; public const string UnknownErrorText = "An unknown error has occurred."; public const string UsernameTextFieldPlaceholder = "Email"; public const string PasswordTextFieldPlaceholder = "Password"; public const string ServerUriTextFieldPlaceholder = "Connect to"; public const string CancelButtonText = "Cancel"; public const string OkButtonText = "Yes"; public const String YesButtonText = "Dismiss All"; public const string SelectAllButtonText = "Select All"; public const string DoneButtonText = "Done"; public const string ConnectionError = "Connection Error"; public const string GenericErrorAlertTitle = "Error"; public const string AlertConfirmButtonText = "OK"; public const string Devices = "Devices"; public const string Disable = "Disable"; public const string StandBy = "Stand By"; public const string EndGun = "End Gun"; public const string Aux1 = "Aux 1"; public const string Aux2 = "Aux 2"; public const string Fwd = "Fwd"; public const string Rev = "Rev"; public const string Auto = "Auto"; public const string Reverse = "Reverse"; //do not change public const string Forward = "Forward"; //do not change public const string Wet = "Wet"; public const string Dry = "Dry"; public const string Speed = "Speed"; public const string Watering = "Watering"; public const string AutoStop = "Auto Stop"; public const string AutoRev = "Auto Rev"; public const string StepNumber = "Step1"; public const string Angle = "50 deg"; public const string MM = "mm"; public const string EndGunE = "E"; public const string Aux1A1 = "A1"; public const string Aux2A2 = "A2"; public const string PivotPrograms = "PivotPrograms"; public const string TimerSetButtonText = "Set"; public const string TimerTitle = "Timer"; public const string TurnOnPermanently = "Turn on Permanently"; public const string On = "On"; public const string Sensors = "Sensors"; public const string Off = "Off"; public const string SearchTextPlaceholder = "Search"; public const string SupportRequestSubject = "Aquamonix App Support"; public const string DeviceNotFoundErrorMessage = "Sorry, device {0} could not be found in the database."; public const string DeviceNotFoundErrorTitle = "Device Not Found"; public const string TestStationConfirmationTitle = "Test Station"; public const string TestStationConfirmationMessage = "Test {0} ({1}) without running any pumps or master valves? (Station may start watering if the main line is pressurised)"; public const string StartStationConfirmationTitle = "Start Station"; public const string Alert = "Alert"; public const string StartStationConfirmationMessage = "Start {0} ({1})? (This will stop the previous station started manually)"; public const string TestButtonText = "Test"; public const string WateringButtonText = "Watering"; public const string StopTestButtonText = "Stop Test"; public const string StartButtonText = "Start"; public const string StopButtonText = "Stop"; public const string Starting = "Starting"; public const string Stopping = "Stopping"; public const string Stopped = "Stopped"; //do not change public const string Waiting = "Waiting"; //do not change public const string ProgramStopped = "Program Stopped"; public const string Running = "Running"; //do not change public const string ProgramRunning = "Program Running"; public const string StartProgramConfirmationTitle = "Start Program"; public const string StopProgramConfirmationTitle = "Stop Program"; public const string NoMailSupportAlertTitle = "No Mail Support"; public const string NoMailSupportAlertMessage = "Sorry, your device is not set up to send mail. Please contact email support: {0}"; public const string EnableDeviceConfirmationTitle = "Enable Device"; public const string DisableDeviceConfirmationTitle = "Disable Device"; public const string ScaleProgramsConfirmationTitle = "Scale Programs"; public const string StartWatering = "Start Watering"; public const string StartCircuits = "Start Circuits"; public const string SetTimer = "Set Timer"; public const string SelectPumps = "Select Pumps"; public const string SchedulesEmptyMessage = "This device has no schedules to display at the moment"; public const string StationsEmptyMessage = "This device has no stations to display at the moment"; public const string ProgramsEmptyMessage = "This device has no programs to display at the moment"; public const string DevicesEmptyMessage = "There are no devices to display at the moment"; public const string CircuitsEmptyMessage = "This device has no circuits to display at the moment"; public const string AlertsEmptyMessage = "This device has no alerts to display at the moment"; public const string AuthFailure = "Authentication Failure"; public const string AuthFailureMessage = "Failed to log in/authenticate with server"; public const string UserNotAuthenticated = "User not authenticated."; public const string ConnectionTimeout = "Connection Timeout"; public const string UnableToEstablishConnection = "Unable to establish a connection with the server."; public const string ConnectionUnavailable = "Connection Unavailable"; public const string ConnectionLost = "Connection to the server has been lost."; public const string TryAgain = "We can try again to reconnect, or go back to Settings."; public const string Reconnecting = "Reconnecting"; public const string Connected = "Connected"; public const string ServerNotAvailable = "Server not Available"; public const string PleaseWaitReconnect = "Please wait while we try to reconnect you."; public const string UpdatingText = "Updating..."; public const string Today = "Today"; public const string Yesterday = "Yesterday"; public const string Pivot = "Pivot"; public const string EmailText = "Please send us this email if you have a question, would like to provide some feedback, or if you experience any difficulty using this app.You can attach screenshots of your device to this email if they provide information related to your support request.You can also add any comments below to help explain the issue or ask a question. We have included some technical information in this email to help us assist and improve our products.\n\n" + "Your comments:\n\n\n\n" + "Device info: \n\n"; //added public const string Dismiss = "Dismiss"; public static string FormatScaleProgramsConfirmationMessage(int value) { return String.Format("Scale programs to {0}% of their normal run time on all controllers in this group? (This will not affect programs already running)", value); } public static string FormatDeviceNotFoundErrorMessage(string deviceId) { return String.Format(DeviceNotFoundErrorMessage, deviceId); } public static string FormatTestStationConfirmationMessage(IEnumerable<string> stationNames, IEnumerable<string> stationNumbers) { return String.Format(TestStationConfirmationMessage, StringUtility.ToCommaDelimitedList(stationNames, "station", "stations"), StringUtility.ToCommaDelimitedList(stationNumbers, "station", "stations")); } public static string FormatStartStationConfirmationMessage(IEnumerable<string> stationNames, IEnumerable<string> stationNumbers) { return String.Format(StartStationConfirmationMessage, StringUtility.ToCommaDelimitedList(stationNames, "station", "stations"), StringUtility.ToCommaDelimitedList(stationNumbers, "station", "stations")); } public static string FormatNumberSelected(int number) { return String.Format("{0} Selected", number); } public static string FormatStartStopProgramConfirmationMessage(bool start, string programName, string programId) { string action = start ? "Start" : "Stop"; return String.Format("{0} Program {1} (program {2})?", action, programName, programId); } public static string FormatDismissAlertsConfirmationMessage() { string Alert = "Mark all new alrms as read?"; return String.Format( Alert); } //added// public static string DismissAllAlertsConfirmationMessage() { string Alert = "Dismiss all alerts?"; return String.Format(Alert); } //added public static string ActiveAlertsNotAccessForDissmiss() { string Alert = "You do not have permission to dismiss some active alerts"; return String.Format(Alert); } public static string FormatProgramsAtPercent(int percent) { return String.Format("Programs at {0}%", percent); } public static string FormatDisabledUntil(DateTime? disabledUntil) { return String.Format("Disabled {0}", FormatTimeUntil(disabledUntil)); } public static string FormatEnableDisableDeviceConfirmationMessage(bool enable) { return String.Format("Are you sure you want to {0} the device?", enable ? "enable" : "disable"); } public static string FormatTimeUntil(DateTime? time) { if (time == null) return "indefinitely"; else { var ts = time.Value.Subtract(DateTime.Now); int days = 0; int hours = 0; int minutes = 0; int seconds = (int)ts.TotalSeconds; if (ts.TotalDays >= 1) { days = (int)Math.Floor(ts.TotalDays); seconds -= 86400 * days; } if (seconds >= 3600) { hours = (int)Math.Floor((double)(seconds / 3600)); seconds -= (hours * 3600); } if (seconds >= 60) { minutes = (int)Math.Floor((double)(seconds / 3600)); seconds -= (minutes * 60); } var sb = new System.Text.StringBuilder(); if (days > 0) sb.Append(String.Format("{0} {1} ", days, ((days > 1) ? "days" : "day"))); if (hours > 0) sb.Append(String.Format("{0} {1} ", hours, ((hours > 1) ? "hours" : "hour"))); if (minutes > 0) sb.Append(String.Format("{0} {1} ", minutes, ((minutes > 1) ? "minutes" : "minute"))); return "for " + sb.ToString().Trim(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FBS.Domain.Core { public class InMemoryContext<TAggregate> : IAggregateContext<TAggregate> where TAggregate : class, IAggregate { private readonly IDictionary<Guid, TAggregate> aggregates; private readonly IEventStore eventStore; public InMemoryContext(IEventStore eventStore) { aggregates = new Dictionary<Guid, TAggregate>(); this.eventStore = eventStore; } private async Task SaveAsync(TAggregate aggregate) { aggregates.Add(aggregate.Id, aggregate); await Task.CompletedTask; } public Type AggregateType => typeof(TAggregate); public async Task ApplyAsync(IDomainEvent @event) { var aggregate = aggregates.ContainsKey(@event.AggregateId) ? aggregates[@event.AggregateId] : null; if (aggregate == null) { aggregate = AggregateBase.CreateEmptyAggregate<TAggregate>(); aggregate.RaiseEvent(@event); await SaveAsync(aggregate); } else { aggregate.RaiseEvent(@event); } } public void Dispose() { eventStore.Dispose(); } public async Task<TAggregate> GetAggregateByIdAsync(Guid aggregateId) { if (aggregates.ContainsKey(aggregateId)) { return await Task.FromResult(aggregates[aggregateId]); } throw new Exception($"Aggregate {aggregateId} not found in Context"); } public Task<IEnumerable<TAggregate>> GetAllAggregates() { return Task.FromResult(aggregates.Values.AsEnumerable<TAggregate>()); } public Task<IEnumerable<TAggregate>> GetAggregatesWhere(Func<TAggregate, bool> predicate) { return Task.FromResult(aggregates.Values.AsEnumerable<TAggregate>().Where(predicate)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicicio18 { class CapitalAcumulado { static void Main(string[] args) { { const int Anos = 3, Anoinicio = 2010; const double Taxamin = 2, Taxamax = 3, Inicial = 1500; double Acumu = 0; Console.Write((Inicial.ToString() + "EUR").PadRight(8)); for (double Taxa = Taxamin; Taxa <= Taxamax; Taxa += 0.5) Console.Write("{0,13:P1}", Taxa / 100); Console.WriteLine(); for (int N = 1; N <= Anos; N++) { Console.Write((Anoinicio + N).ToString().PadRight(8)); for (double Taxa = Taxamin; Taxa <= Taxamax; Taxa += 0.5) { Acumu = Math.Round(Inicial * Math.Pow((1 + Taxa / 100), N), 2); Console.Write("{0, 13:F2}", Acumu); } Console.WriteLine(); } } } } }