text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TweetSharp; using LinqToTwitter; using System.Configuration; using System.Timers; using Google.Apis.Urlshortener.v1; using Google.Apis.Services; namespace SharpDictionary { class Program { static void Main(string[] args) { Console.Title = "SharpDictionary - Checking...."; Console.SetWindowSize(25, 5); Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.White; // Icons from http://ic8.link/453 and http://ic8.link/437 // while (true) { dateStuff(); System.Threading.Thread.Sleep(60000); // Wait for an hour Console.WriteLine("Checked date " + DateTime.Now.TimeOfDay.ToString().Substring(0, 8)); } } private static void dateStuff() { string line = System.IO.File.ReadAllText(@"date.dat"); if (line.Substring(0, 9) != DateTime.Now.Date.ToString().Substring(0, 9)) { readLines(); System.IO.File.WriteAllText(@"date.dat", DateTime.Now.Date.ToString(), Encoding.UTF8); Console.WriteLine("It's a new day!" + Environment.NewLine + "Posted to Twitter."); } else { Console.WriteLine("It's still today!"); } } public static Google.Apis.Urlshortener.v1.Data.Url publicUrl = new Google.Apis.Urlshortener.v1.Data.Url(); public static string response { get; set; } private static void googleStuff(string url) { UrlshortenerService service = new UrlshortenerService(new BaseClientService.Initializer() { ApiKey = "AIzaSyCetMcIe3VOy0skeuJbWSZZ5M-BKyTkUk4", ApplicationName = "SharpDictionary", }); var m = new Google.Apis.Urlshortener.v1.Data.Url(); m.LongUrl = url; publicUrl = m; response = service.Url.Insert(m).Execute().Id; } private static void readLines() { string[] lines = System.IO.File.ReadAllLines(@"englishLanguage.dat"); makeTwitterCall(lines); } private static void makeTwitterCall(string[] lines) { string searchQuery = "http://www.google.com/search?q=" + "define " + lines.First(); googleStuff(searchQuery); var service = new TwitterService("bOMj58v2TPT4Jr0Pob256D2Jo", "6yU8qWsWnWyhzO0wBs3fm8njpGvA1BGxSapC9kee5134hTrXpp"); service.AuthenticateWith("4896141748-yoyZLt4wu5RWBZn6uiTP5H3f90jb9Uy2JsWdcK9", "GzvkjWZOvKNaLcF2G0vlsY3nnY8S43YT0o9w8WDt5ewNC"); TwitterStatus result = service.SendTweet(new SendTweetOptions { Status = "The word of the day is '" + lines.First() + "'." + Environment.NewLine + "#sharpdictionary #everyword #" + lines.First() + " " + "#" + (lines.Length-1).ToString() + "togo" + Environment.NewLine + response }); var newLines = lines.Where(val => val != lines.First()).ToArray(); System.IO.File.WriteAllText(@"englishLanguage.dat", string.Empty); System.IO.File.WriteAllLines(@"englishLanguage.dat", newLines, Encoding.UTF8); } } }
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; namespace EurogamerCommentsApi { internal class Article : INotifyPropertyChanged { #region Private members private string _title; private Uri _uri; private string _contents; private uint _articleId; private Uri _jsonCommentsUri; private Comment[] _comments; #endregion Private members #region Public properties public Uri Uri { get { return _uri; } set { if (_uri == value) return; _uri = value; OnPropertyChanged(); } } public string Contents { get { return _contents; } set { if (_contents == value) return; _contents = value; OnPropertyChanged(); } } public uint ArticleId { get { return _articleId; } set { if (_articleId == value) return; _articleId = value; OnPropertyChanged(); } } public Uri JsonCommentsUri { get { return _jsonCommentsUri; } set { if (_jsonCommentsUri == value) return; _jsonCommentsUri = value; OnPropertyChanged(); } } public Comment[] Comments { get { return _comments; } set { if (_comments == value) return; _comments = value; OnPropertyChanged(); } } public string Title { get { return _title; } set { if (_title == value) return; _title = value; OnPropertyChanged(); } } #endregion Public properties #region Constructor internal Article(string title, Uri uri) { PropertyChanged += Article_PropertyChanged; Title = title; Uri = uri; } #endregion Constructor #region INotifyPropertyChanged members private void Article_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(Uri): Contents = Web.Request(Uri); break; case nameof(Contents): var match = Regex.Match(Contents, @"'aid': (\d+),"); ArticleId = uint.Parse(match.Groups[1].Value); break; case nameof(ArticleId): JsonCommentsUri = new Uri($"http://www.eurogamer.net/ajax.php?action=json-comments&aid={ArticleId:D}&start=0&limit=999999&filter=all&order=asc"); break; case nameof(JsonCommentsUri): Comments = Web.Request<Comment[]>(JsonCommentsUri); break; } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion INotifyPropertyChanged members public override string ToString() { return $"{ArticleId} {Title}"; } } }
namespace BattleEngine.Records { public class BattleUnitRecord { public int id; public int level; public int health; public int ownerId; } }
using DelftTools.Utils; using DelftTools.Utils.Data; namespace GeoAPI.Extensions.Feature { public interface IFeatureData : INameable, IUnique<long> { IFeature Feature { get; set; } object Data { get; set; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CabMedical { public partial class Consultation_aspx : System.Web.UI.Page { ADO d = new ADO(); DataSet dsPat = new DataSet(); SqlDataAdapter daPat; public void RemplirDrop_Patient() { string con = "Data Source=DESKTOP-HT16NSJ\\SQLEXPRESS;Initial Catalog=MyCabMedDB2;Integrated Security=True"; string req = "select Nom_Prénom_Patient , Num_Patient from Patients"; daPat = new SqlDataAdapter(req, con); daPat.Fill(dsPat, "Patients"); DropDownList_Patient.DataTextField = "Nom_Prénom_Patient"; DropDownList_Patient.DataValueField = "Num_Patient"; DropDownList_Patient.DataSource = dsPat.Tables["Patients"]; DropDownList_Patient.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { RemplirDrop_Patient(); } if (Session["User"] == null) { Response.Redirect("Login.aspx"); } TextBox_Medecin.Text = Session["User"].ToString(); } protected void Button_Ajouter_Click(object sender, EventArgs e) { d.connecter(); d.cmd.CommandText = " insert into Consultations (Date_Consultation,Prix,Observation_Consultation,medecin,patient) values ('" + TextBox_Date_Consulation.Text + "'," + TextBox_Prix.Text + ",'" + TextBox1_Description.Text + "','" + TextBox_Medecin.Text + "','" + DropDownList_Patient.Text + "')"; d.cmd.Connection = d.con; d.cmd.ExecuteNonQuery(); d.Deconnecter(); Response.Write("<script>alert('Merci, nous vous contacterons pour confirmer le rendez-vous');window.location = 'Consultation.aspx';</script>"); } protected void Button_View_Click(object sender, EventArgs e) { Response.Redirect("ConsultatioData.aspx"); } } }
using ControleFinanceiro.Domain.Entities; using System; using System.Collections.Generic; namespace ControleFinanceiro.Domain.Contracts.Services { public interface IServicoDespesa : IServicoBase<Despesa> { List<Despesa> ListarDespesaPorData(DateTime data, int idUsuario); } }
using System; namespace UnityAtoms { /// <summary> /// Specify a texture name from your assets which you want to be assigned as an icon to the MonoScript. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class EditorIcon : Attribute { public EditorIcon(string name) { Name = name; } public string Name { get; set; } } }
/* * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * * == AUCTION MASTER == * * Author: Henrique Fantini * Contact: contact@henriquefantini.com * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * * Auction Master is a software with the objective to collect and process data * from World of Warcraft's auction house. The idea behind this is display data * and graphics about the market of each realm and analyse your movimentation. * * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + */ // == IMPORTS // ============================================================================== using AuctionMaster.App.Enumeration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; // == NAMESPACE // ============================================================================== namespace AuctionMaster.App.Exception { // == CLASS // ========================================================================== /// <summary> /// Defines an structure of expcetion related with blizzard API requests. /// </summary> public class AuctionMasterBlizzardException : AuctionMasterException { // == DECLARATIONS // ====================================================================== // == CONST // == VAR // == CONSTRUCTOR(S) // ====================================================================== /// <summary> /// Class constructor /// </summary> /// <param name="message">Error message</param> public AuctionMasterBlizzardException(ExceptionType type, String message) : base(type, message) { } /// <summary> /// Class constructor /// </summary> /// <param name="message">Error message</param> /// <param name="innerException">Inner exception</param> public AuctionMasterBlizzardException(ExceptionType type, String message, System.Exception innerException) : base(type, message, innerException) { } // == METHOD(S) // ====================================================================== // == EVENT(S) // ====================================================================== // == GETTER(S) AND SETTER(S) // ====================================================================== } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MySql.Data.MySqlClient; using System.Data; using System.Configuration; public partial class pages_history : System.Web.UI.Page { private DataLayer sqlOperation = new DataLayer("sqljiuye"); protected void Page_Load(object sender, EventArgs e) { string ispostback = Request.Form["postHistory"];//判断是否有传值 if (IsPostBack && ispostback != null && ispostback == "true") { if (AddNews()) { MessageBox.Message("录入成功!"); } } } /*将数据传入数据库*/ private Boolean AddNews() { string enterprise = Request.Form["enterprise"]; string buildtime = Request.Form["buildTime"]; string usedname = Request.Form["usedName"]; string nowname = Request.Form["nowName"]; string changetime = Request.Form["changeTime"]; string usedname2 = Request.Form["usedName2"]; string nowname2 = Request.Form["nowName2"]; string changetime2 = Request.Form["changeTime2"]; string usedname3 = Request.Form["usedName3"]; string nowname3 = Request.Form["nowName3"]; string changetime3 = Request.Form["changeTime3"]; string remains = Request.Form["remains"]; string product = Request.Form["product"]; string strsqlCommand = "INSERT INTO history(enterprise,buildtime,usedname,nowname,changetime,usedname2,nowname2,changetime2,usedname3,nowname3,changetime3,remains,product,releasetime)" + "VALUES(@enterprise,@buildtime,@usedname,@nowname,@changetime,@usedname2,@nowname2,@changetime2,@usedname3,@nowname3,@changetime3,remains,@product,@releasetime)"; sqlOperation.AddParameterWithValue("@enterprise", enterprise); sqlOperation.AddParameterWithValue("@buildtime", buildtime); sqlOperation.AddParameterWithValue("@usedname", usedname); sqlOperation.AddParameterWithValue("@nowname", nowname); sqlOperation.AddParameterWithValue("@changetime", changetime); sqlOperation.AddParameterWithValue("@usedname2", usedname2); sqlOperation.AddParameterWithValue("@nowname2", nowname2); sqlOperation.AddParameterWithValue("@changetime2", changetime2); sqlOperation.AddParameterWithValue("@usedname3", usedname3); sqlOperation.AddParameterWithValue("@nowname3", nowname3); sqlOperation.AddParameterWithValue("@changetime3", changetime3); sqlOperation.AddParameterWithValue("@remains",remains); sqlOperation.AddParameterWithValue("@product", product); sqlOperation.AddParameterWithValue("@releasetime", DateTime.Now); int intSuccess = sqlOperation.ExecuteNonQuery(strsqlCommand); return (intSuccess > 0) ? true : false; } } //[System.Web.Services.WebMethod()] //public static string AjaxMethod(List<string> olist) //{ // string sb = "("; // foreach (var item in olist) // { // sb = sb + "\"" + item + "\","; // } // for (int i = 0; i < 8; i++) // sb = sb + "\"\","; // sb = sb.Substring(0, sb.Length - 1); // sb = sb + ")"; // //string sb = "("; // //foreach (var item in olist) // //{ // // sb = sb + "\"" + item + "\","; // //} // //sb = sb.Substring(0, sb.Length - 1); // //sb = sb + ")"; // MySqlConnection _sqlConnect;//Mysql连接对象 // MySqlCommand _sqlCommand;//Mysql命令对象 // string _strConnectString;//连接字符串 // _strConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["sqljiuye"].ToString();//!!!数据库名需要修改 // _sqlConnect = new MySqlConnection(_strConnectString); // _sqlCommand = new MySqlCommand("", _sqlConnect); // _sqlConnect.Open(); // _sqlCommand.CommandText = "insert into history values " + sb.ToString(); // if (_sqlCommand.Connection == null) // { // _sqlCommand.Connection = _sqlConnect; // } // try // { // _sqlCommand.ExecuteScalar(); // } // catch // { // _sqlConnect.Close(); // return "0"; // } // _sqlConnect.Close(); // return "1"; //}
using System; using EntoEvents = Entoarox.Framework.Core.Utilities.Events; namespace Entoarox.Framework.Events { public static class MoreEvents { /********* ** Accessors *********/ /// <summary>Triggered whenever a action tile is activated by the player.</summary> public static event EventHandler<EventArgsActionTriggered> ActionTriggered; /// <summary>Triggered whenever a action tile is first walked onto by the player.</summary> public static event EventHandler<EventArgsActionTriggered> TouchActionTriggered; /********* ** Public methods *********/ internal static void FireActionTriggered(EventArgsActionTriggered eventArgs) { EntoEvents.FireEventSafely("ActionTriggered", ActionTriggered, eventArgs); } internal static void FireTouchActionTriggered(EventArgsActionTriggered eventArgs) { EntoEvents.FireEventSafely("TouchActionTriggered", TouchActionTriggered, eventArgs); } } }
using System; namespace Cradiator.Model { public interface IDateTimeNow { DateTime Now { get; set; } } // a class just used for mocking out calls to DateTime public class DateTimeNow : IDateTimeNow { public DateTime Now { get => DateTime.Now; set { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAppWood.Models { public class ModelVenta { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SidebarScript : MonoBehaviour { SpriteRenderer render; public Sprite play; public Sprite pause; void Start() { render = gameObject.GetComponent<SpriteRenderer>(); } public void setPlay(){ render.sprite = play; } public void setPause(){ render.sprite = pause; } }
using AutoMapper; using XH.Commands.Shared; using XH.Domain.Seo.Models; using XH.Infrastructure.Mapper; namespace XH.Command.Handlers.Configs { public class SharedMapperRegistrar : IAutoMapperRegistrar { public void Register(IMapperConfigurationExpression cfg) { cfg.CreateMap<CreateOrUpdateCommandSEOMetaData, SEOMetaData>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace gMediaTools.Models { public class VideoFrameSection { public int StartFrameNumber { get; set; } public int EndFrameNumber { get; set; } public string Name { get; set; } public List<VideoFrameInfo> FramesToDelete { get; } = new List<VideoFrameInfo>(); public List<VideoFrameInfo> FramesToDuplicate { get; } = new List<VideoFrameInfo>(); } }
using System; using Assets.Scripts.Data; using Assets.Scripts.Service; using UnityEngine; using UnityEngine.UI; namespace Assets.Scripts.Controller { public class UIController : MonoBehaviour { [SerializeField] private GameController _gameController; [SerializeField] private LocalDataService _localDataService; [SerializeField] private CameraZoomService _cameraZoomService; [SerializeField] private BlockController _blockController; [SerializeField] private Text _scoreText; [SerializeField] private Text _bestScoreText; [SerializeField] private RawImage _menuBack; [SerializeField] private Material _gameBackMaterial; [SerializeField] private Animator _animator; private int _currentScore = 0; private int _bestScore = 0; private PlayerData _playerData; private Texture2D backgroundTexture; private void Awake() { PrepareDelegates(); PrepareTexture(); } private void PrepareTexture() { backgroundTexture = new Texture2D(1, 2); backgroundTexture.wrapMode = TextureWrapMode.Clamp; backgroundTexture.filterMode = FilterMode.Bilinear; } private void Start() { UpdateScores(); } private void PrepareDelegates() { _gameController.onGameLostAnimations += LostGame; _gameController.onGameStart += StartGame; _blockController.onBlockStacked += IncreaseScore; _localDataService.onDataLoaded += SetupDataFromLocal; _localDataService.onScreenShootLoaded += SetupBackGround; _cameraZoomService.onZoomedOut += GameLost; } public void UpdateScreenShoot() { _localDataService.UpdateScreenShoot(); } public void SetGameLost() { _gameController.InvokeGameLost(); } private void StartGame() { _cameraZoomService.ZoomIn(); _animator.SetTrigger("NewGame"); } private void SetRandomBack() { SetColor(UnityEngine.Random.ColorHSV(), UnityEngine.Random.ColorHSV()); } public void SetColor(Color color1, Color color2) { backgroundTexture.SetPixels(new Color[] { color1, color2 }); backgroundTexture.Apply(); _gameBackMaterial.SetTexture("_MainTex", backgroundTexture); } private void LostGame() { _cameraZoomService.ZoomOut(); } private void SetupBackGround(Texture2D screenShoot) { Debug.Log("setup back"); if(screenShoot == null) { SetRandomBack(); screenShoot = backgroundTexture; } _menuBack.texture = screenShoot; } private void SetupDataFromLocal(PlayerData currentData) { _playerData = currentData; _bestScore = _playerData.playerScore; UpdateScoreText(_bestScoreText, _bestScore); } private void IncreaseScore() { _currentScore++; UpdateScoreText(_scoreText, _currentScore); } private void UpdateScores() { if (_currentScore > _bestScore) { _bestScore = _currentScore; _playerData.playerScore = _bestScore; UpdateScoreText(_bestScoreText, _bestScore); } _currentScore = 0; UpdateScoreText(_scoreText, _currentScore); _localDataService.SetNewDataAndSave(_playerData); } private void UpdateScoreText(Text updateText, int score) { updateText.text = score.ToString(); } private void GameLost() { UpdateScores(); _animator.SetTrigger("LostGame"); UpdateScreenShoot(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.Ajax.Utilities; namespace WebQLKhoaHoc.Models { public class NhaKhoaHocViewModel { public int DsBaiBao { get; set; } public int DsDetai { get; set; } public int DsSach { get; set; } public int MaNKH { get; set; } public string MaNKHHoSo { get; set; } public string HoNKH { get; set; } public string TenNKH { get; set; } public string GioiTinhNKH { get; set; } public string NoiSinh { get; set; } public Nullable<System.DateTime> NgaySinh { get; set; } public string DiaChiLienHe { get; set; } public string DienThoai { get; set; } public string EmailLienHe { get; set; } public int? MaHocHam { get; set; } public virtual HocHam HocHam { get; set; } public DateTime NamKetThucDaoTao { get; set; } public int? MaHocVi { get; set; } public int? MaCNDaoTao { get; set; } public int? MaDonViQL { get; set; } public string AnhCaNhan { get; set; } public int? MaNgachVienChuc { get; set; } public string SoCMND { get; set; } public string EmailThayThe { get; set; } public virtual NhaKhoaHoc_KH NhaKhoaHoc_KH { get; set; } public virtual ICollection<DSPhatMinhNKH> DSPhatMinhNKHs { get; set; } public virtual ICollection<ChuyenMonNKH> ChuyenMonNKHs { get; set; } public virtual ChuyenNganh ChuyenNganh { get; set; } public virtual DonViQL DonViQL { get; set; } public virtual ICollection<DSNguoiThamGiaBaiBao> DSNguoiThamGiaBaiBaos { get; set; } public virtual ICollection<DSNguoiThamGiaDeTai> DSNguoiThamGiaDeTais { get; set; } public virtual ICollection<DSTacGia> DSTacGias { get; set; } public virtual HocVi HocVi { get; set; } public virtual NgachVienChuc NgachVienChuc { get; set; } public virtual ICollection<QuaTrinhCongTac> QuaTrinhCongTacs { get; set; } public virtual ICollection<QuaTrinhDaoTao> QuaTrinhDaoTaos { get; set; } public virtual ICollection<LinhVuc> LinhVucs { get; set; } public virtual ICollection<TrinhDoNgoaiNgu> TrinhDoNgoaiNgus { get; set; } public virtual ICollection<NgoaiNguNKH> NgoaiNguNKHs { get; set; } public virtual NganHangNKH NganHangNKHs { get; set; } public static NhaKhoaHocViewModel Mapping(NhaKhoaHoc nkh) { NhaKhoaHocViewModel nkhvm = new NhaKhoaHocViewModel(); nkhvm.NgachVienChuc = nkh.NgachVienChuc ?? new NgachVienChuc(); nkhvm.NgaySinh = nkh.NgaySinh ?? new DateTime(); nkhvm.HoNKH = nkh.HoNKH ?? String.Empty; nkhvm.TenNKH = nkh.TenNKH ?? String.Empty; nkhvm.AnhCaNhan = nkh.AnhCaNhan != null ? string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(nkh.AnhCaNhan)) : String.Empty; nkhvm.DienThoai = nkh.DienThoai ?? String.Empty; nkhvm.DiaChiLienHe = nkh.DiaChiLienHe ?? String.Empty; nkhvm.HocHam = nkh.HocHam ?? new HocHam(); nkhvm.NamKetThucDaoTao = (nkh.QuaTrinhDaoTaos.Count > 0 && nkh.QuaTrinhDaoTaos != null) ? nkh.QuaTrinhDaoTaos.Where(p => p.MaNKH == nkh.MaNKH).Max(t => t.ThoiGianKT).Value : DateTime.Now; nkhvm.HocVi = nkh.HocVi ?? new HocVi(); nkhvm.DonViQL = nkh.DonViQL ?? new DonViQL(); nkhvm.MaCNDaoTao = nkh.MaCNDaoTao ; nkhvm.MaDonViQL = Convert.ToInt32(nkh.MaDonViQL) ; nkhvm.EmailLienHe = nkh.EmailLienHe ?? String.Empty; nkhvm.EmailThayThe = nkh.EmailThayThe ?? String.Empty; nkhvm.QuaTrinhCongTacs = nkh.QuaTrinhCongTacs ?? new List<QuaTrinhCongTac>(); nkhvm.QuaTrinhDaoTaos = nkh.QuaTrinhDaoTaos ?? new List<QuaTrinhDaoTao>(); nkhvm.DSNguoiThamGiaBaiBaos = nkh.DSNguoiThamGiaBaiBaos ?? new List<DSNguoiThamGiaBaiBao>(); nkhvm.DSNguoiThamGiaDeTais = nkh.DSNguoiThamGiaDeTais ?? new List<DSNguoiThamGiaDeTai>(); nkhvm.DSTacGias = nkh.DSTacGias ?? new List<DSTacGia>(); nkhvm.TrinhDoNgoaiNgus = nkh.NgoaiNguNKHs.Select(p=>p.TrinhDoNgoaiNgu).ToList() ?? new List<TrinhDoNgoaiNgu>(); nkhvm.MaNKHHoSo = nkh.MaNKHHoSo ?? String.Empty ; nkhvm.MaHocVi = nkh.MaHocVi ?? 0 ; nkhvm.MaHocHam = nkh.MaHocHam ?? 0 ; nkhvm.MaNgachVienChuc = nkh.MaNgachVienChuc ?? 0; nkhvm.MaNKH = nkh.MaNKH; nkhvm.ChuyenMonNKHs = nkh.ChuyenMonNKHs ?? new List<ChuyenMonNKH>(); nkhvm.GioiTinhNKH = nkh.GioiTinhNKH ?? String.Empty; nkhvm.ChuyenNganh = nkh.ChuyenNganh ?? new ChuyenNganh(); nkhvm.LinhVucs = nkh.LinhVucs ?? new List<LinhVuc>(); nkhvm.DsBaiBao = nkh.DSNguoiThamGiaBaiBaos.Where(p => p.MaNKH == nkh.MaNKH).Count(); nkhvm.DsSach = nkh.DSTacGias.Where(p => p.MaNKH == nkh.MaNKH).Count(); nkhvm.DsDetai = nkh.DSNguoiThamGiaBaiBaos.Where(p => p.MaNKH == nkh.MaNKH).Count(); nkhvm.NgoaiNguNKHs = nkh.NgoaiNguNKHs ?? new List<NgoaiNguNKH>(); nkhvm.NganHangNKHs = nkh.NganHangNKH ?? new NganHangNKH(); nkhvm.NoiSinh = nkh.NoiSinh ?? String.Empty; nkhvm.SoCMND = nkh.SoCMND ?? String.Empty; nkhvm.NhaKhoaHoc_KH = nkh.NhaKhoaHoc_KH ?? new NhaKhoaHoc_KH(); nkhvm.DSPhatMinhNKHs = nkh.DSPhatMinhNKHs ?? new List<DSPhatMinhNKH>(); return nkhvm; } } }
namespace RankingSystem.Common.Domain { public class Enums { public enum StatusEnum : byte { Pending = 1, Activated = 2 } } }
using AcoesDotNet.Dal.Daos; using System.Threading.Tasks; namespace AcoesDotNet.Repository { public class DataBaseRepository : IDatabaseRepository { private IDataBaseDao _dataBaseDao = new DataBaseDao(); public Task InicializaAsync(string connecionString) { return _dataBaseDao.InicializaAsync(connecionString); } } }
using System.Collections.ObjectModel; using System.Collections.Generic; namespace fileCrawlerWPF.Util { static class FileAliases { public static IReadOnlyCollection<string> x264Aliases = new ReadOnlyCollection<string>(new[] { "x264", "h264", "h.264", "h.264/mpeg-4", "h.264/mpeg-4 avc", "h.264/mp4", "h.264/mp4 avc" }); public static IReadOnlyCollection<string> x265Aliases = new ReadOnlyCollection<string>(new[] { "h265", "hevc", "hevc/h.265", "x265" }); } }
using System; using System.Collections.Generic; using Pathoschild.Stardew.Common.Utilities; namespace ContentPatcher.Framework.Tokens.ValueProviders { /// <summary>A value provider for user-defined dynamic tokens.</summary> internal class DynamicTokenValueProvider : BaseValueProvider { /********* ** Fields *********/ /// <summary>The allowed root values (or <c>null</c> if any value is allowed).</summary> private readonly InvariantHashSet AllowedRootValues; /// <summary>The current values.</summary> private InvariantHashSet Values = new InvariantHashSet(); /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="name">The value provider name.</param> public DynamicTokenValueProvider(string name) : base(name, canHaveMultipleValuesForRoot: false) { this.AllowedRootValues = new InvariantHashSet(); this.EnableInputArguments(required: false, canHaveMultipleValues: false); } /// <summary>Add a set of possible values.</summary> /// <param name="possibleValues">The possible values to add.</param> public void AddAllowedValues(InvariantHashSet possibleValues) { foreach (string value in possibleValues) this.AllowedRootValues.Add(value); this.CanHaveMultipleValuesForRoot = this.CanHaveMultipleValuesForRoot || possibleValues.Count > 1; } /// <summary>Set the current values.</summary> /// <param name="values">The values to set.</param> public void SetValue(InvariantHashSet values) { this.Values = values; } /// <summary>Set whether the token is valid for the current context.</summary> /// <param name="ready">The value to set.</param> public void SetReady(bool ready) { this.IsReady = ready; } /// <summary>Get the allowed values for an input argument (or <c>null</c> if any value is allowed).</summary> /// <param name="input">The input argument, if applicable.</param> /// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception> public override InvariantHashSet GetAllowedValues(string input) { return input != null ? InvariantHashSet.Boolean() : this.AllowedRootValues; } /// <summary>Get the current values.</summary> /// <param name="input">The input argument, if applicable.</param> /// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception> public override IEnumerable<string> GetValues(string input) { this.AssertInputArgument(input); if (input != null) return new[] { this.Values.Contains(input).ToString() }; return this.Values; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Ferris_Directory_Scanner { public static class ScanThings { public static MetroFramework.Forms.MetroForm ProcessCommandLineParameter(string[] args) { if (args.Length > 1) { if (args.Length > 0) { foreach (var s in args) if (File.Exists(s) && s.EndsWith(".fds")) { return OpenResult(s); } } } return new FormMain(); } public static MetroFramework.Forms.MetroForm OpenResult(string xmlfilepath) { var OwnFiles = XMLHelper.Load(xmlfilepath); if (OwnFiles == null) return null; FormListView frmList = new FormListView(OwnFiles); return frmList; } public static MetroFramework.Forms.MetroForm OpenResult(List<OwnFile> OwnFiles) { if (OwnFiles == null) return null; FormListView frmList = new FormListView(OwnFiles); return frmList; } public static List<OwnFile> DeleteNullOwnFile(List<OwnFile> ownFiles) { foreach (var file in ownFiles) { if (file.Name == null) ownFiles.Remove(file); } return ownFiles; } public static bool ParentExist(string childfolder, List<string> folders) { foreach (string parentfolder in folders) { var parentUri = new Uri(parentfolder); var childUri = new DirectoryInfo(childfolder).Parent; while (childUri != null) { if (new Uri(childUri.FullName) == parentUri) { return true; } childUri = childUri.Parent; } } return false; } } }
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.Ports; using System.Windows.Forms.DataVisualization.Charting; using System.Timers; using System.IO; namespace BRI { public partial class MainForm : Form { public string data{ get; set; } int graph_scaler = 100; int send_repeat_counter = 0; bool send_data_flag = false; bool plotter_flag = false; System.IO.StreamWriter out_file; System.IO.StreamReader in_file; public MainForm() { InitializeComponent(); configrations(); } public void configrations() { portConfig.Items.AddRange(SerialPort.GetPortNames()); baudrateConfig.DataSource = new[] { "115200", "19200", "230400", "57600", "38400", "9600", "4800" }; parityConfig.DataSource = new[] { "None", "Odd", "Even", "Mark", "Space" }; databitsConfig.DataSource = new[] { "5", "6", "7", "8" }; stopbitsConfig.DataSource = new[] { "1", "2", "1.5" }; flowcontrolConfig.DataSource = new[] { "None", "RTS", "RTS/X", "Xon/Xoff" }; //portConfig.SelectedIndex = 0; baudrateConfig.SelectedIndex = 5; parityConfig.SelectedIndex = 0; databitsConfig.SelectedIndex = 3; stopbitsConfig.SelectedIndex = 0; flowcontrolConfig.SelectedIndex = 0; openFileDialog1.Filter = "Text|*.txt"; mySerial.DataReceived += rx_data_event; tx_repeater_delay.Tick += new EventHandler(send_data); backgroundWorker1.DoWork += new DoWorkEventHandler(update_rxtextarea_event); tabControl1.Selected += new TabControlEventHandler(tabControl1_Selecting); for (int i = 0; i < 2 && i < 2; i++) graph.Series[i].Points.Add(0); } /*connect and disconnect*/ private void connect_Click(object sender, EventArgs e) { /*Connect*/ if (!mySerial.IsOpen) { if (Serial_port_config()) { try { mySerial.Open(); } catch { alert("Can't open " + mySerial.PortName + " port, it might be used in another program"); return; } UserControl_state(true); } } /*Disconnect*/ else if (mySerial.IsOpen) { try { mySerial.Close(); mySerial.DiscardInBuffer(); mySerial.DiscardOutBuffer(); } catch {/*ignore*/} try {in_file.Dispose();} catch {/*ignore*/ } UserControl_state(false); } } /* RX -----*/ /* read data from serial */ private void rx_data_event(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { if (mySerial.IsOpen) { try { int dataLength = mySerial.BytesToRead; byte[] dataRecevied = new byte[dataLength]; int nbytes = mySerial.Read(dataRecevied, 0, dataLength); if (nbytes == 0) return; this.BeginInvoke((Action)(() => { data = System.Text.Encoding.Default.GetString(dataRecevied); if (!plotter_flag && !backgroundWorker1.IsBusy) { if (display_hex_radiobutton.Checked) data = BitConverter.ToString(dataRecevied); backgroundWorker1.RunWorkerAsync(); } else if (plotter_flag) { double number; string[] variables = data.Split('\n')[0].Split(','); for (int i = 0; i < variables.Length && i < 5; i++) { if (double.TryParse(variables[i], out number)) { if (graph.Series[i].Points.Count > graph_scaler) graph.Series[i].Points.RemoveAt(0); graph.Series[i].Points.Add(number); } } graph.ResetAutoValues(); } })); } catch { alert("Can't read form " + mySerial.PortName + " port it might be opennd in another program"); } } } /* Append text to rx_textarea*/ private void update_rxtextarea_event(object sender, DoWorkEventArgs e) { this.BeginInvoke((Action)(() => { if (rx_textarea.Lines.Count() > 5000) rx_textarea.ResetText(); rx_textarea.AppendText(data); double number; string[] variables = data.Split('\n')[0].Split(','); for (int i = 0; i < variables.Length && i < 5; i++) { if (double.TryParse(variables[i], out number)) { if (number < 170) led1.On = true; else led1.On = false; } } })); } /* Enable data logger and log file selection */ /* clear rx textarea */ private void clear_rx_textarea_Click(object sender, EventArgs e) { rx_textarea.Clear(); } /*TX------*/ /* Write data to serial port */ private void sendData_Click(object sender, EventArgs e) { if (!send_data_flag) { tx_repeater_delay.Interval = (int)send_delay.Value; tx_repeater_delay.Start(); if (send_word_radiobutton.Checked) { progressBar1.Maximum = (int)send_repeat.Value; progressBar1.Visible = true; } else if (write_form_file_radiobutton.Checked) { try { in_file = new System.IO.StreamReader(tx_textarea.Text, true); } catch { alert("Can't open " + tx_textarea.Text + " file, it might be not exist or it is used in another program"); return; } progressBar1.Maximum = file_size(tx_textarea.Text); progressBar1.Visible = true; } send_data_flag = true; tx_num_panel.Enabled = false; tx_textarea.Enabled = false; tx_radiobuttons_panel.Enabled = false; sendData.Text = "Stop"; } else { tx_repeater_delay.Stop(); progressBar1.Value = 0; send_repeat_counter = 0; send_data_flag = false; progressBar1.Visible = false; tx_num_panel.Enabled = true; tx_textarea.Enabled = true; tx_radiobuttons_panel.Enabled = true; sendData.Text = "Send"; if (write_form_file_radiobutton.Checked) try { in_file.Dispose(); } catch { } } } private void send_data(object sender, EventArgs e) { string tx_data = ""; if (send_word_radiobutton.Checked) { tx_data = tx_textarea.Text.Replace("\n", Environment.NewLine); if (send_repeat_counter < (int)send_repeat.Value) { send_repeat_counter++; progressBar1.Value = send_repeat_counter; progressBar1.Update(); } else send_data_flag = false; } else if (write_form_file_radiobutton.Checked) { try { tx_data = in_file.ReadLine(); } catch { } if (tx_data == null) send_data_flag = false; else { progressBar1.Value = send_repeat_counter; send_repeat_counter++; } tx_data += "\\n"; } if (send_data_flag) { if (mySerial.IsOpen) { try { mySerial.Write(tx_data.Replace("\\n", Environment.NewLine)); tx_terminal.AppendText("[TX]> " + tx_data+"\n"); } catch { alert("Can't write to " + mySerial.PortName + " port it might be opennd in another program"); } } } else { tx_repeater_delay.Stop(); sendData.Text = "Send"; send_repeat_counter = 0; progressBar1.Value = 0; progressBar1.Visible = false; tx_radiobuttons_panel.Enabled = true; tx_num_panel.Enabled = true; tx_textarea.Enabled = true; if (write_form_file_radiobutton.Checked) try { in_file.Dispose(); } catch { } } } /* write data when keydown*/ private void tx_textarea_KeyPress(object sender, KeyPressEventArgs e) { if (key_capture_radiobutton.Checked && mySerial.IsOpen) { try { mySerial.Write(e.KeyChar.ToString()); tx_terminal.AppendText("[TX]> " + e.KeyChar.ToString() + "\n"); tx_textarea.Clear(); } catch {alert("Can't write to "+mySerial.PortName+" port it might be opennd in another program"); } } } private void send_word_radiobutton_CheckedChanged(object sender, EventArgs e) { tx_textarea.Clear(); send_repeat.Enabled = send_word_radiobutton.Checked; send_delay.Enabled = send_word_radiobutton.Checked; this.ActiveControl = tx_textarea; } private void key_capture_radiobutton_CheckedChanged(object sender, EventArgs e) { tx_textarea.Clear(); send_repeat.Enabled = !key_capture_radiobutton.Checked; send_delay.Enabled = !key_capture_radiobutton.Checked; sendData.Enabled = !key_capture_radiobutton.Checked; this.ActiveControl = tx_textarea; } private void write_form_file_radiobutton_CheckedChanged(object sender, EventArgs e) { tx_textarea.Clear(); send_repeat.Enabled = !write_form_file_radiobutton.Checked; send_delay.Enabled = write_form_file_radiobutton.Checked; if (write_form_file_radiobutton.Checked) if (openFileDialog1.ShowDialog() == DialogResult.OK) { tx_textarea.Text = openFileDialog1.FileName; tx_textarea.Cursor = Cursors.Hand; tx_textarea.ReadOnly = true; } else { send_word_radiobutton.Checked = true; } else { tx_textarea.Cursor = Cursors.IBeam; tx_textarea.ReadOnly = false; } } /* Plotter ------*/ private void graph_speed_ValueChanged(object sender, EventArgs e) { graph.ChartAreas[0].AxisY.Interval = (int)graph_speed.Value; } /* change graph scale*/ private void graph_scale_ValueChanged(object sender, EventArgs e) { graph_scaler = (int)graph_scale.Value; for (int i = 0; i < 5; i++) graph.Series[i].Points.Clear(); } /* set graph max value*/ private void set_graph_max_enable_CheckedChanged(object sender, EventArgs e) { if (set_graph_max_enable.Checked) try { graph_max.Value = (int)graph.ChartAreas[0].AxisY.Maximum; graph.ChartAreas[0].AxisY.Maximum = (int)graph_max.Value; } catch {alert("Invalid Minimum value");} else graph.ChartAreas[0].AxisY.Maximum = Double.NaN; graph_max.Enabled = set_graph_max_enable.Checked; } private void graph_max_ValueChanged(object sender, EventArgs e) { if (graph_max.Value > graph_min.Value) graph.ChartAreas[0].AxisY.Maximum = (int)graph_max.Value; else alert("Invalid Maximum value"); } /* set graph min value*/ private void set_graph_min_enable_CheckedChanged(object sender, EventArgs e) { if (set_graph_min_enable.Checked) try { graph_min.Value = (int)graph.ChartAreas[0].AxisY.Minimum; graph.ChartAreas[0].AxisY.Minimum = (int)graph_min.Value; } catch { alert("Invalid Minimum value"); } else graph.ChartAreas[0].AxisY.Minimum = Double.NaN; graph_min.Enabled = set_graph_min_enable.Checked; } private void graph_min_ValueChanged(object sender, EventArgs e) { if (graph_min.Value < graph_max.Value) graph.ChartAreas[0].AxisY.Minimum = (int)graph_min.Value; else alert("Invalid Minimum value"); } /* save graph as image*/ private void saveAsImageToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) graph.SaveImage(saveFileDialog1.FileName, ChartImageFormat.Png); } /*clear graph*/ private void clear_graph_Click(object sender, EventArgs e) { for (int i = 0; i < 5; i++) graph.Series[i].Points.Clear(); } /*Application-----*/ /*serial port config*/ private bool Serial_port_config() { try {mySerial.PortName = portConfig.Text; } catch { alert("There are no available ports"); return false;} mySerial.BaudRate = (Int32.Parse(baudrateConfig.Text)); mySerial.StopBits = (StopBits)Enum.Parse(typeof(StopBits), (stopbitsConfig.SelectedIndex + 1).ToString(), true); mySerial.Parity = (Parity)Enum.Parse(typeof(Parity), parityConfig.SelectedIndex.ToString(), true); mySerial.DataBits = (Int32.Parse(databitsConfig.Text)); mySerial.Handshake = (Handshake)Enum.Parse(typeof(Handshake), flowcontrolConfig.SelectedIndex.ToString(), true); return true; } private void UserControl_state(bool value) { serial_options_group.Enabled = !value; write_options_group.Enabled = value; if (value) { connect.Text = "Disconnected"; toolStripStatusLabel1.Text = "Connected port: " + mySerial.PortName + " @ " + mySerial.BaudRate + " bps"; } else { connect.Text = "Connected"; toolStripStatusLabel1.Text = "No Connection"; } } /* tabcontrol*/ void tabControl1_Selecting(object sender, TabControlEventArgs e) { if (tabControl1.SelectedIndex == 2) plotter_flag = true; else plotter_flag = false; } /* Search for available serial ports */ private void portConfig_Click(object sender, EventArgs e) { portConfig.Items.Clear(); portConfig.Items.AddRange(SerialPort.GetPortNames()); } /*alert function*/ private void alert(string text) { alert_messege.Icon = Icon; alert_messege.Visible = true; alert_messege.ShowBalloonTip(5000, "Serial Lab", text, ToolTipIcon.Error); } /*about box*/ private void toolStripStatusLabel2_Click(object sender, EventArgs e) { AboutBox1 a = new AboutBox1(); a.ShowDialog(); } /* Close serial port when closing*/ private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (mySerial.IsOpen) mySerial.Close(); } private void tx_textarea_Click(object sender, EventArgs e) { if (write_form_file_radiobutton.Checked) write_form_file_radiobutton_CheckedChanged(sender, e); } /*get number of lines*/ private int file_size(string path) { var file = new StreamReader(path).ReadToEnd(); string [] lines = file.Split(new char[] { '\n' }); int count = lines.Count(); return count; } private void toolStripMenuItem1_Click(object sender, EventArgs e) { tx_terminal.Clear(); } private void MainForm_Load(object sender, EventArgs e) { } private void graph_Click(object sender, EventArgs e) { } private void tabPage1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void rx_textarea_TextChanged(object sender, EventArgs e) { } private void led1_StateChanged(object sender, EventArgs e) { } } }
/* The MIT License (MIT) * * Copyright (c) 2018 Marc Clifton * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* Code Project Open License (CPOL) 1.02 * https://www.codeproject.com/info/cpol10.aspx */ using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Clifton.Meaning; namespace MeaningExplorer { /// <summary> /// Simplified structure for creating a data dictionary used by Javascript /// to populate the value in the appropriate input control and set the /// instance ID path when a lookup is used. /// </summary> public class LookupItem { /// <summary> /// Will contain the value and instance path for the original full path context associated with the lookup. /// </summary> public List<Guid> OriginalContextInstancePath { get; protected set; } /// <summary> /// This is the new path for the input control which includes the parent hierarchy so we know /// for which input control the particular sub-context lookup item is associated. /// In other words, the field's ID. /// </summary> public List<Guid> NewContextInstancePath { get; protected set; } /// <summary> /// The value associated with each component of the lookup record. /// </summary> public string Value { get; protected set; } public int LookupId { get; protected set; } [JsonIgnore] public Type ContextType { get; protected set; } [JsonIgnore] public ContextValue ContextValue { get; protected set; } public LookupItem(ContextValue contextValue, Type contextType, int lookupId) { ContextValue = contextValue; ContextType = contextType; Value = contextValue.Value; LookupId = lookupId; // OriginalContextInstancePath = contextValue.InstancePath.ToList(); // Initialize for later completion. OriginalContextInstancePath = new List<Guid>(); NewContextInstancePath = new List<Guid>(); } } }
using SimulationDemo.Enums; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimulationDemo.Elements { public class CheckoutArea { private ConcurrentBag<CashierQueue> _cashierQueues; private List<SelfCheckoutQueue> _selfCheckoutQueues; private int _numMachine; private int _totalWaitingTime; private double _avgWaitingTime; private int _totalAngryLeaveCount; private int _totalArrivalCustomerCount; private int _totalDepartureCustomerCount; private int _totalChangeLineCount; private LinkedList<int> _last10waitingtime; public int NumMachine { get => _numMachine; } public CheckoutArea(int numCashier, int numSelfChechout, int numMachine) { _cashierQueues = new ConcurrentBag<CashierQueue>(); _selfCheckoutQueues = new List<SelfCheckoutQueue>(); _numMachine = numMachine; _last10waitingtime = new LinkedList<int>(); if (numCashier + numSelfChechout <= 0 && numCashier * numSelfChechout <= 0) { throw new Exception($"At least one line should be opened: numCashier = {numCashier}, numSelfCheckout = {numSelfChechout}"); } for (int i = 0; i < numCashier; i++) { _cashierQueues.Add(new CashierQueue()); } for (int i = 0; i < numSelfChechout; i++) { _selfCheckoutQueues.Add(new SelfCheckoutQueue(_numMachine)); } } public void AddOneNewCashier() { var closedQueue = _cashierQueues.FirstOrDefault(q => q.IsQueueOpened == false); if (closedQueue != null) { closedQueue.OpenQueue(); } else { _cashierQueues.Add(new CashierQueue()); } } public void CloseOneCashier() { _cashierQueues.FirstOrDefault(q => q.IsQueueOpened)?.CloseQueue(); } public IQueue QuickestQueue(Customer customer) { IQueue quickestCashier = null; foreach (var currentQ in _cashierQueues) { if (currentQ.IsQueueOpened) { if (quickestCashier == null || currentQ.IsQueueIdle() || (!currentQ.IsQueueIdle() && !quickestCashier.IsQueueIdle() && quickestCashier.NumOfWaitingCustomers() > currentQ.NumOfWaitingCustomers())) { quickestCashier = currentQ; } } } IQueue quickestSelfCheckout = null; foreach (var currentQ in _selfCheckoutQueues) { if (currentQ.IsQueueOpened) { if (quickestSelfCheckout == null || currentQ.IsQueueIdle() || (!currentQ.IsQueueIdle() && !quickestSelfCheckout.IsQueueIdle() && quickestSelfCheckout.NumOfWaitingCustomers() >= currentQ.NumOfWaitingCustomers())) { quickestSelfCheckout = currentQ; } } } // -- only the customers with small or medium amount of items are allowed to use self-checkout area if (customer.AmountItems == EventEnum.ScaningLargeAmountItems) { return quickestCashier; } if (quickestSelfCheckout.IsQueueIdle()) { return quickestSelfCheckout; } if (quickestCashier.IsQueueIdle()) { return quickestCashier; } return quickestCashier.NumOfWaitingCustomers() <= (quickestSelfCheckout.NumOfWaitingCustomers() / (_numMachine)) ? quickestCashier : quickestSelfCheckout; } public IEnumerable<IQueue> GetAllQueues() { List<IQueue> allQueues = new List<IQueue>(); allQueues.AddRange(_cashierQueues); allQueues.AddRange(_selfCheckoutQueues); return allQueues; } public IEnumerable<Customer> GetAllCustomers() { List<Customer> allCustomers = new List<Customer>(); foreach(IQueue queue in this.GetAllQueues()) { allCustomers.AddRange(queue.GetAllCustomers()); } return allCustomers; } public void UpdateStatisticsOnArrival(Customer customer) { _totalArrivalCustomerCount++; } public void UpdateStatisticsOnChangeLine(Customer customer) { _totalChangeLineCount++; } public void UpdateStatisticsOnDeparture(Customer customer) { _totalDepartureCustomerCount++; int newWaitingTime = 0; if (customer.StartCheckoutTime == 0) { _totalAngryLeaveCount++; newWaitingTime = (Simulation.GlobalTime - customer.ArrivalTime); } else { newWaitingTime = (customer.StartCheckoutTime - customer.ArrivalTime); } _totalWaitingTime += newWaitingTime; _last10waitingtime.AddLast(newWaitingTime); if(_last10waitingtime.Count > 10) { _last10waitingtime.RemoveFirst(); } _avgWaitingTime = _totalWaitingTime / _totalDepartureCustomerCount; } public void PrintOut() { Console.WriteLine(); Console.WriteLine("-------------------------------Statistics---------------------------------------------------"); Console.WriteLine($"Total Arrival: {_totalArrivalCustomerCount}"); Console.WriteLine($"Total Departure: {_totalDepartureCustomerCount}"); Console.WriteLine($"Total Remainint Customers: {_totalArrivalCustomerCount - _totalDepartureCustomerCount}"); Console.WriteLine($"Total Angry Departure: {_totalAngryLeaveCount}"); Console.WriteLine($"Avg. Waiting Time: {_avgWaitingTime}"); Console.WriteLine($"Total Change Line Counts: {_totalChangeLineCount}"); StringBuilder sb = new StringBuilder(); foreach(int n in _last10waitingtime) { sb.Append($"{n}, "); } Console.WriteLine($"Waiting Time of Lastest {_last10waitingtime.Count} Customers: [{(_last10waitingtime.Count == 0 ? "" : sb.ToString())}]"); Console.WriteLine(); Console.WriteLine("-------------------------------Checkout Area------------------------------------------------"); foreach (var q in _cashierQueues) { q.PrintOut(); } foreach(var q in _selfCheckoutQueues) { q.PrintOut(); } } } }
using System; using Xamarin.Forms; using System.Threading.Tasks; namespace PGATourLeaderboard { public class TournamentScoresPage : ContentPage { public TournamentScoresPage (Tournament tournament) { this.Title = "Loaderboard"; var loader = new ActivityIndicator { HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, Color = Color.FromRgb(0, 61, 125), IsRunning = true, }; this.Content = loader; GetScores (tournament.Id); } private async Task GetScores(string tournamentId) { var listView = new ListView { ItemsSource = await new PlayerManager(tournamentId).GetPlayerScores() }; var cell = new DataTemplate (typeof(TextCell)); cell.SetBinding (TextCell.TextProperty, "FullName"); cell.SetBinding (TextCell.DetailProperty, "ScoreDisplay"); listView.ItemTemplate = cell; this.Content = listView; } } }
namespace FailureSimulator.Core.Graph { /// <summary> /// Ребро /// </summary> public class Edge : IGraphUnit { public string Name => $"{VertexFrom} <-> {VertexTo.Name}"; /// <summary> /// Интенсивность отказов всей связи /// </summary> public double FailIntensity { get; set; } /// <summary> /// Интенсивность восстановления /// </summary> public double RepairIntensity { get; set; } /// <summary> /// Вершина, в которую направлено ребро /// </summary> public Vertex VertexTo { get; private set; } /// <summary> /// Вершина, из которой направлено ребро /// </summary> public Vertex VertexFrom { get; private set; } public Edge(Vertex from, Vertex to, double failIntensity = 0) { VertexFrom = from; VertexTo = to; FailIntensity = failIntensity; } public override string ToString() => Name; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace GodMorgon.Models { /** * Classe mère des types de carte (attack, defense, move, ...) * Elle contient des variables communes à chaque type de carte * Elle permet que toutes les classes filles soient de scriptable object */ [CreateAssetMenu(fileName = "New Card", menuName = "Cards/BasicCard")] public class BasicCard : ScriptableObject { public enum CARDTYPE { MOVE, ATTACK, DEFENSE, POWER_UP, SPELL, SIGHT, CURSE, } public CARDTYPE cardType = CARDTYPE.MOVE; public int id; public new string name; [TextArea] public string description; public int actionCost = 1; public int price = 0; public Sprite template; public Sprite artwork; public CardEffectData[] effectsData; #region GET_DATA //retourne les dégats de base de la carte public int GetRealDamage() { int damageData = 0; foreach (CardEffectData effect in effectsData) { damageData += effect.damagePoint; //check pour les autres effets if (effect.shiver) damageData = damageData * 2; else if (effect.trust && BuffManager.Instance.IsTrustValidate(effect.trustNb)) damageData = damageData * 2; } return damageData; } //retourne les blocks de base de la carte public int GetRealBlock() { int blockData = 0; foreach (CardEffectData effect in effectsData) { blockData += effect.nbBlock; if (effect.shiver) blockData = blockData * 2; else if (effect.trust && BuffManager.Instance.IsTrustValidate(effect.trustNb)) blockData = blockData * 2; } return blockData; } //retourne les mouvements de base de la carte public int GetRealMove() { int moveData = 0; foreach (CardEffectData effect in effectsData) { moveData += effect.nbMoves; if (effect.shiver) moveData = moveData * 2; else if (effect.trust && BuffManager.Instance.IsTrustValidate(effect.trustNb)) moveData = moveData * 2; } return moveData; } //retourne le heal de base de la carte public int GetRealHeal() { int healData = 0; foreach (CardEffectData effect in effectsData) { healData += effect.nbHeal; if (effect.shiver) healData = healData * 2; else if (effect.trust && BuffManager.Instance.IsTrustValidate(effect.trustNb)) healData = healData * 2; } return healData; } //retourne le nombre de carte à piocher de base de la carte public int GetRealNbDraw() { int nbDrawData = 0; foreach (CardEffectData effect in effectsData) { nbDrawData += effect.nbCardToDraw; if (effect.shiver) nbDrawData = nbDrawData * 2; else if (effect.trust && BuffManager.Instance.IsTrustValidate(effect.trustNb)) nbDrawData = nbDrawData * 2; } return nbDrawData; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio5 { class Cambios { static void Main(string[] args) { { Console.Write("Digite a quantia em dólares americanos "); double Usd = Convert.ToDouble(Console.ReadLine()); Console.Write("Digite a taxa de câmbio: número de euros" + " por um dólar americano "); double Taxa = Convert.ToDouble(Console.ReadLine()); double Eur = Usd * Taxa; Console.WriteLine("{0} dólares americanos equivalem a {1}" + " euros", Usd, Eur); } } } }
using System; using System.Drawing; using MonoTouch.ObjCRuntime; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Microsoft.WindowsAzure.Messaging { /*@interface SBNotificationHub : NSObject - (void) unregisterAllWithDeviceToken:(NSData*)deviceToken completion:(void (^)(NSError* error))completion; // sync operations - (BOOL) registerNativeWithDeviceToken:(NSData*)deviceToken tags:(NSSet*)tags error:(NSError**)error; - (BOOL) registerTemplateWithDeviceToken:(NSData*)deviceToken name:(NSString*)templateName jsonBodyTemplate:(NSString*)bodyTemplate expiryTemplate:(NSString*)expiryTemplate tags:(NSSet*)tags error:(NSError**)error; - (BOOL) unregisterNativeWithError:(NSError**)error; - (BOOL) unregisterTemplateWithName:(NSString*)name error:(NSError**)error; - (BOOL) unregisterAllWithDeviceToken:(NSData*)deviceToken error:(NSError**)error;*/ public delegate void SBNotificationHubHandler(NSError error); [BaseType(typeof(NSObject))] public interface SBNotificationHub { [Static, Export("version")] string Version { get; } [Export("initWithConnectionString:notificationHubPath:")] IntPtr Constructor(string connectionString, string notificationHubPath); [Export("registerNativeWithDeviceToken:tags:completion:")] void Register(NSData deviceToken, NSSet tags, SBNotificationHubHandler completion); [Export("unregisterNativeWithCompletion:")] void Unregister(SBNotificationHubHandler completion); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using CreamBell_DMS_WebApps.App_Code; using System.IO; using System.Drawing; using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html; using iTextSharp.text.html.simpleparser; using Elmah; namespace CreamBell_DMS_WebApps { public partial class frmVRSTransactionDetails : System.Web.UI.Page { CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); protected void Page_Load(object sender, EventArgs e) { if (Session["USERID"] == null) { Response.Redirect("Login.aspx"); return; } //if (Convert.ToString(Session["LOGINTYPE"]) == "3") { // phState.Visible = false; //} if (!IsPostBack) { obj.FillSaleHierarchy(); BindFilters(); //ShowDetails(); //fillSiteAndState(); txtFromDate.Text = string.Format("{0:dd/MMM/yyyy }", DateTime.Today);// DateTime.Today.ToString(); txtToDate.Text = string.Format("{0:dd/MMM/yyyy }", DateTime.Today);// DateTime.Today.ToString(); fillHOS(); if (Convert.ToString(Session["LOGINTYPE"]) == "3") { //DataView DtSaleHierarchy = (DataTable)HttpContext.Current.Session["SaleHierarchy"]; DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); if (dt.Rows.Count > 0) { var dr_row = dt.AsEnumerable(); var test = (from r in dr_row select r.Field<string>("SALEPOSITION")).First<string>(); //string dr1 = dt.Select("SALEPOSITION").ToString(); if (test == "VP") { chkListHOS.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; //chkAll_CheckedChanged(null, null); } else if (test == "GM") { chkListHOS.Enabled = false; chkListVP.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; CheckBox1.Enabled = false; CheckBox1.Checked = true; //chkAll_CheckedChanged(null, null); } else if (test == "DGM") { chkListHOS.Enabled = false; chkListVP.Enabled = false; chkListGM.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; CheckBox1.Enabled = false; CheckBox1.Checked = true; CheckBox2.Enabled = false; CheckBox2.Checked = true; //chkAll_CheckedChanged(null, null); } else if (test == "RM") { chkListHOS.Enabled = false; chkListVP.Enabled = false; chkListGM.Enabled = false; chkListDGM.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; CheckBox1.Enabled = false; CheckBox1.Checked = true; CheckBox2.Enabled = false; CheckBox2.Checked = true; CheckBox3.Enabled = false; CheckBox3.Checked = true; //chkAll_CheckedChanged(null, null); } else if (test == "ZM") { chkListHOS.Enabled = false; chkListVP.Enabled = false; chkListGM.Enabled = false; chkListDGM.Enabled = false; chkListRM.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; CheckBox1.Enabled = false; CheckBox1.Checked = true; CheckBox2.Enabled = false; CheckBox2.Checked = true; CheckBox3.Enabled = false; CheckBox3.Checked = true; CheckBox4.Enabled = false; CheckBox4.Checked = true; //chkAll_CheckedChanged(null, null); } else if (test == "ASM") { chkListHOS.Enabled = false; chkListVP.Enabled = false; chkListGM.Enabled = false; chkListDGM.Enabled = false; chkListRM.Enabled = false; chkListZM.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; CheckBox1.Enabled = false; CheckBox1.Checked = true; CheckBox2.Enabled = false; CheckBox2.Checked = true; CheckBox3.Enabled = false; CheckBox3.Checked = true; CheckBox4.Enabled = false; CheckBox4.Checked = true; CheckBox5.Enabled = false; CheckBox5.Checked = true; //chkAll_CheckedChanged(null, null); } else if (test == "EXECUTIVE") { chkListHOS.Enabled = false; chkListVP.Enabled = false; chkListGM.Enabled = false; chkListDGM.Enabled = false; chkListRM.Enabled = false; chkListZM.Enabled = false; chkListEXECUTIVE.Enabled = false; chkAll.Enabled = false; chkAll.Checked = true; CheckBox1.Enabled = false; CheckBox1.Checked = true; CheckBox2.Enabled = false; CheckBox2.Checked = true; CheckBox3.Enabled = false; CheckBox3.Checked = true; CheckBox4.Enabled = false; CheckBox4.Checked = true; CheckBox5.Enabled = false; CheckBox5.Checked = true; CheckBox6.Enabled = false; CheckBox6.Checked = true; //chkAll_CheckedChanged(null, null); } ddlCountry_SelectedIndexChanged(null, null); } } if (Convert.ToString(Session["LOGINTYPE"]) == "3") { //tclabel.Width = "90%"; Panel1.Visible = true; } else { //tclabel.Width = "100%"; Panel1.Visible = false; } if (Convert.ToString(Session["LOGINTYPE"]) == "0" && Convert.ToString(Session["ISDISTRIBUTOR"]) == "Y") { // ShowReportSummary(); // bind(); } } } private void BindFilters() { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); string queryProductGroup = "Select distinct replace(replace(PRODUCT_SUBCATEGORY, char(9), ''), char(13) + char(10), '') as SUBCATEGORY from ax.INVENTTABLE"; DDLSubCategoryNew.Items.Clear(); DDLSubCategoryNew.Items.Add("-Select-"); obj.BindToDropDownp(DDLSubCategoryNew, queryProductGroup, "SUBCATEGORY", "SUBCATEGORY"); } //private void ShowDetails() //{ // CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global(); // string query = "ACX_USP_VRSTransactionDetails"; // List<string> ilist = new List<string>(); // List<string> item = new List<string>(); // DataTable dt = new DataTable(); // ilist.Add("@Site_Code"); item.Add(ucRoleFilters.GetCommaSepartedSiteId()); // ilist.Add("@DATAAREAID"); item.Add(Session["DATAAREAID"].ToString()); // ilist.Add("@StartDate"); item.Add(txtFromDate.Text); // ilist.Add("@EndDate"); item.Add(txtToDate.Text); // ilist.Add("@StateCode"); item.Add(""); // ilist.Add("@VRSCode"); item.Add(""); // ilist.Add("@subcategory"); item.Add(""); // dt = obj.GetData_New(query, CommandType.StoredProcedure, ilist, item); // if (dt.Rows.Count > 0) // { // gridVRSDetails.DataSource = dt; // gridVRSDetails.DataBind(); // LblMessage.Text = "Total Records : " + dt.Rows.Count.ToString(); // Session["SaleRegister"] = dt; // } // else // { // LblMessage.Text = string.Empty; // } //} protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { string statesel = ""; foreach (System.Web.UI.WebControls.ListItem litem1 in lstState.Items) { if (litem1.Selected) { if (statesel.Length == 0) statesel = "'" + litem1.Value.ToString() + "'"; else statesel += ",'" + litem1.Value.ToString() + "'"; } } if (lstState.SelectedValue == string.Empty) { lstSiteId.Items.Clear(); DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); DataView view = new DataView(dt); DataTable distinctValues = view.ToTable(true, "Distributor", "DistributorName"); lstSiteId.DataSource = distinctValues; string AllSitesFromHierarchy = ""; foreach (DataRow row in distinctValues.Rows) { if (AllSitesFromHierarchy == "") { AllSitesFromHierarchy += "'" + row["Distributor"].ToString() + "'"; } else { AllSitesFromHierarchy += ",'" + row["Distributor"].ToString() + "'"; } } if (AllSitesFromHierarchy != "") { string sqlstr1 = @"Select Distinct SITEID as Code,SITEID +' - '+ Name AS Name,Name as SiteName from [ax].[INVENTSITE] IV LEFT JOIN AX.ACXUSERMASTER UM on IV.SITEID = UM.SITE_CODE where SITEID IN (" + AllSitesFromHierarchy + ") Order by SiteName "; dt = obj.GetData(sqlstr1); lstSiteId.DataSource = dt; lstSiteId.DataTextField = "Name"; lstSiteId.DataValueField = "Code"; lstSiteId.DataBind(); } } else { string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'"; object objcheckSitecode = obj.GetScalarValue(sqlstr); if (objcheckSitecode != null) { lstSiteId.Items.Clear(); string sqlstr1 = @"Select Distinct SITEID as Code,SITEID + ' - ' + NAME AS NAME,Name as SiteName from [ax].[INVENTSITE] IV JOIN AX.ACXUSERMASTER UM on IV.SITEID=UM.SITE_CODE where STATECODE in (" + statesel + ") Order by SiteName"; DataTable dt = obj.GetData(sqlstr1); lstSiteId.DataSource = dt; lstSiteId.DataTextField = "Name"; lstSiteId.DataValueField = "Code"; lstSiteId.DataBind(); } else { lstSiteId.Items.Clear(); if (Convert.ToString(Session["LOGINTYPE"]) == "3") { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); dt.DefaultView.RowFilter = "STATE in (" + statesel + ")"; DataTable uniqueCols = dt.DefaultView.ToTable(true, "Distributor", "DistributorName"); string AllSitesFromHierarchy = ""; foreach (DataRow row in uniqueCols.Rows) { if (AllSitesFromHierarchy == "") { AllSitesFromHierarchy += "'" + row["Distributor"].ToString() + "'"; } else { AllSitesFromHierarchy += ",'" + row["Distributor"].ToString() + "'"; } } string sqlstr1 = @"Select Distinct SITEID as Code,SITEID +' - '+ Name AS Name,Name as SiteName from [ax].[INVENTSITE] IV LEFT JOIN AX.ACXUSERMASTER UM on IV.SITEID = UM.SITE_CODE where SITEID IN (" + AllSitesFromHierarchy + ") Order by SiteName "; dt = obj.GetData(sqlstr1); lstSiteId.DataSource = dt; lstSiteId.DataTextField = "Name"; lstSiteId.DataValueField = "Code"; lstSiteId.DataBind(); } else { string sqlstr1 = @"Select Distinct SITEID as Code,SITEID + ' - ' + NAME AS NAME from [ax].[INVENTSITE] IV JOIN AX.ACXUSERMASTER UM on IV.SITEID=UM.SITE_CODE where SITEID = '" + Session["SiteCode"].ToString() + "'"; DataTable dt = obj.GetData(sqlstr1); lstSiteId.DataSource = dt; lstSiteId.DataTextField = "Name"; lstSiteId.DataValueField = "Code"; lstSiteId.DataBind(); } } } if (lstSiteId.Items.Count == 1) { foreach (System.Web.UI.WebControls.ListItem litem in lstSiteId.Items) { litem.Selected = true; } } ddlSiteId_SelectedIndexChanged(null, null); Session["SalesData"] = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); } protected void fillSiteAndState(DataTable dt) { string sqlstr = ""; if (Convert.ToString(Session["ISDISTRIBUTOR"]) == "Y") { if (Convert.ToString(Session["LOGINTYPE"]) == "3") { DataTable dtState = dt.DefaultView.ToTable(true, "STATE", "STATENAME"); dtState.Columns.Add("STATENAMES", typeof(string), "STATE + ' - ' + STATENAME"); lstState.Items.Clear(); DataRow dr = dtState.NewRow(); lstState.DataSource = dtState; lstState.DataTextField = "STATENAMES"; lstState.DataValueField = "STATE"; lstState.DataBind(); } else { sqlstr = "Select Distinct I.StateCode Code,I.StateCode + ' - ' + LS.Name AS Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' AND I.SITEID='" + Convert.ToString(Session["SiteCode"]) + "' order by Name"; DataTable dt1 = obj.GetData(sqlstr); lstState.DataSource = dt1; lstState.DataTextField = "Name"; lstState.DataValueField = "Code"; lstState.DataBind(); } } else { sqlstr = "Select Distinct I.StateCode Code,I.StateCode + ' - ' + LS.Name AS Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' order by Name "; lstState.Items.Add("Select..."); // baseObj.BindToDropDown(ddlState, sqlstr, "Name", "Code"); DataTable dt1 = obj.GetData(sqlstr); lstState.DataSource = dt1; lstState.DataTextField = "Name"; lstState.DataValueField = "Code"; lstState.DataBind(); } if (lstState.Items.Count == 1) { foreach (System.Web.UI.WebControls.ListItem litem in lstState.Items) { litem.Selected = true; } } // fillbu(); } protected void fillHOS() { chkListHOS.Items.Clear(); DataTable dtHOS = (DataTable)Session["SaleHierarchy"]; DataTable uniqueCols = dtHOS.DefaultView.ToTable(true, "HOSNAME", "HOSCODE"); chkListHOS.DataSource = uniqueCols; chkListHOS.DataTextField = "HOSNAME"; chkListHOS.DataValueField = "HOSCODE"; chkListHOS.DataBind(); if (uniqueCols.Rows.Count == 1) { chkListHOS.Items[0].Selected = true; lstHOS_SelectedIndexChanged(null, null); } fillSiteAndState(dtHOS); } protected void lstHOS_SelectedIndexChanged(object sender, EventArgs e) { chkListVP.Items.Clear(); chkListGM.Items.Clear(); chkListDGM.Items.Clear(); chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListHOS)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); //chkListVP.Items.Clear(); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "VPNAME", "VPCODE"); chkListVP.DataSource = uniqueCols2; chkListVP.DataTextField = "VPNAME"; chkListVP.DataValueField = "VPCODE"; chkListVP.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListVP.Items[0].Selected = true; lstVP_SelectedIndexChanged(null, null); } else { chkListVP.Items[0].Selected = false; } fillSiteAndState(dt); uppanel.Update(); //chkListGM.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void lstVP_SelectedIndexChanged(object sender, EventArgs e) { chkListGM.Items.Clear(); chkListDGM.Items.Clear(); chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListVP)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "GMNAME", "GMCODE"); chkListGM.DataSource = uniqueCols2; chkListGM.DataTextField = "GMNAME"; chkListGM.DataValueField = "GMCODE"; chkListGM.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListGM.Items[0].Selected = true; lstGM_SelectedIndexChanged(null, null); } else { chkListGM.Items[0].Selected = false; } fillSiteAndState(dt); uppanel.Update(); } ddlCountry_SelectedIndexChanged(null, null); } protected void lstGM_SelectedIndexChanged(object sender, EventArgs e) { chkListDGM.Items.Clear(); chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListGM)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "DGMNAME", "DGMCODE"); chkListDGM.DataSource = uniqueCols2; chkListDGM.DataTextField = "DGMNAME"; chkListDGM.DataValueField = "DGMCODE"; chkListDGM.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListDGM.Items[0].Selected = true; lstDGM_SelectedIndexChanged(null, null); } else { chkListDGM.Items[0].Selected = false; } fillSiteAndState(dt); uppanel.Update(); } ddlCountry_SelectedIndexChanged(null, null); } protected void lstDGM_SelectedIndexChanged(object sender, EventArgs e) { chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListDGM)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "RMNAME", "RMCODE"); chkListRM.DataSource = uniqueCols2; chkListRM.DataTextField = "RMNAME"; chkListRM.DataValueField = "RMCODE"; chkListRM.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListRM.Items[0].Selected = true; lstRM_SelectedIndexChanged(null, null); } else { chkListRM.Items[0].Selected = false; } fillSiteAndState(dt); uppanel.Update(); } ddlCountry_SelectedIndexChanged(null, null); //upsale.Update() } public Boolean CheckSelect(ref CheckBoxList ChkList) { foreach (System.Web.UI.WebControls.ListItem litem in ChkList.Items) { if (litem.Selected) { return true; } } return false; } protected void lstRM_SelectedIndexChanged(object sender, EventArgs e) { chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListRM)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "ZMNAME", "ZMCODE"); chkListZM.DataSource = uniqueCols2; chkListZM.DataTextField = "ZMNAME"; chkListZM.DataValueField = "ZMCODE"; chkListZM.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListZM.Items[0].Selected = true; lstZM_SelectedIndexChanged(null, null); } else { } fillSiteAndState(dt); uppanel.Update(); } ddlCountry_SelectedIndexChanged(null, null); } protected void lstZM_SelectedIndexChanged(object sender, EventArgs e) { chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListZM)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); chkListASM.Items.Clear(); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "ASMNAME", "ASMCODE"); chkListASM.DataSource = uniqueCols2; chkListASM.DataTextField = "ASMNAME"; chkListASM.DataValueField = "ASMCODE"; chkListASM.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListASM.Items[0].Selected = true; lstASM_SelectedIndexChanged(null, null); } fillSiteAndState(dt); uppanel.Update(); } ddlCountry_SelectedIndexChanged(null, null); } protected void lstASM_SelectedIndexChanged(object sender, EventArgs e) { //chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); if (CheckSelect(ref chkListASM)) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); chkListEXECUTIVE.Items.Clear(); DataTable uniqueCols2 = dt.DefaultView.ToTable(true, "EXECUTIVENAME", "EXECUTIVECODE"); chkListEXECUTIVE.DataSource = uniqueCols2; chkListEXECUTIVE.DataTextField = "EXECUTIVENAME"; chkListEXECUTIVE.DataValueField = "EXECUTIVECODE"; chkListEXECUTIVE.DataBind(); if (uniqueCols2.Rows.Count == 1) { chkListEXECUTIVE.Items[0].Selected = true; } fillSiteAndState(dt); uppanel.Update(); } ddlCountry_SelectedIndexChanged(null, null); } protected void lstEXECUTIVE_SelectedIndexChanged(object sender, EventArgs e) { DataTable dt = App_Code.Global.HierarchyDataTable(ref chkListHOS, ref chkListVP, ref chkListGM, ref chkListDGM, ref chkListRM, ref chkListZM, ref chkListASM, ref chkListEXECUTIVE); fillSiteAndState(dt); uppanel.Update(); ddlCountry_SelectedIndexChanged(null, null); } protected void chkAll_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(chkAll, chkListHOS); lstHOS_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(chkAll, chkListHOS); chkListVP.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox1_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(CheckBox1, chkListVP); lstVP_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(CheckBox1, chkListVP); // chkListVP.Items.Clear(); chkListGM.Items.Clear(); //chkListRM.Items.Clear(); //chkListZM.Items.Clear(); //chkListASM.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox2_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(CheckBox2, chkListGM); lstGM_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(CheckBox2, chkListGM); // chkListGM.Items.Clear(); chkListDGM.Items.Clear(); chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox3_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(CheckBox3, chkListDGM); lstDGM_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(CheckBox3, chkListDGM); //chkListGM.Items.Clear(); //chkListDGM.Items.Clear(); chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox4_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(CheckBox4, chkListRM); lstRM_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(CheckBox4, chkListRM); //chkListGM.Items.Clear(); // chkListDGM.Items.Clear(); //chkListRM.Items.Clear(); chkListZM.Items.Clear(); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox5_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(CheckBox5, chkListZM); //chkListASM.Items.Clear(); lstZM_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(CheckBox5, chkListZM); chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox6_CheckedChanged(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; if (chk.Checked) { CheckAll_CheckedChanged(CheckBox6, chkListASM); //chkListASM.Items.Clear(); lstASM_SelectedIndexChanged(null, null); } else { CheckAll_CheckedChanged(CheckBox6, chkListASM); //chkListASM.Items.Clear(); chkListEXECUTIVE.Items.Clear(); } ddlCountry_SelectedIndexChanged(null, null); } protected void CheckBox7_CheckedChanged(object sender, EventArgs e) { CheckAll_CheckedChanged(CheckBox7, chkListEXECUTIVE); ddlCountry_SelectedIndexChanged(null, null); //chkListASM.DataSource = null; } protected void CheckAll_CheckedChanged(CheckBox CheckAll, CheckBoxList ChkList) { if (CheckAll.Checked == true) { for (int i = 0; i < ChkList.Items.Count; i++) { ChkList.Items[i].Selected = true; } } else { for (int i = 0; i < ChkList.Items.Count; i++) { ChkList.Items[i].Selected = false; } } } protected void BtnSearch_Click(object sender, EventArgs e) { bool b = ValidateSearch(); if (b == true) { CreamBell_DMS_WebApps.App_Code.Global obj = new Global(); try { string FromDate = txtFromDate.Text; string ToDate = txtToDate.Text; string State = string.Empty; string Siteid = string.Empty; string VRSId = string.Empty; string ProdSubCategory = string.Empty; string query = "ACX_USP_VRSTransactionDetails"; List<string> ilist = new List<string>(); List<string> item = new List<string>(); DataTable dt = new DataTable(); //if (Convert.ToString(Session["LOGINTYPE"]) == "3") //{ // State = ucRoleFilters.GetCommaSepartedStateId(); // Siteid = ucRoleFilters.GetCommaSepartedSiteId(); //} //else { // if (ddlState.SelectedIndex > 0) // { // State = ddlState.SelectedValue; // } // else // { // State = ""; // } // if (ddlSiteId.SelectedIndex > 0) // { // Siteid = ddlSiteId.SelectedValue; // } // else // { // Siteid = ""; // } //} foreach (System.Web.UI.WebControls.ListItem itemnew in lstState.Items) { if (itemnew.Value != "") { if (State.Length > 0) State += ",'" + itemnew.Value + "'"; else State += "'" + itemnew.Value + "'"; } } foreach (System.Web.UI.WebControls.ListItem itemnew in lstSiteId.Items) { if (itemnew.Value != "") { if (Siteid.Length > 0) Siteid += ",'" + itemnew.Value + "'"; else Siteid += "'" + itemnew.Value + "'"; } } if (ddlVRSNew.SelectedIndex >= 0) { VRSId = ddlVRSNew.SelectedValue; } else { VRSId = ""; } if (DDLSubCategoryNew.SelectedIndex > 0) { ProdSubCategory = DDLSubCategoryNew.SelectedValue.ToString(); } else { ProdSubCategory = ""; } string dataareaid = Session["DATAAREAID"].ToString(); ilist.Add("@StateCode"); item.Add(State); ilist.Add("@Site_Code"); item.Add(Siteid); ilist.Add("@VRSCode"); item.Add(VRSId); //ilist.Add("@Site_Code"); item.Add(Session["SiteCode"].ToString()); ilist.Add("@DATAAREAID"); item.Add(Session["DATAAREAID"].ToString()); ilist.Add("@StartDate"); item.Add(txtFromDate.Text); ilist.Add("@EndDate"); item.Add(txtToDate.Text); ilist.Add("@subcategory"); item.Add(ProdSubCategory); dt = obj.GetData_New(query, CommandType.StoredProcedure, ilist, item); if (dt.Rows.Count > 0) { gridVRSDetails.DataSource = dt; gridVRSDetails.DataBind(); LblMessage.Text = "Total Records : " + dt.Rows.Count.ToString(); Session["SaleRegister"] = dt; } else { LblMessage.Text = string.Empty; gridVRSDetails.DataSource = dt; gridVRSDetails.DataBind(); // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('No Data Exits Between This Date Range !');", true); LblMessage.Text = "No Data Exits Between This Date Range !"; LblMessage.Visible = true; uppanel.Update(); } } catch (Exception ex) { LblMessage.Text = ex.Message.ToString(); ErrorSignal.FromCurrentContext().Raise(ex); } } } private bool ValidateSearch() { bool value = false; if (txtFromDate.Text == string.Empty && txtToDate.Text == string.Empty) { value = false; //this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide The Date Range Parameter !');", true); LblMessage.Text = "Please Provide The Date Range Parameter !"; LblMessage.Visible = true; uppanel.Update(); } if (txtFromDate.Text != string.Empty && txtToDate.Text == string.Empty) { value = false; // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide The TO Date Range Parameter !');", true); LblMessage.Text = "Please Provide The TO Date Range Parameter !"; LblMessage.Visible = true; uppanel.Update(); } if (txtFromDate.Text == string.Empty && txtToDate.Text != string.Empty) { value = false; // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide The FROM Date Range Parameter !');", true); LblMessage.Text = "Please Provide The FROM Date Range Parameter !"; LblMessage.Visible = true; uppanel.Update(); } if (txtFromDate.Text != string.Empty && txtToDate.Text != string.Empty) { value = true; } return value; } public override void VerifyRenderingInServerForm(Control control) { /* Verifies that the control is rendered */ } protected void imgBtnExportToExcel_Click(object sender, ImageClickEventArgs e) { if (gridVRSDetails.Rows.Count > 0) { //ExportToExcel(); ExportToExcelNew(); } else { // this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Cannot Export Data due to No Records available. !');", true); LblMessage.Text = "Cannot Export Data due to No Records available. !"; LblMessage.Visible = true; uppanel.Update(); } } private void ExportToExcelNew() { Response.Clear(); Response.Buffer = true; Response.ClearContent(); Response.ClearHeaders(); Response.Charset = ""; string FileName = "VRSTransactionDetails" + DateTime.Now + ".xls"; StringWriter strwritter = new StringWriter(); HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName); gridVRSDetails.GridLines = GridLines.Both; gridVRSDetails.HeaderStyle.Font.Bold = true; gridVRSDetails.RenderControl(htmltextwrtter); { Response.Write("<table><tr><td><b>From Date: " + txtFromDate.Text + "</b></td><td></td> <td><b>To Date: " + txtToDate.Text + "</b></td></tr></table>"); } Response.Write(strwritter.ToString()); Response.End(); } protected void VRSDetail() { string SiteList = ""; //if (Convert.ToString(Session["LOGINTYPE"]) == "3") //{ // SiteList = ucRoleFilters.GetCommaSepartedSiteId(); //} //else { // if (ddlSiteId.SelectedIndex == 0) // { foreach (System.Web.UI.WebControls.ListItem item in lstSiteId.Items) { if (item.Value != "") { if (SiteList.Length > 0) SiteList += ",'" + item.Value + "'"; else SiteList += "'" + item.Value + "'"; } } //} //else //{ // SiteList = "'" + ddlSiteId.SelectedValue.ToString() + "'"; //} // } if (SiteList.Length > 0) { DataTable dt = new DataTable(); string sqlstr1 = string.Empty; string sqlstr = @"SELECT DISTINCT ax.ACXCUSTMASTER.CUSTOMER_CODE , ax.ACXCUSTMASTER.CUSTOMER_NAME FROM ax.INVENTSITE INNER JOIN ax.ACXCUSTMASTER ON ax.INVENTSITE.SITEID = ax.ACXCUSTMASTER.SITE_CODE INNER JOIN ax.ACXCUSTGROUPMASTER ON ax.ACXCUSTMASTER.CUST_GROUP = ax.ACXCUSTGROUPMASTER.CUSTGROUP_CODE where ax.INVENTSITE.STATECODE <>'' and [ax].[ACXCUSTMASTER].CUst_Group='CG0002' and ax.INVENTSITE.SITEID in (" + SiteList + ") "; dt = obj.GetData(sqlstr); ddlVRSNew.Items.Clear(); DataRow dr = dt.NewRow(); dr[0] = ""; dr[1] = "--Select--"; dt.Rows.InsertAt(dr, 0); ddlVRSNew.DataSource = dt; ddlVRSNew.DataTextField = "CUSTOMER_NAME"; ddlVRSNew.DataValueField = "CUSTOMER_CODE"; ddlVRSNew.DataBind(); //ddlVRS.Items.Insert(0, new ListItem("--Select--", "")); } else { ddlVRSNew.Items.Clear(); } } //protected void fillSiteAndState() //{ // string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'"; // object objcheckSitecode = obj.GetScalarValue(sqlstr); // if (objcheckSitecode != null) // { // ddlState.Items.Clear(); // string sqlstr11 = "Select Distinct I.StateCode Code,LS.Name from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.STATECODE <>'' ORDER BY LS.Name "; // ddlState.Items.Add("Select..."); // obj.BindToDropDown(ddlState, sqlstr11, "Name", "Code"); // } // else // { // ddlState.Items.Clear(); // ddlSiteId.Items.Clear(); // string sqlstr1 = @"Select I.StateCode StateCode,LS.Name as StateName,I.SiteId,I.Name as SiteName from [ax].[INVENTSITE] I left join [ax].[LOGISTICSADDRESSSTATE] LS on LS.STATEID = I.STATECODE where I.SiteId = '" + Session["SiteCode"].ToString() + "' ORDER BY LS.Name"; // obj.BindToDropDown(ddlState, sqlstr1, "StateName", "StateCode"); // obj.BindToDropDown(ddlSiteId, sqlstr1, "SiteName", "SiteId"); // VRSDetail(); // } //} //protected void ddlState_SelectedIndexChanged(object sender, EventArgs e) //{ // gridVRSDetails.DataSource = null; // gridVRSDetails.DataBind(); // string sqlstr = "select * from ax.ACXSITEMENU where SITE_CODE ='" + Session["SiteCode"].ToString() + "'"; // object objcheckSitecode = obj.GetScalarValue(sqlstr); // if (objcheckSitecode != null) // { // ddlSiteId.Items.Clear(); // string sqlstr1 = @"Select Distinct SITEID as Code,NAME from [ax].[INVENTSITE] where STATECODE = '" + ddlState.SelectedItem.Value + "' Order By NAME"; // ddlSiteId.Items.Add("All..."); // obj.BindToDropDown(ddlSiteId, sqlstr1, "Name", "Code"); // ddlSiteId_SelectedIndexChanged(null, null); // } // else // { // ddlSiteId.Items.Clear(); // string sqlstr1 = @"Select Distinct S ITEID as Code,NAME from [ax].[INVENTSITE] where SITEID = '" + Session["SiteCode"].ToString() + "' Order By NAME"; // //ddlSiteId.Items.Add("All..."); // obj.BindToDropDown(ddlSiteId, sqlstr1, "Name", "Code"); // ddlSiteId_SelectedIndexChanged(null, null); // } //} protected void ddlSiteId_SelectedIndexChanged(object sender, EventArgs e) { gridVRSDetails.DataSource = null; gridVRSDetails.DataBind(); VRSDetail(); } protected void ddlVRS_SelectedIndexChanged(object sender, EventArgs e) { } } }
using Alabo.App.Asset.Coupons.Domain.Entities; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.App.Asset.Coupons.Domain.Repositories { public interface ICouponRepository : IRepository<Coupon, ObjectId> { } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Imp.Web.Framework.Mvc; namespace Imp.Admin.Models.Users { public class RoleModel : BaseImpEntityModel { [DisplayName("角色名称")] [Required(ErrorMessage = "名称不能为空")] public string Name { get; set; } [DisplayName("角色系统名称")] public string SystemName { get; set; } [DisplayName("显示顺序")] [Required(ErrorMessage = "请输入顺序"), RegularExpression(@"^[0-9]*$", ErrorMessage = "请输入数字")] public int DisplayOrder { get; set; } [DisplayName("是否系统角色")] public bool IsSystemRole { get; set; } } }
using System; using FluentAssertions; using Xunit; namespace PluralsightDdd.SharedKernel.UnitTests.DateTimeRangeTests { public class DateTimeRange_Overlaps { [Fact] public void ReturnsTrueGivenSameDateTimeRange() { var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var result = dtr.Overlaps(dtr); result.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenEarlierRangeExceedingStart() { var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var earlier = new DateTimeRange(DateTimes.TestDateTime.AddMinutes(-5), TimeSpan.FromMinutes(10)); var result = dtr.Overlaps(earlier); result.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenRangeWithinRange() { var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var within = new DateTimeRange(DateTimes.TestDateTime.AddMinutes(5), TimeSpan.FromMinutes(10)); var result = dtr.Overlaps(within); result.Should().BeTrue(); } [Fact] public void ReturnsTrueGivenRangeStartingWithinRangeEndingLater() { var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var endslater = new DateTimeRange(dtr.End.AddMinutes(-5), TimeSpan.FromMinutes(10)); var result = dtr.Overlaps(endslater); result.Should().BeTrue(); } [Fact] public void ReturnsFalseGivenRangeEndingBeforeStart() { var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var endsearlier = new DateTimeRange(dtr.Start.AddHours(-1), TimeSpan.FromMinutes(10)); var result = dtr.Overlaps(endsearlier); result.Should().BeFalse(); } [Fact] public void ReturnsFalseGivenRangeStartingAfterEnd() { var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var startslater = new DateTimeRange(dtr.End.AddMinutes(1), TimeSpan.FromMinutes(10)); var result = dtr.Overlaps(startslater); result.Should().BeFalse(); } } }
using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UPractice.Dbcontext; namespace UPractice.Model { class AddTeacherModel : BindableBase { public void AddTeacher(string FirstName, string SecondName, string LastName, int Phone, string Email) { if (!(string.IsNullOrEmpty(FirstName) && string.IsNullOrWhiteSpace(FirstName)) && !(string.IsNullOrEmpty(SecondName) && string.IsNullOrWhiteSpace(SecondName)) && !(string.IsNullOrEmpty(LastName) && string.IsNullOrWhiteSpace(LastName)) && !(string.IsNullOrEmpty(Email) && string.IsNullOrWhiteSpace(Email))) { Teacher teacher = new Teacher() { FirstName = FirstName , SecondName = SecondName, LastName = LastName, Phone = Phone, Email = Email }; using (var db = new MyDbcontext()) { db.Teachers.Add(teacher); db.SaveChanges(); } } else { throw new System.InvalidOperationException("Fields are empty"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace HardwareStore.Domain.Entities { public class TextField : EntityBase { [Required] public string CodeWord { get; set; } [Display(Name = "Заголовок")] public virtual string Title { get; set; } = "Информационная страница"; [Display(Name = "Полное описание")] public virtual string Text { get; set; } = "Содержание заполняется администратором"; } }
using System; using System.Collections.Generic; using System.Text; namespace VehicleModel { public interface IRover { Position Position { get; } RoverFacing Facing { get; } void MoveForward(); void TurnLeft(); void TurnRight(); } }
using System; using zm.Util; namespace zm.Users { /// <summary> /// Class holding collection of Users to enable serialization of List<User> /// </summary> [Serializable] public class UserResultsCollection : GenericSerializableCollection<UserResult> { } }
using System; using NetEscapades.AspNetCore.SecurityHeaders.Headers; // ReSharper disable once CheckNamespace namespace Microsoft.AspNetCore.Builder { /// <summary> /// Extension methods for adding a <see cref="PermissionsPolicyHeader" /> to a <see cref="HeaderPolicyCollection" /> /// </summary> public static class PermissionsPolicyHeaderExtensions { /// <summary> /// Add a Permissions-Policy header to all requests /// </summary> /// <param name="policies">The collection of policies</param> /// <param name="configure">Configure the Permissions-Policy</param> /// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns> public static HeaderPolicyCollection AddPermissionsPolicy(this HeaderPolicyCollection policies, Action<PermissionsPolicyBuilder> configure) { return policies.ApplyPolicy(PermissionsPolicyHeader.Build(configure)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.Http; using WebApiPagingAngularClient.Models; namespace WebApiPagingAngularClient.Controllers { [RoutePrefix("api/book")] public class BookController : ApiController { [Route("")] // GET: api/Book public IHttpActionResult Get() { using (var db = new BooksEntities()) { var boo = ( from b in db.Book select new { Name = b.Name, Image = b.Image, Description = b.Description, File = b.File, Authors = (from a in db.Author from t in db.Table where (t.Author_id == a.Id && t.Book_id == b.Id) select a).ToList() }).ToList(); var result = new { Books = boo }; return Ok(result); } } // GET: api/Book/pageSize/pageNumber/ [Route("{pageSize:int}/{pageNumber:int}")] public IHttpActionResult Get( int pageSize, int pageNumber) { using (var db = new BooksEntities()) { var boo = ( from b in db.Book orderby b.Id descending select new { Name = b.Name, Image = b.Image, Description = b.Description, File = b.File, Authors = (from a in db.Author from t in db.Table where (t.Author_id == a.Id && t.Book_id == b.Id) select a).ToList() }).ToList(); var totalCount = boo.Count(); var totalPages = Math.Ceiling((double)totalCount / pageSize); var elements = boo.Skip((pageNumber - 1) * pageSize) .Take(pageSize) .ToList(); var result = new { TotalCount = totalCount, TotalPages = totalPages, Books = elements }; return Ok(result); } } // GET: api/Book/Author [Route("{name:minlength(0)}")] public IHttpActionResult Get(string name) { using (var db = new BooksEntities()) { //пошук книг по автору var temp = (from a in db.Author join t in db.Table on a.Id equals t.Author_id where (a.Name + " " + a.SName).Contains(name) select t); var auth = ( from b in db.Book join t in temp on b.Id equals t.Book_id where (b.Id == t.Book_id) select new { Name = b.Name, Image = b.Image, Description = b.Description, File = b.File, Authors = (from a in db.Author from t in db.Table where (t.Author_id == a.Id && t.Book_id == b.Id) select a).ToList() }).GroupBy(n => new { n.Name }).Select(g => g.FirstOrDefault()).ToList(); //Пошук книг по назві var boo = ( from b in db.Book where b.Name.Contains(name) select new { Name = b.Name, Image = b.Image, Description = b.Description, File = b.File, Authors = (from a in db.Author from t in db.Table where (t.Author_id == a.Id && t.Book_id == b.Id) select a).ToList() }).ToList(); var result = new { Book = auth.Union(boo).GroupBy(n => new { n.Name }).Select(g => g.FirstOrDefault()) }; return Ok(result); } } // GET: api/Book/Name/file [Route("add/{name:minlength(0)}/{file:minlength(0)}")] public IHttpActionResult Get(string name, string file) { string img = "C: \\Users\\OlehX\\Desktop\\Implement - directory - file - browsing--master\\WebApiBooksAngularClient\\Books\\Images\\Car Hacks.jpg"; string descr = "AZAZA"; Book book = new Book { Name = name, Image = img, Description = descr, File = file }; List<Author> authors = new List<Author> { new Author{Id = 0, Name = "Abuu", SName = "Sitkh" }, new Author { Id = 1, Name = "Эрик", SName = "Фримен" } }; using (var db = new BooksEntities()) { if (!(from b in db.Book where (b.Name.Equals(book.Name)) select b).Any()) { book.Id = (from b in db.Book select b.Id).ToList().Last() + 1; db.Book.Add(book); //пошук книг по автору foreach (Author author in authors) { var temp = (from a in db.Author join t in db.Table on a.Id equals t.Author_id where (a.Name.Equals(author.Name) && a.SName.Equals(author.SName)) select a.Id).FirstOrDefault(); if (temp != 0) { author.Id = temp; } else { author.Id = (from a in db.Author select a.Id).ToList().Last() + 1; db.Author.Add(author); } db.Table.Add(new Table { Id = (from t in db.Table select t.Id).ToList().Last() + 1, Book_id = book.Id, Author_id = author.Id }); db.SaveChanges(); } } } return Get(); } // POST: api/Book [Route("")] [HttpPost] public void Post([FromBody]BookModel book) { Book boo = new Book { Name = book.Name, Image = book.Image, Description = book.Description, File = book.File }; /* List<Author> authors = new List<Author> { new Author{Id = 0, Name = "Abuu", SName = "Sitkh" }, new Author { Id = 1, Name = "Эрик", SName = "Фримен" } };*/ using (var db = new BooksEntities()) { if (!(from b in db.Book where (b.Name.Equals(book.Name)) select b).Any()) { boo.Id = (from b in db.Book select b.Id).ToList().Last() + 1; db.Book.Add(boo); //пошук книг по автору foreach (Author author in book.Authors) { var temp = (from a in db.Author join t in db.Table on a.Id equals t.Author_id where (a.Name.Equals(author.Name) && a.SName.Equals(author.SName)) select a.Id).FirstOrDefault(); if (temp != 0) { author.Id = temp; } else { author.Id = (from a in db.Author select a.Id).ToList().Last() + 1; db.Author.Add(author); } db.Table.Add(new Table { Id = (from t in db.Table select t.Id).ToList().Last() + 1, Book_id = boo.Id, Author_id = author.Id }); db.SaveChanges(); } } } } // PUT: api/Book/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Book/5 public void Delete(int id) { } } }
using System.Collections.Generic; using SuperMario.Collision; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using SuperMario.Sound; namespace SuperMario.Entities.Items { public class Star : MovingAnimatedEntity { Texture2D starTexture; int currentX; int distanceUpFromBounce; int upWardVelocity; bool goUp; ICollisionHandler itemCollisionHandler; int numberOfFrames = 4; public Star(Vector2 screenLocation) : base(screenLocation, 700000) { upWardVelocity = -3; distanceUpFromBounce = 0; goUp = false; starTexture = WinterTextureStorage.StarSpriteSheetWinter; itemCollisionHandler = new ItemCollisionHandler(this); EntityVelocity = new Vector2(1, -3); } public override ISprite FirstSprite => new Sprite(starTexture, new Rectangle(0, 0, starTexture.Width / numberOfFrames, starTexture.Height)); public override ISprite NextSprite { get { currentX += starTexture.Width / numberOfFrames; if (currentX == starTexture.Width) currentX = 0; return new Sprite(starTexture, new Rectangle(currentX, 0, starTexture.Width / numberOfFrames, starTexture.Height)); } } public override void Update(GameTime gameTime) { base.Update(gameTime); Move(); RestrictedMovementDirections.Clear(); } public void Obtain() { SoundEffects.Instance.PlayPowerUp(); int timeInTicksToPlayHurryMusic = 1000000000; if (HUDController.Instance.TimeInTicks>= timeInTicksToPlayHurryMusic) Music.Instance.PlayStarman(); else Music.Instance.PlayStarManHurry(); Seppuku(); } protected override void Move() { int maxBounceHeight = 48; base.Move(); if (Grounded) goUp = true; if (!RestrictedMovementDirections.Contains(Direction.Up) && goUp && distanceUpFromBounce <= maxBounceHeight) { ScreenLocation = new Vector2(ScreenLocation.X, ScreenLocation.Y + EntityVelocity.Y); distanceUpFromBounce = distanceUpFromBounce - upWardVelocity; } else { goUp = false; distanceUpFromBounce = 0; } } public override void Collide(Entity entity, RectangleCollisions collisions) { RestrictedMovementDirections.UnionWith(itemCollisionHandler.Collide(entity, collisions)); } } }
using DanialProject.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using System; using System.Security.Claims; using System.Threading.Tasks; [assembly: OwinStartupAttribute(typeof(DanialProject.Startup))] namespace DanialProject { public partial class Startup { public Startup() { } public void Configuration(IAppBuilder app) { this.ConfigureAuth(app); } public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext<ApplicationDbContext>(new Func<ApplicationDbContext>(ApplicationDbContext.Create)); app.CreatePerOwinContext<ApplicationUserManager>(new Func<IdentityFactoryOptions<ApplicationUserManager>, IOwinContext, ApplicationUserManager>(ApplicationUserManager.Create)); app.CreatePerOwinContext<ApplicationSignInManager>(new Func<IdentityFactoryOptions<ApplicationSignInManager>, IOwinContext, ApplicationSignInManager>(ApplicationSignInManager.Create)); IAppBuilder app1 = app; CookieAuthenticationOptions options = new CookieAuthenticationOptions { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/Home/Index"), Provider = (ICookieAuthenticationProvider)new CookieAuthenticationProvider() { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(TimeSpan.FromMinutes(525600.0), (Func<ApplicationUserManager, ApplicationUser, Task<ClaimsIdentity>>)((manager, user) => user.GenerateUserIdentityAsync((UserManager<ApplicationUser>)manager))), OnApplyRedirect = (Action<CookieApplyRedirectContext>)(ctx => { if (Startup.IsAjaxRequest(ctx.Request)) return; ctx.Response.Redirect(ctx.RedirectUri); }) } }; app1.UseCookieAuthentication(options); app.UseExternalSignInCookie("ExternalCookie"); app.UseTwoFactorSignInCookie("TwoFactorCookie", TimeSpan.FromMinutes(525600.0)); app.UseTwoFactorRememberBrowserCookie("TwoFactorRememberBrowser"); } private static bool IsAjaxRequest(IOwinRequest request) { IReadableStringCollection query = request.Query; if (query != null && query["X-Requested-With"] == "XMLHttpRequest") return true; IHeaderDictionary headers = request.Headers; return headers != null && headers["X-Requested-With"] == "XMLHttpRequest"; } } }
using System; using System.Collections.Generic; using System.Linq; using Modelos; using System.Data.Entity; namespace AcessoDados.Repositorio { public class ProdutoRepositorio { public List<Produto> ObterProdutos(int pagina = 1, int linhas = 5) { using (Contexto db = new Contexto()) { //db.Produtos.Include("Usuario").OrderBy(p => p.nmProduto).Skip((pagina - 1) * linhas).Take(linhas).ToList() --- LAZY /* var query = db.Produtos; //.Where(d => d.Nome == "Desenvolvimento"); var dev = query.Single(); db.Entry(dev).Collection("Usuario").Load(); Explicit */ return db.Produtos.Include("Usuario").Include("Categoria").OrderBy(p => p.nmProduto).Skip((pagina - 1) * linhas).Take(linhas).ToList(); } } public Produto InstanciarProduto() { Produto produto = new Produto(); return produto; } public int ObterQuantidadeProdutos() { using (Contexto db = new Contexto()) { try { return db.Produtos.Count(); } catch (Exception e) { throw e; } } } public Produto ObterProduto(int Pid) { using (Contexto db = new Contexto()) { return db.Produtos.Include("Usuario").Include("Unidade").Include("Categoria").SingleOrDefault(p => p.ID == Pid); } } public List<Produto> ObterPNome(string pNmProduto) { using (Contexto db = new Contexto()) { try { return db.Produtos.Include("Unidade").Where(p => p.nmProduto.Contains(pNmProduto)).ToList(); } catch (Exception e) { throw e; } } } public string ObterNomeProduto(long pId) { using (Contexto db = new Contexto()) { try { return db.Produtos.SingleOrDefault(p => p.ID == pId).nmProduto; } catch (Exception e) { return ""; } } } public Produto IncluirProduto(Produto Pproduto) { using (Contexto db = new Contexto()) { db.Entry(Pproduto).State = EntityState.Added; db.SaveChanges(); return Pproduto; } } public Produto AtualizarProduto(Produto Pproduto) { using (Contexto db = new Contexto()) { db.Entry(Pproduto).State = EntityState.Modified; db.SaveChanges(); return Pproduto; } } public void ExcluirProduto(Produto Pproduto) { using (Contexto db = new Contexto()) { db.Entry(Pproduto).State = EntityState.Deleted; db.SaveChanges(); } } public IEnumerable<Produto> ObterProdCategoria(int Pid) { using (Contexto db = new Contexto()) { return db.Produtos.ToList().Where(p => p.CategoriaId == Pid); } } } }
using Alabo.Data.People.Internals.Domain.Entities; using Alabo.Domains.Services; using MongoDB.Bson; namespace Alabo.Data.People.Internals.Domain.Services { public interface IInternalService : IService<Internal, ObjectId> { } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Aquamonix.Mobile.Lib.Extensions; namespace Aquamonix.Mobile.Lib.Domain { [DataContract] public class StartTime : IDomainObjectWithId, ICloneable<StartTime>, IMergeable<StartTime> { [DataMember(Name = PropertyNames.Id)] public string Id { get; set; } [DataMember(Name = PropertyNames.StartTime)] public string Value { get; set; } public StartTime Clone() { return new StartTime() { Id = this.Id, Value = this.Value }; } public void MergeFromParent(StartTime parent, bool removeIfMissingFromParent, bool parentIsMetadata) { if (parent != null) { this.Id = MergeExtensions.MergeProperty(this.Id, parent.Id, removeIfMissingFromParent, parentIsMetadata); this.Value = MergeExtensions.MergeProperty(this.Value, parent.Value, removeIfMissingFromParent, parentIsMetadata); } } public void ReadyChildIds() { } } }
using UnityEngine; using System.Collections; public class StageSelect_NoButton : MonoBehaviour { public Animator selectFrameAnim; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnBottonClick() { selectFrameAnim.SetTrigger("isClose"); } }
using Quark.Attributes; using Quark.Conditions; using Quark.Contexts; using Quark.Utilities; namespace Quark { /// <summary> /// This class is used for configuring a Quark game. /// It includes the base Attributes and Stats and the common interruption conditions. /// </summary> public class QuarkConfig { public AttributeCollection DefaultAttributes = new AttributeCollection(); public ConditionCollection<ICastContext> DefaultInterruption = new ConditionCollection<ICastContext> { new FalseCondition() }; public LogLevel LogLevel { get { return Logger.Level; } set { Logger.Level = value; } } } }
using System; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using System.Globalization; namespace Discord_Bot { public class UtilitySample : ModuleBase<SocketCommandContext> { [Command("ping")] [Summary("Show current latency.")] public async Task Ping() => await ReplyAsync($"Latency: {Context.Client.Latency} ms"); [Command("avatar")] [Alias("getavatar")] [Summary("Get a user's avatar.")] public async Task GetAvatar([Remainder]SocketGuildUser user = null) => await ReplyAsync($":frame_photo: **{(user ?? Context.User as SocketGuildUser).Username}**'s avatar\n{Functions.GetAvatarUrl(user)}"); [Command("info")] [Alias("server", "serverinfo")] [Summary("Show server information.")] [RequireBotPermission(GuildPermission.EmbedLinks)] // Require the bot the have the 'Embed Links' permissions to execute this command. public async Task ServerEmbed() { double botPercentage = Math.Round(Context.Guild.Users.Count(x => x.IsBot) / Context.Guild.MemberCount * 100d, 2); EmbedBuilder embed = new EmbedBuilder() .WithColor(0, 225, 225) .WithDescription( $"🏷️\n**Guild name:** {Context.Guild.Name}\n" + $"**Guild ID:** {Context.Guild.Id}\n" + $"**Created at:** {Context.Guild.CreatedAt:dd/M/yyyy}\n" + $"**Owner:** {Context.Guild.Owner}\n\n" + $"💬\n" + $"**Users:** {Context.Guild.MemberCount - Context.Guild.Users.Count(x => x.IsBot)}\n" + $"**Bots:** {Context.Guild.Users.Count(x => x.IsBot)} [ {botPercentage}% ]\n" + $"**Channels:** {Context.Guild.Channels.Count}\n" + $"**Roles:** {Context.Guild.Roles.Count}\n" + $"**Emotes: ** {Context.Guild.Emotes.Count}\n\n" + $"🌎 **Region:** {Context.Guild.VoiceRegionId}\n\n" + $"🔒 **Security level:** {Context.Guild.VerificationLevel}") .WithImageUrl(Context.Guild.IconUrl); await ReplyAsync($":information_source: Server info for **{Context.Guild.Name}**", embed: embed.Build()); } [Command("role")] [Alias("roleinfo")] [Summary("Show information about a role.")] public async Task RoleInfo([Remainder]SocketRole role) { // Just in case someone tries to be funny. if (role.Id == Context.Guild.EveryoneRole.Id) return; await ReplyAsync( $":flower_playing_cards: **{role.Name}** information```ini" + $"\n[Members] {role.Members.Count()}" + $"\n[Role ID] {role.Id}" + $"\n[Hoisted status] {role.IsHoisted}" + $"\n[Created at] {role.CreatedAt:dd/M/yyyy}" + $"\n[Hierarchy position] {role.Position}" + $"\n[Color Hex] {role.Color}```"); } // Please don't remove this command. I will appreciate it a lot <3 [Command("source")] [Alias("sourcecode", "src")] [Summary("Link the source code used for this bot.")] public async Task Source() => await ReplyAsync($":heart: **{Context.Client.CurrentUser}** is based on this source code:\nhttps://github.com/VACEfron/Discord-Bot-Csharp"); } }
namespace ProgFrog.Interface.TaskRunning { public interface IRunnerVisitor { void Configure(IProcessTaskRunner runner); } }
using RRExpress.Common.PCL; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace RRExpress.Common { public static class StringHelper { /// <summary> /// 從URL中取 Key / Value /// </summary> /// <param name="s"></param> /// <param name="ignoreCase"></param> /// <returns></returns> public static Dictionary<string, string> ParseString(this string s, bool ignoreCase) { //必須這樣,請不要修改 if (string.IsNullOrEmpty(s)) { return new Dictionary<string, string>(); } if (s.IndexOf('?') != -1) { s = s.Remove(0, s.IndexOf('?')); } Dictionary<string, string> kvs = new Dictionary<string, string>(); Regex reg = new Regex(@"[\?&]?(?<key>[^=]+)=(?<value>[^\&]*)"); MatchCollection ms = reg.Matches(s); string key; foreach (Match ma in ms) { key = ignoreCase ? ma.Groups["key"].Value.ToLower() : ma.Groups["key"].Value; if (kvs.ContainsKey(key)) { kvs[key] += "," + ma.Groups["value"].Value; } else { kvs[key] = ma.Groups["value"].Value; } } return kvs; } /// <summary> /// 設置 URL中的 key /// </summary> /// <param name="url"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="encode"></param> /// <returns></returns> public static string SetUrlKeyValue(this string url, string key, string value, Encoding encode = null) { if (url == null) url = ""; if (String.IsNullOrEmpty(key)) throw new ArgumentNullException("key"); if (value == null) value = ""; if (null == encode) encode = Encoding.UTF8; if (url.ParseString(true).ContainsKey(key.ToLower())) { Regex reg = new Regex(@"([\?\&])(" + key + @"=)([^\&]*)(\&?)", RegexOptions.IgnoreCase); return reg.Replace(url, (ma) => { if (ma.Success) { return string.Format("{0}{1}{2}{3}", ma.Groups[1].Value, ma.Groups[2].Value, value, ma.Groups[4].Value); } return ""; }); } else { return string.Format("{0}{1}{2}={3}", url, (url.IndexOf('?') > -1 ? "&" : "?"), key, value); } } public static string SetUrlKeyValue(this string url, Dictionary<string, string> kvs, Encoding encode = null) { foreach (var kv in kvs) { url = url.SetUrlKeyValue(kv.Key, kv.Value, encode); } return url; } /// <summary> /// 修正URL /// </summary> /// <param name="url"></param> /// <returns></returns> public static string FixUrl(this string url) { return url.FixUrl(""); } /// <summary> /// 修正URL /// </summary> /// <param name="url"></param> /// <param name="defaultPrefix"></param> /// <returns></returns> public static string FixUrl(this string url, string defaultPrefix) { // 必須這樣,請不要修改 if (url == null) url = ""; if (defaultPrefix == null) defaultPrefix = ""; string tmp = url.Trim(); if (!Regex.Match(tmp, "^(http|https):").Success) { tmp = string.Format("{0}/{1}", defaultPrefix, tmp); } tmp = Regex.Replace(tmp, @"(?<!(http|https):)[\\/]+", "/").Trim(); return tmp; } #region To int /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static int ToInt(this string str, int defaultValue) { int v; if (int.TryParse(str, out v)) { return v; } else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static int ToInt(this string str) { return str.ToInt(0); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static int? ToIntOrNull(this string str, int? defaultValue) { int v; if (int.TryParse(str, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static int? ToIntOrNull(this string str) { return str.ToIntOrNull(null); } /// <summary> /// 智慧轉換為 Int ,取字串中的第一個數位串 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static int SmartToInt(this string str, int defaultValue) { if (string.IsNullOrEmpty(str)) return defaultValue; //Match ma = Regex.Match(str, @"(\d+)"); Match ma = Regex.Match(str, @"((-\s*)?\d+)"); if (ma.Success) { return ma.Groups[1].Value.Replace(" ", "").ToInt(defaultValue); } else { return defaultValue; } } #endregion #region To Float /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static float ToFloat(this string str, float defaultValue) { float v; if (float.TryParse(str, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static float ToFloat(this string str) { return str.ToFloat(0f); } /// <summary> /// 智慧轉換為 float ,取字串中的第一個數位串 /// 可轉換 a1.2, 0.12 1.2aa , 1.2e+7 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static float SmartToFloat(this string str, float defaultValue) { if (string.IsNullOrEmpty(str)) return defaultValue; //Regex rx = new Regex(@"((\d+)(\.?((?=\d)\d+))?(e\+\d)*)"); Regex rx = new Regex(@"((-\s*)?(\d+)(\.?((?=\d)\d+))?(e[\+-]?\d+)*)"); Match ma = rx.Match(str); if (ma.Success) { return ma.Groups[1].Value.Replace(" ", "").ToFloat(defaultValue); } else { return defaultValue; } } #endregion #region To Decimal /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static decimal ToDecimal(this string str, decimal defaultValue) { decimal v; if (decimal.TryParse(str, NumberStyles.Any, null, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static decimal ToDecimal(this string str) { return str.ToDecimal(0); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static decimal? ToDecimalOrNull(this string str) { decimal temp; if (decimal.TryParse(str, out temp)) return temp; else return null; } /// <summary> /// 智慧轉換為 float ,取字串中的第一個數位串 /// 可轉換 a1.2, 0.12 1.2aa , 1.2e+7 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static decimal SmartToDecimal(this string str, decimal defaultValue) { if (string.IsNullOrEmpty(str)) return defaultValue; //Regex rx = new Regex(@"((\d+)(\.?((?=\d)\d+))?(e\+\d)*)"); //Regex rx = new Regex(@"((-\s*)?(\d+)(\.?((?=\d)\d+))?(e[\+-]?\d+)*)"); Regex rx = new Regex(@"((-\s*)?(\d+(,\d+)*)(\.?((?=\d)\d+))?(e[\+-]?\d+)*)"); Match ma = rx.Match(str); if (ma.Success) { return ma.Groups[1].Value.Replace(" ", "").Replace(",", "").ToDecimal(defaultValue); } else { return defaultValue; } } #endregion #region To byte /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static byte ToByte(this string str, byte defaultValue) { byte v; if (byte.TryParse(str, out v)) { return v; } else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte ToByte(this string str) { return str.ToByte(0); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static byte? ToByteOrNull(this string str, byte? defaultValue) { byte v; if (byte.TryParse(str, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte? ToByteOrNull(this string str) { return str.ToByteOrNull(null); } #endregion #region To long /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static long ToLong(this string str, long defaultValue) { long v; if (long.TryParse(str, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static long ToLong(this string str) { return str.ToLong(0); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static long? ToLongOrNull(this string str) { long temp; if (long.TryParse(str, out temp)) return temp; else return null; } #endregion #region To ulong /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static ulong ToUlong(this string str, ulong defaultValue) { ulong v; if (ulong.TryParse(str, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static ulong ToUlong(this string str) { return str.ToUlong(0); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static ulong? ToUlongOrNull(this string str) { ulong temp; if (ulong.TryParse(str, out temp)) return temp; else return null; } #endregion #region ToBool /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static bool ToBool(this string str, bool defaultValue) { bool b; if (bool.TryParse(str, out b)) { return b; } else { return defaultValue; } } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool ToBool(this string str) { return str.ToBool(false); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool? ToBoolOrNull(this string str) { bool temp; if (bool.TryParse(str, out temp)) return temp; else return null; } #endregion #region ToDouble /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static double ToDouble(this string str, double defaultValue) { double v; if (double.TryParse(str, NumberStyles.Any, null, out v)) return v; else return defaultValue; } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static double ToDouble(this string str) { return str.ToDouble(0); } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static double? ToDoubleOrNull(this string str) { double temp; if (double.TryParse(str, out temp)) return temp; else return null; } #endregion #region DateTime /// <summary> /// 轉換為日期,如果轉換失敗,返回預設值 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static DateTime? ToDateTimeOrNull(this string str, DateTime? defaultValue = null) { DateTime d; if (DateTime.TryParse(str, out d)) return d; else { if (DateTime.TryParseExact(str, new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd", "yyyyMMdd HH:mm:ss", "yyyy/MM/dd", "yyyy'/'MM'/'dd HH:mm:ss", "MM'/'dd'/'yyyy HH:mm:ss", "yyyy-M-d", "yyy-M-d hh:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d)) return d; else return defaultValue; } } /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="dateFmt"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static DateTime? ToDateTimeOrNull(this string str, string dateFmt, DateTime? defaultValue = null) { DateTime d; //if (DateTime.TryParse(str, out d)) // return d; //else { if (DateTime.TryParseExact(str, dateFmt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d)) return d; else return defaultValue; //} } private static readonly DateTime MinDate = new DateTime(1900, 1, 1); /// <summary> /// 轉換日期,轉換失敗時,返回 defaultValue /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static DateTime ToDateTime(this string str, DateTime defaultValue = default(DateTime)) { DateTime d; if (DateTime.TryParse(str, out d)) return d; else { if (DateTime.TryParseExact(str, new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd", "yyyyMMdd HH:mm:ss", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d)) return d; else if (default(DateTime) == defaultValue) return MinDate; else return defaultValue; } } /// <summary> /// 按給定日期格式進行日期轉換 /// </summary> /// <param name="str"></param> /// <param name="dateFmt"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static DateTime ToDateTime(this string str, string dateFmt, DateTime defaultValue) { DateTime d; //if (DateTime.TryParse(str, out d)) // return d; //else { if (DateTime.TryParseExact(str, dateFmt, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d)) return d; else return defaultValue; //} } /// <summary> /// 轉換為日期,轉換失敗時,返回null /// </summary> /// <param name="str"></param> /// <returns></returns> public static DateTime? ToDateTimeOrNull(this string str) { return str.ToDateTimeOrNull(null); } /// <summary> /// 轉換日期,轉換失敗時,返回當前時間 /// </summary> /// <param name="str"></param> /// <returns></returns> public static DateTime ToDateTime(this string str) { return str.ToDateTime(DateTime.Now); } /// <summary> /// 是否為日期型字串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsDateTime(this string str) { //return Regex.IsMatch(str, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$ "); DateTime d; if (DateTime.TryParseExact(str, new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyyMMdd", "yyyyMMdd HH:mm:ss", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "MM/dd/yyyy", "MM/dd/yyyy HH:mm:ss" }, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d)) return true; else return false; } #endregion #region ToTimeSpan /// <summary> /// /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static TimeSpan ToTimeSpan(this string str, TimeSpan defaultValue) { TimeSpan t; if (TimeSpan.TryParse(str, out t)) { return t; } else { return defaultValue; } } /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static TimeSpan ToTimeSpan(this string str) { return str.ToTimeSpan(new TimeSpan()); } #endregion #region Guid /// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public static Guid ToGuid(this string str) { Guid g; if (Guid.TryParse(str, out g)) return g; else return Guid.Empty; } #endregion #region mix /// <summary> /// 獲取用於 Javascript 的安全字串 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string JsSafeString(this string str) { if (String.IsNullOrEmpty(str)) return "";//必須這樣,請不要修改 return str.ToString().Replace("'", "\\'").Replace("\"", "&quot;"); } /// <summary> /// 安全的转换为大写 /// <remarks> /// 如果直接用 ToUpper , 当为 null 的时候,会报 NullReference /// </remarks> /// </summary> /// <param name="str"></param> /// <returns></returns> public static string SafeToUpper(this string str) { if (string.IsNullOrWhiteSpace(str)) return str; else return str.ToUpper(); } /// <summary> /// 安全的转换为小写 /// <remarks> /// 如果直接用 ToUpper , 当为 null 的时候,会报 NullReference /// </remarks> /// </summary> /// <param name="str"></param> /// <returns></returns> public static string SafeToLower(this string str) { if (string.IsNullOrWhiteSpace(str)) return str; else return str.ToLower(); } public static string SafeSubString(this string str, int length, int start = 0) { if (string.IsNullOrEmpty(str)) return str; return new String(str.Cast<char>().Skip(start).Take(length).ToArray()); } public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } public static bool IsNullOrWhiteSpace(this string str) { return string.IsNullOrWhiteSpace(str); } #endregion #region public static string ToMD5(this string input) { using (var md5Hasher = MD5.Create()) { byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EntityFrameworkCoreDemo.Models { public enum Schedules { Day = 0, Night = 1 } }
using System; namespace SingletonPattern { public class ChocolateBoiler { public static ChocolateBoiler Instance { get; } = new ChocolateBoiler(); public bool Empty { get; private set; } public bool Boiled { get; private set; } private ChocolateBoiler() { Empty = true; Boiled = false; } public void Fill() { if (Empty) { Empty = false; Boiled = false; Console.WriteLine("filling the boiler with a milk/chocolate mixture"); } } public void Drain() { if (!Empty && Boiled) { Console.WriteLine("draining the boiled milk and chocolate"); Empty = true; } } public void Boil() { if (!Empty && !Boiled) { Console.WriteLine("bringing the contents to a boil"); Boiled = true; } } } }
namespace Vidly.Migrations { using System; using System.Data.Entity.Migrations; public partial class Genre2 : DbMigration { public override void Up() { Sql("INSERT INTO Movies (Name, GenreId, ReleaseDate, DateAdded, NumberInStock) VALUES ('Bahubali2',1,CAST('2018-06-30' AS DATETIME), CAST('2019-04-01' AS DATETIME),8)"); Sql("INSERT INTO Movies (Name, GenreId, ReleaseDate, DateAdded, NumberInStock) VALUES ('Robo',1,CAST('2017-09-01' AS DATETIME), CAST('2019-04-01' AS DATETIME),3)"); Sql("INSERT INTO Movies (Name, GenreId, ReleaseDate, DateAdded, NumberInStock) VALUES ('Bharath Ana Nanu',3,CAST('2018-11-01' AS DATETIME), CAST('2019-04-01' AS DATETIME),12)"); Sql("INSERT INTO Movies (Name, GenreId, ReleaseDate, DateAdded, NumberInStock) VALUES ('2.0',1,CAST('2018-11-19' AS DATETIME), CAST('2019-04-01' AS DATETIME),5)"); Sql("INSERT INTO Movies (Name, GenreId, ReleaseDate, DateAdded, NumberInStock) VALUES ('Johnny',4,CAST('2010-06-10' AS DATETIME), CAST('2019-04-01' AS DATETIME),10)"); Sql("INSERT INTO Movies (Name, GenreId, ReleaseDate, DateAdded, NumberInStock) VALUES ('f2',5,CAST('2019-01-15' AS DATETIME), CAST('2019-04-01' AS DATETIME),30)"); } public override void Down() { } } }
using System; class Program { static void Main() { int students = int.Parse(Console.ReadLine()); int sheets = int.Parse(Console.ReadLine()); double price = double.Parse(Console.ReadLine()); long totalSheets = students * sheets; double reams = totalSheets / 400.0; double amount = reams * price; Console.WriteLine("{0:F3}", amount); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using service.Models; namespace service.Controllers { public class NewsController : Controller { Logmodel log = new Logmodel(); // GET: /<controller>/ public IActionResult Index() { return View("~/Views/web001/News/Index.cshtml"); } public IActionResult Postnews() { return View(); } [HttpPost] public IActionResult news_feed() { Encryption_model encode = new Encryption_model(); var body = ""; using (var mem = new MemoryStream()) using (var reader = new StreamReader(mem)) { Request.Body.CopyTo(mem); body = reader.ReadToEnd(); mem.Seek(0, SeekOrigin.Begin); body = reader.ReadToEnd(); } //var request_data = JObject.Parse(body); log.info("Iswan receive_message " + body.ToString()); log.info("Iswan receive_message " + encode.base64_decode(body.ToString())); var request_data = JObject.Parse(encode.base64_decode(body.ToString())); return Content("Receivedata : " + Utility.numConvertChar("1020000.21")); } [HttpPost] public IActionResult receive_message() { Encryption_model encode = new Encryption_model(); var body = ""; using (var mem = new MemoryStream()) using (var reader = new StreamReader(mem)) { Request.Body.CopyTo(mem); body = reader.ReadToEnd(); mem.Seek(0, SeekOrigin.Begin); body = reader.ReadToEnd(); } //var request_data = JObject.Parse(body); log.info("Iswan receive_message " + body.ToString()); log.info("Iswan receive_message " + encode.base64_decode(body.ToString())); var request_data = JObject.Parse(encode.base64_decode(body.ToString())); return Content("Receivedata : "+Utility.numConvertChar("1020000.21")); } } }
using PhotoShare.Client.Interfaces; using System; using System.Data.Entity.Validation; namespace PhotoShare.Client.Core { class Engine : IRunnable { private readonly ICommandDispatcher commandDispatcher; private readonly IReader reader; private readonly IWriter writer; public Engine(ICommandDispatcher commandDispatcher, IReader reader, IWriter writer) { this.commandDispatcher = commandDispatcher; this.reader = reader; this.writer = writer; } public void Run(string start) { this.writer.WriteLine("Program started"); while (true) { try { string input = reader.ReadLine(); string[] data = input.Split(); string commandName = data[0]; IExecutable command = this.commandDispatcher.DispatchCommand(commandName, data); string result = command.Execute(); command.CommitChanges(); this.writer.WriteLine(result); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } catch (Exception e) { this.writer.WriteLine(e.Message); } } } } }
// <copyright file="ThirdTask.cs" company="MyCompany.com"> // Contains the solutions to tasks of the 'Methods in detail' module. // </copyright> // <author>Daryn Akhmetov</author> namespace Methods_in_detail { /// <summary> /// Contains implementation of the given by the task algorithm. /// </summary> public static class ThirdTask { /// <summary> /// Gets a value indicating whether a given null-able variable is equal to null. /// </summary> /// <param name="nullableVariable">Variable of null-able type.</param> /// <returns>true if a given null-able variable is equal to null; otherwise false.</returns> public static bool IsNull(this object nullableVariable) { return nullableVariable == null; } } }
using Barker_API.Models; using Barker_API.Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Barker_API.Data { public class UserService : IUserService { IUserRepo repo; public UserService() { repo = new UserRepo(); } public async Task<User> CreateUserAsync(User user) { return await repo.CreateUserAsync(user); } public async Task DeleteUserAsync(int userID) { await repo.DeleteUserAsync(userID); } public async Task<User> GetUserAsync(string email) { return await repo.GetUserAsync(email); } public async Task<User> GetUserAsync(int id) { return await repo.GetUserAsync(id); } public async Task<User> UpdateUserAsync(User user) { return await repo.UpdateUserAsync(user); } } }
using System; namespace Class_Library { public class clsManufacturer { public bool Active { get; set; } public bool Available { get; set; } public DateTime YearMade { get; set; } public int ManufacturerID { get; set; } public int BatchProductionNo { get; set; } public int PhoneNo { get; set; } public string CarModel { get; set; } public string ChairMan { get; set; } public string Email { get; set; } public bool Find(int ManufacturerID) { //always return true return true; } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using Pe.Stracon.Politicas.Aplicacion.Core.Base; using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract; using Pe.Stracon.Politicas.Aplicacion.Service.Base; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using Pe.Stracon.Politicas.Infraestructura.Core.QueryContract.General; using Pe.Stracon.Politicas.Infraestructura.QueryModel.General; using Pe.Stracon.Politicas.Infraestructura.Core.CommandContract.General; using Pe.Stracon.Politicas.Infraestructura.CommandModel.General; using Pe.Stracon.Politicas.Aplicacion.Adapter.General; using Pe.Stracon.PoliticasCross.Core.Exception; using System.Transactions; using Pe.Stracon.PoliticasCross.Core.Base; using Pe.Stracon.Politicas.Infraestructura.Core.Context; using System.Data; namespace Pe.Stracon.Politicas.Aplicacion.Service.General { /// <summary> /// Implementación base generica de servicios de aplicación /// </summary> /// <remarks> /// Creación: GMD 20150327 <br /> /// Modificación: <br /> /// </remarks> public class ParametroValorService : GenericService, IParametroValorService { /// <summary> /// Repositorio de parametro valor logic /// </summary> public IParametroValorLogicRepository parametroValorLogicRepository { get; set; } /// <summary> /// Service de Parametro Sección /// </summary> public IParametroSeccionService parametroSeccionService { get; set; } /// <summary> /// Service de Parametro /// </summary> public IParametroService parametroService { get; set; } /* JCP: 16/01/2018 * Metodo Original para carga de parametros se reemplazo la logica * por BuscarParametroValor_Optimizado que hace la carga de parametros * en memoria para luego utilizarlas /// <summary> /// Realiza la busqueda de Parametro Valor /// </summary> /// <param name="filtro">Filtro de Parametro Valor</param> /// <returns>Listado de parametro valor</returns> public ProcessResult<List<ParametroValorResponse>> BuscarParametroValor(ParametroValorRequest filtro) { ProcessResult<List<ParametroValorResponse>> resultado = new ProcessResult<List<ParametroValorResponse>>(); try { List<ParametroValorLogic> listado = parametroValorLogicRepository.BuscarParametroValor( filtro.CodigoParametro, filtro.IndicadorEmpresa, (filtro.CodigoEmpresa != null ? new Guid(filtro.CodigoEmpresa) : (Guid?)null), (filtro.CodigoSistema != null ? new Guid(filtro.CodigoSistema) : (Guid?)null), filtro.CodigoIdentificador, filtro.TipoParametro, filtro.CodigoSeccion, filtro.CodigoValor, filtro.Valor, filtro.EstadoRegistro); var listaParametroValor = new List<ParametroValorResponse>(); ParametroValorResponse parametroValor = new ParametroValorResponse(); parametroValor.RegistroCadena = new Dictionary<string, string>(); parametroValor.RegistroObjeto = new Dictionary<string, object>(); for (var iterator = 0; iterator < listado.Count; iterator++) { var itemValue = listado[iterator]; parametroValor.Valor = itemValue.Valor; parametroValor.CodigoSeccion = itemValue.CodigoSeccion; var listSecciones = parametroSeccionService.BuscarParametroSeccion(new ParametroSeccionRequest() { CodigoParametro = itemValue.CodigoParametro }).Result; var seccionActual = listSecciones.Where(itemSeccion => itemSeccion.CodigoSeccion == itemValue.CodigoSeccion).FirstOrDefault(); if (seccionActual != null) { string valorTexto = ParametroValorAdapter.ObtenerParametroValorTexto(itemValue.CodigoTipoDato, itemValue.Valor); object valorObject = ParametroValorAdapter.ObtenerParametroValorObjeto(itemValue.CodigoTipoDato, itemValue.Valor); //Asginación de la Sección con su respectivo Valor Original parametroValor.RegistroCadena.Add(itemValue.CodigoSeccion.ToString(), valorTexto); parametroValor.RegistroObjeto.Add(itemValue.CodigoSeccion.ToString(), valorObject); //Asginación de la Sección con su respectivo Valor Relacionado if (seccionActual.CodigoParametroRelacionado != null && seccionActual.CodigoSeccionRelacionado != null && seccionActual.CodigoSeccionRelacionadoMostrar != null) { var parametroValorRelacionado = parametroValorLogicRepository.BuscarParametroValor(seccionActual.CodigoParametroRelacionado, null, null, null, null, null, null, null, null, DatosConstantes.EstadoRegistro.Activo); var codigoValorRelacionado = parametroValorRelacionado.Where(itemWhere => itemWhere.CodigoSeccion == seccionActual.CodigoSeccionRelacionado && itemWhere.Valor == valorTexto).Select(itemSelect => itemSelect.CodigoValor).FirstOrDefault(); var valorRelacionado = parametroValorRelacionado.Where(itemWhere => itemWhere.CodigoValor == codigoValorRelacionado && itemWhere.CodigoSeccion == seccionActual.CodigoSeccionRelacionadoMostrar).FirstOrDefault() ?? new ParametroValorLogic(); object valorObjectRelacionado = ParametroValorAdapter.ObtenerParametroValorObjeto(valorRelacionado.CodigoTipoDato, valorRelacionado.Valor); string valorTextoRelacionado = ParametroValorAdapter.ObtenerParametroValorTexto(valorRelacionado.CodigoTipoDato, valorRelacionado.Valor); parametroValor.RegistroCadena.Add("-" + itemValue.CodigoSeccion.ToString(), valorTextoRelacionado); parametroValor.RegistroObjeto.Add("-" + itemValue.CodigoSeccion.ToString(), valorObjectRelacionado); } //Asginación del Estado de Registro if (parametroValor.EstadoRegistro == null || parametroValor.EstadoRegistro == DatosConstantes.EstadoRegistro.Inactivo) { parametroValor.EstadoRegistro = itemValue.EstadoRegistro; } //Añade el registro en la Lista de Parametros según su quiebre if (iterator == listado.Count - 1 || itemValue.CodigoValor != listado[iterator + 1].CodigoValor) { parametroValor.CodigoValor = itemValue.CodigoValor; parametroValor.CodigoIdentificador = itemValue.CodigoIdentificador; parametroValor.CodigoParametro = itemValue.CodigoParametro; var seccionesFaltante = listSecciones.Where(itemWhere => !parametroValor.RegistroCadena.Any(itemAny => itemAny.Key == itemWhere.CodigoSeccion.ToString())).ToList(); foreach (var seccion in seccionesFaltante) { //Setear la Sección con su respectivo Valor parametroValor.RegistroCadena.Add(seccion.CodigoSeccion.ToString(), null); parametroValor.RegistroObjeto.Add(seccion.CodigoSeccion.ToString(), null); } listaParametroValor.Add(parametroValor); //Limpiar variable parametroValor = new ParametroValorResponse(); parametroValor.RegistroCadena = new Dictionary<string, string>(); parametroValor.RegistroObjeto = new Dictionary<string, object>(); } } } resultado.Result = listaParametroValor; } catch (Exception e) { resultado.Result = new List<ParametroValorResponse>(); resultado.IsSuccess = false; resultado.Exception = new ApplicationLayerException<ParametroValorService>(e); } return resultado; }*/ /// <summary> /// Realiza la busqueda de Parametro Valor /// </summary> /// <param name="filtro">Filtro de Parametro Valor</param> /// <returns>Listado de parametro valor</returns> public ProcessResult<List<ParametroValorResponse>> BuscarParametroValor(ParametroValorRequest filtro) { ProcessResult<List<ParametroValorResponse>> resultado = new ProcessResult<List<ParametroValorResponse>>(); try { List<ParametroValorLogic> listado = parametroValorLogicRepository.BuscarParametroValor( filtro.CodigoParametro, filtro.IndicadorEmpresa, (filtro.CodigoEmpresa != null ? new Guid(filtro.CodigoEmpresa) : (Guid?)null), (filtro.CodigoSistema != null ? new Guid(filtro.CodigoSistema) : (Guid?)null), filtro.CodigoIdentificador, filtro.TipoParametro, filtro.CodigoSeccion, filtro.CodigoValor, filtro.Valor, filtro.EstadoRegistro); var listaParametroValor = new List<ParametroValorResponse>(); int? codigoParametro = null; if (listado.Count > 0) { codigoParametro = listado.FirstOrDefault().CodigoParametro; } var listSecciones = parametroSeccionService.BuscarParametroSeccion(new ParametroSeccionRequest() { CodigoParametro = codigoParametro }).Result; List<ParametroValorLogic> listaparametroValorRelacionado = new List<ParametroValorLogic>(); List<int> listaParametrosCargados = new List<int>(); foreach (ParametroSeccionResponse seccionActual in listSecciones) { //para ver si tiene parametro relacionado //tambien vemos que no lo tengamos cargado if (seccionActual.CodigoParametroRelacionado != null && !listaParametrosCargados.Contains(seccionActual.CodigoParametroRelacionado.Value)) { var parametroValorRelacionado = parametroValorLogicRepository.BuscarParametroValor(seccionActual.CodigoParametroRelacionado, null, null, null, null, null, null, null, null, DatosConstantes.EstadoRegistro.Activo); listaparametroValorRelacionado.AddRange(parametroValorRelacionado); } } ParametroValorResponse parametroValor = new ParametroValorResponse(); parametroValor.RegistroCadena = new Dictionary<string, string>(); parametroValor.RegistroObjeto = new Dictionary<string, object>(); for (var iterator = 0; iterator < listado.Count; iterator++) { var itemValue = listado[iterator]; var seccionActual = listSecciones.Where(itemSeccion => itemSeccion.CodigoSeccion == itemValue.CodigoSeccion).FirstOrDefault(); if (seccionActual != null) { string valorTexto = ParametroValorAdapter.ObtenerParametroValorTexto(itemValue.CodigoTipoDato, itemValue.Valor); object valorObject = ParametroValorAdapter.ObtenerParametroValorObjeto(itemValue.CodigoTipoDato, itemValue.Valor); //Asginación de la Sección con su respectivo Valor Original parametroValor.RegistroCadena.Add(itemValue.CodigoSeccion.ToString(), valorTexto); parametroValor.RegistroObjeto.Add(itemValue.CodigoSeccion.ToString(), valorObject); //Asginación de la Sección con su respectivo Valor Relacionado if (seccionActual.CodigoParametroRelacionado != null && seccionActual.CodigoSeccionRelacionado != null && seccionActual.CodigoSeccionRelacionadoMostrar != null) { var codigoValorRelacionado = listaparametroValorRelacionado.Where(itemWhere => itemWhere.CodigoSeccion == seccionActual.CodigoSeccionRelacionado && itemWhere.Valor == valorTexto).Select(itemSelect => itemSelect.CodigoValor).FirstOrDefault(); var valorRelacionado = listaparametroValorRelacionado.Where(itemWhere => itemWhere.CodigoValor == codigoValorRelacionado && itemWhere.CodigoSeccion == seccionActual.CodigoSeccionRelacionadoMostrar).FirstOrDefault() ?? new ParametroValorLogic(); object valorObjectRelacionado = ParametroValorAdapter.ObtenerParametroValorObjeto(valorRelacionado.CodigoTipoDato, valorRelacionado.Valor); string valorTextoRelacionado = ParametroValorAdapter.ObtenerParametroValorTexto(valorRelacionado.CodigoTipoDato, valorRelacionado.Valor); parametroValor.RegistroCadena.Add("-" + itemValue.CodigoSeccion.ToString(), valorTextoRelacionado); parametroValor.RegistroObjeto.Add("-" + itemValue.CodigoSeccion.ToString(), valorObjectRelacionado); } //Asginación del Estado de Registro if (parametroValor.EstadoRegistro == null || parametroValor.EstadoRegistro == DatosConstantes.EstadoRegistro.Inactivo) { parametroValor.EstadoRegistro = itemValue.EstadoRegistro; } //Añade el registro en la Lista de Parametros según su quiebre if (iterator == listado.Count - 1 || itemValue.CodigoValor != listado[iterator + 1].CodigoValor) { parametroValor.CodigoValor = itemValue.CodigoValor; parametroValor.CodigoIdentificador = itemValue.CodigoIdentificador; parametroValor.CodigoParametro = itemValue.CodigoParametro; var seccionesFaltante = listSecciones.Where(itemWhere => !parametroValor.RegistroCadena.Any(itemAny => itemAny.Key == itemWhere.CodigoSeccion.ToString())).ToList(); foreach (var seccion in seccionesFaltante) { //Setear la Sección con su respectivo Valor parametroValor.RegistroCadena.Add(seccion.CodigoSeccion.ToString(), null); parametroValor.RegistroObjeto.Add(seccion.CodigoSeccion.ToString(), null); } listaParametroValor.Add(parametroValor); //Limpiar variable parametroValor = new ParametroValorResponse(); parametroValor.RegistroCadena = new Dictionary<string, string>(); parametroValor.RegistroObjeto = new Dictionary<string, object>(); } } } resultado.Result = listaParametroValor; } catch (Exception e) { resultado.Result = new List<ParametroValorResponse>(); resultado.IsSuccess = false; resultado.Exception = new ApplicationLayerException<ParametroValorService>(e); } return resultado; } /// <summary> /// Realiza la busqueda de Parametro Valor /// </summary> /// <param name="filtro">Filtro de Parametro Valor</param> /// <returns>Listado de parametro valor dinamico</returns> public ProcessResult<List<dynamic>> BuscarParametroValorDinamico(ParametroValorRequest filtro) { #region Antiguo //var parametroValor = this.BuscarParametroValor(filtro); //var listaDinamica = new List<dynamic>(); //parametroValor.Result.ForEach(p => //{ // var expandoObject = new ExpandoObject(); // var expandoDictionary = (IDictionary<string, object>)expandoObject; // if (p.RegistroObjeto != null) // { // foreach (var campo in p.RegistroObjeto) // { // expandoDictionary.Add("Atributo" + campo.Key, campo.Value); // } // listaDinamica.Add((dynamic)expandoObject); // } //}); #endregion #region Mejorado var listaDinamica = new List<dynamic>(); DataTable listado = parametroValorLogicRepository.BuscarParametroValorMejorado( filtro.CodigoParametro, filtro.IndicadorEmpresa, (filtro.CodigoEmpresa != null ? new Guid(filtro.CodigoEmpresa) : (Guid?)null), (filtro.CodigoSistema != null ? new Guid(filtro.CodigoSistema) : (Guid?)null), filtro.CodigoIdentificador, filtro.TipoParametro, filtro.CodigoSeccion, filtro.CodigoValor, filtro.Valor, filtro.EstadoRegistro); foreach (DataRow row in listado.Rows) { int key = 1; var expandoObject = new ExpandoObject(); var expandoDictionary = (IDictionary<string, object>)expandoObject; foreach (DataColumn column in listado.Columns) { expandoDictionary.Add("Atributo" + key.ToString(), row[column]); key += 1; } listaDinamica.Add((dynamic)expandoObject); } #endregion var resultado = new ProcessResult<List<dynamic>>(); resultado.Result = listaDinamica; return resultado; } /// <summary> /// Realiza el registro de un de Parametro Valor /// </summary> /// <param name="filtro">Parametro Valor a Registrar</param> /// <returns>Indicador de Error</returns> public ProcessResult<string> RegistrarParametroValor(ParametroValorRequest filtro) { string result = "0"; var resultadoProceso = new ProcessResult<string>(); try { var listSecciones = parametroSeccionService.BuscarParametroSeccion(new ParametroSeccionRequest() { CodigoParametro = filtro.CodigoParametro }).Result; int codigoValor = 0; bool isActualizacion = false; if (filtro.CodigoValor == null) { var ultimoParametroValor = BuscarParametroValor(new ParametroValorRequest() { CodigoParametro = filtro.CodigoParametro, EstadoRegistro = null }).Result.OrderBy(itemOrderBy => itemOrderBy.CodigoValor).LastOrDefault(); if (ultimoParametroValor != null) { codigoValor = ultimoParametroValor.CodigoValor + 1; } else { codigoValor = 1; } } else { codigoValor = (int)filtro.CodigoValor; isActualizacion = true; } using (TransactionScope scope = new TransactionScope()) { try { foreach (var item in filtro.RegistroCadena) { bool isSeccionExistente = false; var seccionActual = listSecciones.Where(itemWhere => itemWhere.CodigoSeccion.ToString() == item.Key).FirstOrDefault(); ParametroValorResponse parametroValorActual = null; if (isActualizacion) { parametroValorActual = BuscarParametroValor(new ParametroValorRequest() { CodigoParametro = filtro.CodigoParametro, CodigoSeccion = seccionActual.CodigoSeccion, CodigoValor = codigoValor }).Result.FirstOrDefault(); isSeccionExistente = (parametroValorActual != null) ? true : false; } string value = ""; switch (seccionActual.CodigoTipoDato) { case "ENT": value = item.Value; break; case "DEC": value = item.Value.Replace(',', '.'); break; case "FEC": value = item.Value; break; default: value = item.Value; break; } ParametroValorLogic logic = new ParametroValorLogic(); logic.CodigoParametro = (int)filtro.CodigoParametro; logic.CodigoSeccion = seccionActual.CodigoSeccion; logic.CodigoValor = codigoValor; logic.Valor = value; if (!isActualizacion || !isSeccionExistente) { logic.EstadoRegistro = DatosConstantes.EstadoRegistro.Activo; if (parametroValorLogicRepository.RegistrarParametroValor(logic) <= 0) { throw new Exception(); } } else { logic.EstadoRegistro = null; if (parametroValorLogicRepository.ModificarParametroValor(logic) <= 0) { throw new Exception(); } } } scope.Complete(); resultadoProceso.Result = "1"; resultadoProceso.IsSuccess = true; } catch (Exception e) { scope.Dispose(); throw e; } } } catch (Exception) { result = "-1"; resultadoProceso.Result = result; resultadoProceso.IsSuccess = false; } return resultadoProceso; } /// <summary> /// Realiza el eliminar de un de Parametro Valor /// </summary> /// <param name="filtro">Parametro Valor a Eliminar</param> /// <returns>Indicador de Error</returns> public ProcessResult<string> EliminarParametroValor(ParametroValorRequest filtro) { string result = "0"; var resultadoProceso = new ProcessResult<string>(); try { var parametroActual = parametroService.BuscarParametro(new ParametroRequest() { CodigoParametro = filtro.CodigoParametro }).Result.FirstOrDefault(); if (!parametroActual.IndicadorPermiteEliminar) { result = "2"; resultadoProceso.Result = result; resultadoProceso.IsSuccess = false; return resultadoProceso; } var parametroValorActual = BuscarParametroValor(new ParametroValorRequest() { CodigoParametro = filtro.CodigoParametro, CodigoValor = filtro.CodigoValor }).Result.FirstOrDefault(); foreach (var item in parametroValorActual.RegistroCadena) { ParametroValorLogic logic = new ParametroValorLogic(); logic.CodigoParametro = parametroValorActual.CodigoParametro; logic.CodigoSeccion = Convert.ToInt32(item.Key); logic.CodigoValor = parametroValorActual.CodigoValor; logic.Valor = null; logic.EstadoRegistro = DatosConstantes.EstadoRegistro.Inactivo; if (parametroValorLogicRepository.ModificarParametroValor(logic) <= 0) { throw new Exception(); } } resultadoProceso.Result = "1"; resultadoProceso.IsSuccess = true; } catch (Exception) { result = "-1"; resultadoProceso.Result = result; resultadoProceso.IsSuccess = false; } return resultadoProceso; } /// <summary> /// Realiza el eliminar de un de Parametro Valor /// </summary> /// <param name="filtro">Lista de Parametro Valor a Eliminar</param> /// <returns>Indicador de Error</returns> public ProcessResult<string> EliminarMasivoParametroValor(List<ParametroValorRequest> filtro) { string result = "0"; var resultadoProceso = new ProcessResult<string>(); try { using (TransactionScope scope = new TransactionScope()) { try { foreach (var item in filtro) { var resultItem = EliminarParametroValor(item); if (!resultItem.IsSuccess) { throw new Exception(); } } scope.Complete(); } catch (Exception e) { scope.Dispose(); throw e; } } resultadoProceso.Result = "1"; resultadoProceso.IsSuccess = true; } catch (Exception) { result = "-1"; resultadoProceso.Result = result; resultadoProceso.IsSuccess = false; } return resultadoProceso; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Search_for_a_Number { class Program { static void Main(string[] args) { List<int> numbers = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); int[] manipulator = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); List<int> resultList = numbers.Take(manipulator[0]).ToList(); resultList.RemoveRange(0, manipulator[1]); if (resultList.Contains(manipulator[2])) { Console.WriteLine("YES!"); } else { Console.WriteLine("NO!"); } // second example 60 % only /* List<int> numbers = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); int[] manipulator = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); numbers.RemoveRange(manipulator[0] + 1, (numbers.Count - 1) - manipulator[0]); numbers.RemoveRange(0, manipulator[1]); if (numbers.Contains(manipulator[2])) { Console.WriteLine("YES!"); } else { Console.WriteLine("NO!"); } */ } } }
using Clases; using LogicaNegocio; using ProyectoLP2; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Formularios { public partial class frmAdministrarComisionVendedores : Form { private UsuarioBL usuarioBL; private PagoBL pagoBL; public frmAdministrarComisionVendedores() { InitializeComponent(); CargarVendedores(); btnPagar.Enabled = false; dgvpagos.DataSource = pagoBL.listar_todos_Pagos(); txtTotalComision.Text = "0.0"; } private void CargarVendedores() { usuarioBL = new UsuarioBL(); BindingList<Persona> vendedores = new BindingList<Persona>(); vendedores = usuarioBL.listarVendedores(); cbxvendedores.ValueMember = "Dni"; cbxvendedores.DisplayMember = "Nombre"; cbxvendedores.DataSource = vendedores; cbxvendedores.SelectedIndex = -1; } private void btnRegresar_Click(object sender, EventArgs e) { Close(); } private void button1_Click(object sender, EventArgs e) { string dni = cbxvendedores.SelectedValue.ToString(); double montototal = pagoBL.calcular_monto(pagoBL.listarPagos(dni)); txtTotalComision.Text = montototal.ToString(); var v = MessageBox.Show("¿Desea confirmar el pago al vendedor por el monto de "+montototal+"?", "confirmacion",MessageBoxButtons.OKCancel); if (v == DialogResult.OK) { if (cbxvendedores.SelectedIndex != -1) { btnPagar.Enabled = true; //se insertan en una tabla las info del pago que esta hecho pagoBL.insertarPago(pagoBL.listarPagos(dni),dni); //se cambia el estado de la factura pagoBL.cambiarEstado(pagoBL.listarPagos(dni)); dgvpagos.DataSource = pagoBL.listarPagos(dni); } } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void cbxvendedores_SelectedIndexChanged(object sender, EventArgs e) { pagoBL = new PagoBL(); string dni = ""; if (cbxvendedores.SelectedIndex != -1) { btnPagar.Enabled = true; dni = cbxvendedores.SelectedValue.ToString(); dgvpagos.AutoGenerateColumns = false; dgvpagos.DataSource = pagoBL.listarPagos(dni); double montototal = pagoBL.calcular_monto(pagoBL.listarPagos(dni)); txtTotalComision.Text = montototal.ToString(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using TravelBuddySite.DAL; using TravelBuddySite.Handlers; using TravelBuddySite.Models; namespace TravelBuddySite.Controllers { public class LoginController : Controller { private MainContext db = new MainContext(); // GET: Login public ActionResult Index() { return View(); } // Checks if the user exists and initializing the user sessions if exists [HttpPost] public ActionResult Login(User u) { // Find the user cardentials in db var v = db.Users.Where(a => a.Username.Equals(u.Username) && a.Password.Equals(u.Password)).FirstOrDefault(); // Creats seesion for user id and name if (v != null) { TempData["LoginStatus"] = null; Session["LogedUserID"] = v.Id.ToString(); Session["LogedUsername"] = v.Username.ToString(); // Checks if the user is manager if (v.IsManager) { Session["manager"] = 1; } // The user is sent to the home page return RedirectToAction("Index", "Home"); } // Login failes else { ModelState.AddModelError("", "Login data is incorrect!"); TempData["LoginStatus"] = "Failiure"; return View("~/Views/Login/Index.cshtml"); } } // The function deletes the user sessions public ActionResult Logout() { // Free user sessions if ( Session["LogedUserID"]!=null) { Session["LogedUsername"] = null; Session["LogedUserID"] = null; } // Free manager session if (SessionsHandler.IsManager(Session)) { Session["manager"] = null; } return RedirectToAction("Index","Home"); } } }
using UnityEngine.UI; using UnityEngine; public class planeSelecter : MonoBehaviour { public GameObject[] planes; public Button[] buttons; public Text[] planeText; public Text mainText; Animation an,an2,anPre,anNext; string msg; public GameObject tick, warning; bool success=false; public GameObject soundOff, soundOn; int scrollPointer=1; public GameObject SCrollOBj; public Button PRE, NXT; public GameObject PREan, NXTan; public GameObject otherGames; // Start is called before the first frame update void Start() { PRE.interactable = false; tick.SetActive(false); warning.SetActive(false); msg = ""; an = mainText.GetComponent<Animation>(); an2 = SCrollOBj.GetComponent<Animation>(); anPre = PREan.GetComponent<Animation>(); anNext = NXTan.GetComponent<Animation>(); CheckForSound(); planePointerFn(); } public void planePointerFn() { int pnt= PlayerPrefs.GetInt("planePointer"); if(pnt==0) ActivatePlane(0); if (pnt == 1) ActivatePlane(1); if (pnt == 2) ActivatePlane(2); if (pnt == 3) ActivatePlane(3); if (pnt == 4) ActivatePlane(4); } public void selecctAPlane(int i) { int lvl= PlayerPrefs.GetInt("gameLevel"); if (i == 0) { success = true; ActivatePlane(0); PlayerPrefs.SetInt("planePointer",0); msg = "SELECTED"; showMsgFn(); } else if (i == 1) { if (lvl >= 10) { ActivatePlane(1); success = true; PlayerPrefs.SetInt("planePointer", 1); msg = "SELECTED"; showMsgFn(); } else { msg = " CLEAR LEVEL 10"; showMsgFn(); success = false; } }else if (i == 2) { if (lvl >= 20) { ActivatePlane(2); success = true; PlayerPrefs.SetInt("planePointer", 2); msg = "SELECTED"; showMsgFn(); } else { msg = " CLEAR LEVEL 20"; showMsgFn(); success = false; } } else if (i == 3) { if (lvl >= 40) { ActivatePlane(3); success = true; PlayerPrefs.SetInt("planePointer", 3); msg = "SELECTED"; showMsgFn(); } else { msg = " CLEAR LEVEL 40"; showMsgFn(); success = false; } } else if (i == 4) { if (lvl >= 50) { PlayerPrefs.SetInt("planePointer", 4); ActivatePlane(4); success = true; msg = "SELECTED"; showMsgFn(); } else { msg = "CLEAR LEVEL 50"; showMsgFn(); success = false; } } } void ActivatePlane(int x) { //activate planes for (int i = 0; i < planes.Length; i++) { if (i == x) planes[i].SetActive(true); else planes[i].SetActive(false); } //change color of button /* for (int i = 0; i < planes.Length; i++) { if (i == x) buttons[i].GetComponent<Image>().color = Color.green; else buttons[i].GetComponent<Image>().color = Color.white; }*/ //change text for (int i = 0; i < planes.Length; i++) { if (i == x) planeText[i].text = "SELECTED"; else planeText[i].text = "SELECT"; } } void showMsgFn() { an.Play("planeText3D"); Invoke("showMsg",0.5f); } void showMsg() { if (success) { tick.SetActive(true); warning.SetActive(false); } else { tick.SetActive(false); warning.SetActive(true); } mainText.text = msg; an.Play("planeText3Dcome"); } public void CheckForSound() { if (PlayerPrefs.GetInt("sound") == 1) { AudioListener.volume = 0f; soundOff.SetActive(true); soundOn.SetActive(false); } else { AudioListener.volume = 1f; soundOff.SetActive(false); soundOn.SetActive(true); } } public void soundOnClicked() { AudioListener.volume = 0f; soundOff.SetActive(true); soundOn.SetActive(false); PlayerPrefs.SetInt("sound", 1); } public void soundOffClicked() { AudioListener.volume = 1f; soundOff.SetActive(false); soundOn.SetActive(true); PlayerPrefs.SetInt("sound", 0); } public void nextBtnClicked() { anNext.Play("PreNextBtnClicked"); if (scrollPointer == 1) { an2.Play("1_2"); scrollPointer = 2;PRE.interactable = true; }else if (scrollPointer == 2) { an2.Play("2_3"); scrollPointer = 3; }else if (scrollPointer == 3) { an2.Play("3_4"); scrollPointer = 4; }else if (scrollPointer == 4) { an2.Play("4_5"); scrollPointer = 5; NXT.interactable = false; } } public void preBtnClicked() { anPre.Play("PreNextBtnClicked"); if (scrollPointer == 5) { an2.Play("5_4"); scrollPointer = 4; NXT.interactable = true; } else if (scrollPointer == 4) { an2.Play("4_3"); scrollPointer = 3; } else if (scrollPointer == 3) { an2.Play("3_2"); scrollPointer = 2; } else if (scrollPointer == 2) { an2.Play("2_1"); scrollPointer = 1; PRE.interactable = false; } } public void otherGamesFn() { otherGames.SetActive(true); } public void HordenPass() { Application.OpenURL("https://apps.apple.com/us/app/horden-pass/id1453519752"); //ios https://apps.apple.com/us/app/horden-pass/id1453519752 //android https://play.google.com/store/apps/details?id=com.IneptDevs.HordenPass&hl=en_US } public void eddyBall() { Application.OpenURL("https://apps.apple.com/us/app/eddy-ball/id1453687434"); //ios https://apps.apple.com/us/app/eddy-ball/id1453687434 //android https://play.google.com/store/apps/details?id=com.IneptDevs.EddyBall&hl=en_US } public void DribbleUp() { Application.OpenURL("https://apps.apple.com/us/app/dribble-up/id1460474486"); //ios https://apps.apple.com/us/app/dribble-up/id1460474486 //android https://play.google.com/store/apps/details?id=com.IneptDevs.DribbleUp&hl=en_US } public void moreGames() { Application.OpenURL("https://apps.apple.com/us/developer/ravi-vohra/id1448125379"); //ios https://apps.apple.com/us/developer/ravi-vohra/id1448125379 //android https://play.google.com/store/apps/developer?id=Inept&hl=en_US } public void closeOtherGames() { otherGames.SetActive(false); } public void exitGame() { Application.Quit(); } } //PlayerPrefs.GetInt("planePointer");
using UnityEngine; namespace Interaction { public sealed class InteractableSwitch : InteractableBase { [SerializeField] private bool _state = false; private Animator _animator; private readonly int _hashActivated = Animator.StringToHash("Activated"); private void Awake() { _animator = GetComponent<Animator>(); if (_animator != null) _animator.SetBool(_hashActivated, _state); } public override void Interact() { _state = !_state; if (_animator != null) _animator.SetBool(_hashActivated, _state); } } }
namespace Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class Attributes : DbMigration { public override void Up() { CreateTable( "Web.JobInvoiceHeaderAttributes", c => new { Id = c.Int(nullable: false, identity: true), HeaderTableId = c.Int(nullable: false), DocumentTypeHeaderAttributeId = c.Int(nullable: false), Value = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("Web.DocumentTypeHeaderAttributes", t => t.DocumentTypeHeaderAttributeId) .ForeignKey("Web.JobInvoiceHeaders", t => t.HeaderTableId) .Index(t => t.HeaderTableId) .Index(t => t.DocumentTypeHeaderAttributeId); CreateTable( "Web.StockHeaderAttributes", c => new { Id = c.Int(nullable: false, identity: true), HeaderTableId = c.Int(nullable: false), DocumentTypeHeaderAttributeId = c.Int(nullable: false), Value = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("Web.DocumentTypeHeaderAttributes", t => t.DocumentTypeHeaderAttributeId) .ForeignKey("Web.StockHeaders", t => t.HeaderTableId) .Index(t => t.HeaderTableId) .Index(t => t.DocumentTypeHeaderAttributeId); } public override void Down() { DropForeignKey("Web.StockHeaderAttributes", "HeaderTableId", "Web.StockHeaders"); DropForeignKey("Web.StockHeaderAttributes", "DocumentTypeHeaderAttributeId", "Web.DocumentTypeHeaderAttributes"); DropForeignKey("Web.JobInvoiceHeaderAttributes", "HeaderTableId", "Web.JobInvoiceHeaders"); DropForeignKey("Web.JobInvoiceHeaderAttributes", "DocumentTypeHeaderAttributeId", "Web.DocumentTypeHeaderAttributes"); DropIndex("Web.StockHeaderAttributes", new[] { "DocumentTypeHeaderAttributeId" }); DropIndex("Web.StockHeaderAttributes", new[] { "HeaderTableId" }); DropIndex("Web.JobInvoiceHeaderAttributes", new[] { "DocumentTypeHeaderAttributeId" }); DropIndex("Web.JobInvoiceHeaderAttributes", new[] { "HeaderTableId" }); DropTable("Web.StockHeaderAttributes"); DropTable("Web.JobInvoiceHeaderAttributes"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using VirtualDiskCMD.FileSystems.VMFS1; namespace VirtualDiskCMD { /// <summary> /// Represents the VMFS1 file system format /// </summary> public class VMFS1Volume : VolumeInfo<VMFS1DirectoryInfo, VMFS1FileInfo>, ICollection<VMFS1FileTableRecord> { byte[] diskData; public bool Bootable { get; private set; } // Code to jump to the beginning of the bootstrap code for a bootable disk byte[] jump = new byte[] { 0x28, 0x00, 0x04, 0x00, 0x18, 0x28, 0x00, 0x00 }; private string volumeLabel; public string VolumeLabel { get { return volumeLabel; } set { if (value.Length > 8) throw new Exception(); volumeLabel = value; } } string fileSystemLabel = "VMFS1\0\0\0"; private List<byte> bootstrap = new List<byte>(); public byte[] Bootstrap { get { return bootstrap.ToArray(); } set { if (value.Length != 486) { bootstrap.Clear(); bootstrap.AddRange(value); } } } byte[] bootSignature = new byte[] { 0x66, 0xBB }; public VMFS1Volume(string volumeLabel) { VolumeLabel = volumeLabel; fileTable = new List<VMFS1FileTableRecord>(); } public VMFS1Volume(byte[] data) { diskData = data; byte[] s = new byte[8]; // Check boot signature and FS label // Get file system label Array.Copy(diskData, 16, s, 0, 8); string fsLabel = Encoding.UTF8.GetString(s); if (!((data[510] == 0x66) & (data[511] == 0xBB) & (fsLabel == "VMFS1\0\0\0"))) { throw new Exception("Invalid boot signature or file system label."); } // Get the jump code Array.Copy(diskData, 0, jump, 0, 8); // Get the volume label Array.Copy(diskData, 8, s, 0, 8); volumeLabel = Encoding.UTF8.GetString(s); // Get boostrap code byte[] a_bootstrap = new byte[486]; Array.Copy(diskData, 24, a_bootstrap, 0, 486); bootstrap.AddRange(a_bootstrap); // Get table fileTable = new List<VMFS1FileTableRecord>(); int offset = 512; byte[] filename = new byte[28]; byte[] startSector = new byte[2]; byte[] fileLength = new byte[2]; for (int i = 0; i < 2880; i++) { // Get the raw data Array.Copy(diskData, offset, filename, 0, 28); Array.Copy(diskData, offset + 28, startSector, 0, 2); Array.Copy(diskData, offset + 30, fileLength, 0, 2); // Convert the values ushort sector = BitConverter.ToUInt16(startSector, 0); ushort len = BitConverter.ToUInt16(fileLength, 0); // Get the file data byte[] fileData = new byte[len]; if (len > 0) { Array.Copy(diskData, sector * 512, fileData, 0, len); VMFS1FileTableRecord record = new VMFS1FileTableRecord(Encoding.UTF8.GetString(filename), sector, fileData); fileTable.Add(record); } offset = offset + 32; } } List<VMFS1FileTableRecord> fileTable; public VMFS1FileTableRecord[] FileTable { get { return fileTable.ToArray(); } } public VMFS1FileTableRecord this[int index] { get { if ((index >= 0) & (index < fileTable.Count)) return fileTable[index]; else throw new IndexOutOfRangeException(); } } public VMFS1FileTableRecord this[string filename] { get { for (int i = 0; i < fileTable.Count; i++) { if (fileTable[i].Name == filename) return fileTable[i]; } throw new IndexOutOfRangeException(); } set { for (int i = 0; i < fileTable.Count; i++) { if (fileTable[i].Name == filename) { fileTable[i] = value; return; } } throw new IndexOutOfRangeException(); } } public int Count => ((ICollection<VMFS1FileTableRecord>)fileTable).Count; public bool IsReadOnly => ((ICollection<VMFS1FileTableRecord>)fileTable).IsReadOnly; public override int Size { get { int size = 0; for (int i = 0; i < Count; i++) { size += this[i].Data.Length; } return size; } } public override int Attributes { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override int VolumeSize { get { return 1474560; } } public override string Name { get { return volumeLabel.Trim('\0'); } set { volumeLabel = value.Trim().PadRight(8, '\0'); } } public override string FullName { get { return volumeLabel.Trim('\0'); } } public override FileSystemInfo<VMFS1DirectoryInfo, VMFS1FileInfo> Parent { get { return null; } } public void Add(VMFS1FileTableRecord item) { ((ICollection<VMFS1FileTableRecord>)fileTable).Add(item); } public void Clear() { ((ICollection<VMFS1FileTableRecord>)fileTable).Clear(); } public bool Contains(VMFS1FileTableRecord item) { return ((ICollection<VMFS1FileTableRecord>)fileTable).Contains(item); } public void CopyTo(VMFS1FileTableRecord[] array, int arrayIndex) { ((ICollection<VMFS1FileTableRecord>)fileTable).CopyTo(array, arrayIndex); } public bool Remove(VMFS1FileTableRecord item) { return ((ICollection<VMFS1FileTableRecord>)fileTable).Remove(item); } public IEnumerator<VMFS1FileTableRecord> GetEnumerator() { return ((IEnumerable<VMFS1FileTableRecord>)fileTable).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)fileTable).GetEnumerator(); } public override byte[] ToBinary() { List<byte> value = new List<byte>(); value.AddRange(jump); value.AddRange(Encoding.UTF8.GetBytes(volumeLabel)); value.AddRange(new byte[8 - volumeLabel.Length]); value.AddRange(Encoding.UTF8.GetBytes(fileSystemLabel)); value.AddRange(new byte[8 - fileSystemLabel.Length]); value.AddRange(bootstrap); value.AddRange(bootSignature); if (value.Count != 512) throw new Exception(string.Format("Boot sector is not the correct length. ({0} bytes instead of 512 bytes)", value.Count)); // Build file table for (int i = 0; i < 2880; i++) { if (i < fileTable.Count) { value.AddRange(fileTable[i].RecordData); } else { value.AddRange(new byte[32]); } } if (value.Count != (2880 * 32) + 512) throw new Exception(string.Format("File table is not the correct length. ({0} bytes instead of 92572 bytes)", value.Count)); // Add file data for (int i = 0; i < fileTable.Count; i++) { value.AddRange(fileTable[i].Data); } byte[] padding = new byte[1474560 - value.Count]; value.AddRange(padding); return value.ToArray(); } public override VMFS1FileInfo[] GetFiles() { VMFS1FileInfo[] files = new VMFS1FileInfo[Count]; for (int i = 0; i < Count; i++) { files[i] = new VMFS1FileInfo(this, this[i]); } return files; } public bool Contains(string filename) { for (int i = 0; i < Count; i++) { if (this[i].Name == filename) return true; } return false; } public override void Create() { System.IO.File.WriteAllBytes(VolumeLabel.Trim() + ".bin", ToBinary()); } public override void Delete() { throw new NotImplementedException(); } public override void Copy(VMFS1DirectoryInfo destination, string newName = null) { throw new NotImplementedException(); } public override bool Exists() { throw new NotImplementedException(); } public override void Defragment() { ushort sector = 181; for (int i = 0; i < Count; i++) { VMFS1FileTableRecord record = fileTable[i]; record.StartSector = sector; fileTable[i] = record; int sectorLength = record.Data.Length / 512; if (record.Data.Length % 512 > 0) sectorLength++; sector = (ushort)(sector + sectorLength); } } public override void Rename(string name) { if (name.Length > 8) throw new ArgumentOutOfRangeException(); else volumeLabel = name.PadRight(8, '\0'); } public override DirectoryInfo<VMFS1DirectoryInfo, VMFS1FileInfo> CreateSubdirectory(string name) { throw new NotImplementedException(); } public override DirectoryInfo<VMFS1DirectoryInfo, VMFS1FileInfo>[] GetDirectories() { throw new NotImplementedException(); } public override FileInfo<VMFS1DirectoryInfo, VMFS1FileInfo> CreateFile(string name) { VMFS1FileInfo file = new VMFS1FileInfo(this, name); return file; } } public struct VMFS1FileTableRecord { string name; public string Name { get { return name; } set { if (value.Length <= 28) { name = value; } else { throw new Exception(); } } } public ushort StartSector { get; set; } public byte[] Data { get; set; } public byte[] RecordData { get { List<byte> value = new List<byte>(); value.AddRange(Encoding.UTF8.GetBytes(Name)); value.AddRange(new byte[28 - name.Length]); value.AddRange(BitConverter.GetBytes(StartSector)); value.AddRange(BitConverter.GetBytes((ushort)Data.Length)); // Convert to ushort to make the value 2 bytes instead of 4 return value.ToArray(); } } public VMFS1FileTableRecord(string name, ushort startSector, byte[] data) : this() { this.name = name; StartSector = startSector; Data = data; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using LINQ101MVC.Controllers; namespace LINQ101MVC.Models { [Table("Sales.CreditCard")] public partial class CreditCard { public int CreditCardID { get; set; } [Required] [StringLength(50)] public string CardType { get; set; } [Required] [StringLength(25)] public string CardNumber { get; set; } public byte ExpMonth { get; set; } public short ExpYear { get; set; } public DateTime ModifiedDate { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage","CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; } = new HashSet<SalesOrderHeader>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Assessment.Data; using Assessment.Models; using Microsoft.AspNetCore.Http; using System.IO; namespace Assessment.Controllers { public class FileUploadsController : Controller { private readonly ApplicationDbContext _context; public FileUploadsController(ApplicationDbContext context) { _context = context; } // GET: FileUploads public async Task<IActionResult> Index() { return View(await _context.FileUpload.ToListAsync()); } // GET: FileUploads/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var fileUpload = await _context.FileUpload .FirstOrDefaultAsync(m => m.EmpId == id); if (fileUpload == null) { return NotFound(); } return View(fileUpload); } // GET: FileUploads/Create public IActionResult Create() { return View(); } // POST: FileUploads/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("EmpId,EmpName,photo")] FileUpload fileUpload, IFormFile photo) { if (ModelState.IsValid) { string path = Environment.CurrentDirectory; string fullName = Path.Combine(path, "wwwroot", "Images",photo.FileName); fileUpload.photo = fullName; _context.Add(fileUpload); await _context.SaveChangesAsync(); if(photo.Length>0) { using(var stream = System.IO.File.Create(fullName)) { await photo.CopyToAsync(stream); } } return RedirectToAction(nameof(Index)); } return View(fileUpload); } // GET: FileUploads/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var fileUpload = await _context.FileUpload.FindAsync(id); if (fileUpload == null) { return NotFound(); } return View(fileUpload); } // POST: FileUploads/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("EmpId,EmpName,photo")] FileUpload fileUpload) { if (id != fileUpload.EmpId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(fileUpload); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FileUploadExists(fileUpload.EmpId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(fileUpload); } // GET: FileUploads/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var fileUpload = await _context.FileUpload .FirstOrDefaultAsync(m => m.EmpId == id); if (fileUpload == null) { return NotFound(); } return View(fileUpload); } // POST: FileUploads/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var fileUpload = await _context.FileUpload.FindAsync(id); _context.FileUpload.Remove(fileUpload); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool FileUploadExists(int id) { return _context.FileUpload.Any(e => e.EmpId == id); } } }
 using System; using System.Collections.Generic; using System.Linq; using TheMapToScrum.Back.DAL.Entities; using TheMapToScrum.Back.DTO; namespace TheMapToScrum.Back.BLL.Mapping { internal static class MapTeamDTO { internal static TeamDTO ToDto(Team objet) { TeamDTO retour = new TeamDTO(); if (objet != null) { retour.Id = objet.Id; retour.Label = objet.Label; retour.IsDeleted = objet.IsDeleted; retour.DateCreation = (System.DateTime)objet.DateCreation; retour.DateModification = (System.DateTime)objet.DateModification; } return retour; } internal static List<TeamDTO> ToDto(List<Team> liste) { //récupération de la liste d'entités TeamDTO transformés en entités List<TeamDTO> retour = new List<TeamDTO>(); retour = liste.Select(x => new TeamDTO() { Id = x.Id, Label = x.Label, DateCreation = (System.DateTime)x.DateCreation, DateModification = (System.DateTime)x.DateModification, IsDeleted = x.IsDeleted, }).ToList(); return retour; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows.Forms; namespace BikeRaceApp { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //Initializing Racemanager class and passing it through all the other classes RaceManager rm = new RaceManager(); //Loading Riders rm.LoadRiders(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMainMenu(rm)); } } }
namespace iPhoneController.Models { using System; using System.Collections.Generic; using System.IO; class TetheredDhcpLease { public const string DhcpClientLeasesFilePath = "/var/db/dhcp_leases"; // name public string Name { get; set; } // ip_address public string IpAddress { get; set; } // hw_address public string MacAddress { get; set; } public string Identifier { get; set; } // lease public string Lease { get; set; } public static List<TetheredDhcpLease> ParseDhcpLeases() { var list = new List<TetheredDhcpLease>(); if (!File.Exists(DhcpClientLeasesFilePath)) { Console.WriteLine($"DHCP client lease database at {DhcpClientLeasesFilePath} does not exist..."); return list; } var lines = File.ReadAllLines(DhcpClientLeasesFilePath); TetheredDhcpLease lease = null; foreach (var line in lines) { if (line.Contains("{")) { lease = new TetheredDhcpLease(); } else if (line.Contains("name=")) { lease.Name = line.Replace("name=", "").Trim('\t'); } else if (line.Contains("ip_address=")) { lease.IpAddress = line.Replace("ip_address=", "").Trim('\t'); } else if (line.Contains("hw_address=")) { lease.MacAddress = line.Replace("hw_address=", "").Trim('\t'); } else if (line.Contains("identifier=")) { lease.Identifier = line.Replace("identifier=", "").Trim('\t'); } else if (line.Contains("lease=")) { lease.Lease = line.Replace("lease=", "").Trim('\t'); } else if (line.Contains("}")) { list.Add(lease); } } return list; } } }
using EBS.Application.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Application { public interface IStocktakingPlanFacade { void Create(StocktakingPlanModel model); void Edit(StocktakingPlanModel model); void StartPlan(int id, int editedBy, string editor); void MergeDetial(int id, int editedBy, string editor); void EndPlan(int id, int editedBy, string editor, string loginPassword); void Cancel(int id, int editedBy, string editor,string reason); } }
using System; using System.Collections.Generic; using System.Web.Http; using AutoMapper; using Conditions.Guards; using Properties.Core.Interfaces; using Properties.Core.Objects; using Properties.Helper; using LandlordSearchParameter = Properties.Models.LandlordSearchParameter; using PropertySummary = Properties.Models.PropertySummary; using SearchParameter = Properties.Models.SearchParameter; using SearchResult = Properties.Models.SearchResult; using Property = Properties.Models.Property; using LandlordSummary = Properties.Models.LandlordSummary; namespace Properties.Controllers { public class SearchController : ApiController { private readonly ISearchService _propertySearchService; private readonly ILandlordSearchService _landlordSearchService; public SearchController(ISearchService propertySearchService, ILandlordSearchService landlordSearchService) { Check.If(propertySearchService).IsNotNull(); Check.If(landlordSearchService).IsNotNull(); _propertySearchService = propertySearchService; _landlordSearchService = landlordSearchService; } [HttpPost, Route("api/propertysearch")] public List<SearchResult> Post(List<SearchParameter> searchParameters, string orderBy = "Most Expensive", string filter = "Available") { Check.If(searchParameters).IsNotNull(); return Mapper.Map<List<SearchResult>>( _propertySearchService.Search(Mapper.Map<List<Core.Objects.SearchParameter>>(searchParameters), EnumHelper<Ordering>.Parse(orderBy), EnumHelper<Filtering>.Parse(filter))); } [HttpPost, Route("api/fullpropertysearch")] public List<Property> Search(List<SearchParameter> searchParameters, string orderBy = "Most Expensive", string filter = "Available") { Check.If(searchParameters).IsNotNull(); return Mapper.Map<List<Property>>( _propertySearchService.FullSearch(Mapper.Map<List<Core.Objects.SearchParameter>>(searchParameters), EnumHelper<Ordering>.Parse(orderBy), EnumHelper<Filtering>.Parse(filter))); } [HttpPost, Route("api/fullpropertysearch/v2")] public List<PropertySummary> SearchV2(List<SearchParameter> searchParameters, string orderBy = "Most Expensive", string filter = "Available") { Check.If(searchParameters).IsNotNull(); return Mapper.Map<List<PropertySummary>>( _propertySearchService.FullSearchV1(Mapper.Map<List<Core.Objects.SearchParameter>>(searchParameters), EnumHelper<Ordering>.Parse(orderBy), EnumHelper<Filtering>.Parse(filter))); } [HttpPost, Route("api/landlordsearch")] public List<LandlordSummary> Search(List<LandlordSearchParameter> searchParameters) { Check.If(searchParameters).IsNotNull(); return Mapper.Map<List<LandlordSummary>>( _landlordSearchService.Search( Mapper.Map<List<Core.Objects.LandlordSearchParameter>>(searchParameters))); } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; using App.Core.Interfaces.Dto; using App.Core.Interfaces.Dto.Responses; using App.Core.Interfaces.Errors; using App.Core.Interfaces.Managers; using Easy.MessageHub; using ImpromptuInterface; using Microsoft.AspNetCore.SignalR; using SimpleInjector; namespace App.Web.SignalR { internal class DynamicClient : DynamicObject { private IClientProxy Client { get; } public DynamicClient(IClientProxy client) { Client = client; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = Client.SendCoreAsync(binder.Name, args); return true; } } public abstract class AsyncApi<TServer, TClient> : Hub where TServer : class where TClient : class { protected TClient GetClient(IClientProxy c) => Impromptu.ActLike<TClient>(new DynamicClient(c)); } public interface INotificationServer { Task Connect(string token); } public interface INotificationClient { Task Error(NotificationDto notification); Task CreateMessage(NotificationDto notification); Task UpdateMessage(NotificationDto notification); Task DeleteMessage(NotificationDto notification); Task AddUserToChat(NotificationDto notification); Task RemoveUserFromChat(NotificationDto notification); } public class NotificationsHub : AsyncApi<INotificationServer, INotificationClient>, INotificationServer { protected IChatManager ChatManager { get; } protected IMessageManager MessageManager { get; } protected ISessionManager SessionManager { get; } protected IMessageHub MessageHub { get; } public NotificationsHub(Container container) { ChatManager = container.GetInstance<IChatManager>(); MessageManager = container.GetInstance<IMessageManager>(); SessionManager = container.GetInstance<ISessionManager>(); MessageHub = container.GetInstance<IMessageHub>(); } public override Task OnDisconnectedAsync(Exception exception) { if (Context.Items.ContainsKey("subscription")) { var subscription = (Guid) Context.Items["subscription"]; MessageHub.Unsubscribe(subscription); } return base.OnDisconnectedAsync(exception); } public async Task Connect(string token) { await GetClient(Clients.All).Error(new NotificationDto { Type = NotificationType.Error, ErrorCode = StatusCode.InternalError }); var ctx = Context.Items; var client = Clients.Caller; try { var session = SessionManager.GetSessionByToken(token); ctx["userId"] = session.UserId; ctx["token"] = token; var chats = ChatManager.GetUserChats(session.User); ctx["chatIds"] = chats.Select(c => c.ChatId).ToList().ToHashSet(); var subscription = MessageHub.Subscribe<NotificationDto>(notification => { if (notification.TargetUserId != null && (int) ctx["userId"] == notification.TargetUserId.Value || notification.TargetChatId != null && ((HashSet<int>) ctx["chatIds"]).Contains(notification.TargetChatId.Value)) { switch (notification.Type) { case NotificationType.AddUserToChat: { var chatId = ((ChatDto) notification.Data[typeof(ChatDto)].List.First().Value) .ChatId; ((HashSet<int>) ctx["chatIds"]).Add(chatId); break; } case NotificationType.RemoveUserFromChat: { var chatId = ((ChatDto) notification.Data[typeof(ChatDto)].List.First().Value) .ChatId; ((HashSet<int>) ctx["chatIds"]).Remove(chatId); break; } } client.SendCoreAsync(notification.Type.ToString(), new object[] { notification }); } }); ctx["subscription"] = subscription; } catch (ServiceException e) { // TODO. } } } }
#if REPLICA_DISABLING_NET5_ONLY using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using DFC.ServiceTaxonomy.Neo4j.Commands.Interfaces; using DFC.ServiceTaxonomy.Neo4j.Queries.Interfaces; using DFC.ServiceTaxonomy.Neo4j.Services.Internal; using Microsoft.Extensions.Logging; using FakeItEasy; using Xunit; namespace DFC.ServiceTaxonomy.UnitTests.Neo4j.Services.Internal { public class GraphTests { internal Graph Graph { get; set; } internal INeoEndpoint NeoEndpoint { get; set; } internal ILogger Logger { get; set; } internal IQuery<int>[] Queries { get; set; } internal ICommand[] Commands { get; set; } internal ManualResetEventSlim TestFinished { get; set; } internal const string GraphName = "Steffi"; internal const bool DefaultGraph = true; public GraphTests() { NeoEndpoint = A.Fake<INeoEndpoint>(); Logger = A.Fake<ILogger>(); Graph = new Graph(NeoEndpoint, GraphName, DefaultGraph, 0, Logger); Queries = new[] {A.Fake<IQuery<int>>()}; Commands = new[] {A.Fake<ICommand>()}; TestFinished = new ManualResetEventSlim(false); } [Fact] public async Task InFlightCount_RunQueries_CountMatchesInFlightQueries() { // arrange const int inFlightRuns = 10; A.CallTo(() => NeoEndpoint.Run(Queries, GraphName, DefaultGraph)) .ReturnsLazily(() => { TestFinished.Wait(); return new List<int>(); }); var tasks = Enumerable.Range(0, inFlightRuns).Select(i => Task.Run(() => Graph.Run(Queries))); await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(2000)); // act + assert Assert.Equal((ulong)inFlightRuns, Graph.InFlightCount); // clean up TestFinished.Set(); await Task.WhenAll(tasks); } [Fact] public async Task InFlightCount_RunCommands_CountMatchesInFlightCommands() { // arrange const int inFlightRuns = 10; A.CallTo(() => NeoEndpoint.Run(Commands, GraphName, DefaultGraph)) .ReturnsLazily(() => { TestFinished.Wait(); return Task.CompletedTask; }); var tasks = Enumerable.Range(0, inFlightRuns).Select(i => Task.Run(() => Graph.Run(Commands))); await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(2000)); // act + assert Assert.Equal((ulong)inFlightRuns, Graph.InFlightCount); // clean up TestFinished.Set(); await Task.WhenAll(tasks); } [Fact] public async Task InFlightCount_RunQueriesAndCommands_CountMatchesInFlightQueries() { // arrange const int inFlightQueryRuns = 5; const int inFlightCommandRuns = 5; A.CallTo(() => NeoEndpoint.Run(Queries, GraphName, DefaultGraph)) .ReturnsLazily(() => { TestFinished.Wait(); return new List<int>(); }); A.CallTo(() => NeoEndpoint.Run(Commands, GraphName, DefaultGraph)) .ReturnsLazily(() => { TestFinished.Wait(); return Task.CompletedTask; }); var queryTasks = Enumerable.Range(0, inFlightQueryRuns).Select(i => Task.Run(() => Graph.Run(Queries))); var commandTasks = Enumerable.Range(0, inFlightCommandRuns).Select(i => Task.Run(() => Graph.Run(Commands))); await Task.WhenAny(Task.WhenAll(queryTasks), Task.WhenAll(commandTasks), Task.Delay(2000)); // act + assert Assert.Equal((ulong)inFlightQueryRuns + inFlightCommandRuns, Graph.InFlightCount); // clean up TestFinished.Set(); await Task.WhenAll(Task.WhenAll(queryTasks), Task.WhenAll(commandTasks)); } [Fact] public void InFlightCount_RunQueriesThrewException_CountIs0() { A.CallTo(() => NeoEndpoint.Run(Queries, GraphName, DefaultGraph)) .Throws<Exception>(); Assert.Equal(0ul, Graph.InFlightCount); } [Fact] public void InFlightCount_RunCommandsThrewException_CountIs0() { A.CallTo(() => NeoEndpoint.Run(Commands, GraphName, DefaultGraph)) .Throws<Exception>(); Assert.Equal(0ul, Graph.InFlightCount); } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace KartExchangeEngine { public class FileMaskMonitor:AbstractFlagMonitor { /// <summary> /// Маска файла для проведения импорта /// </summary> public string ImportFileMask { get; set; } /// <summary> /// Маска файла для проведения экспорта /// </summary> public string ExportFileMaskFlag { get; set; } public string ImportFileFlag { get; set; } /// <summary> /// Строка подключения /// </summary> public string ConnectionString { get; set; } /// <summary> /// Каталог входных файлов /// </summary> public string InDir { get; set; } /// <summary> /// Каталог выходных файлов /// </summary> public string OutDir { get; set; } public FileMaskMonitor() { } public FileMaskMonitor(string dirName, string fileMask) { DirName = dirName; ImportFileMask = fileMask; } public FileMaskMonitor(string connectionString, string fileName, string dirName) { DirName = dirName; ConnectionString = connectionString; ImportFileMask = fileName; } public FileMaskMonitor(string connectionString, string _InDir, string _OutDir, string FileMask) { ConnectionString = connectionString; DirName = InDir = _InDir; ImportFileMask = ExportFileMaskFlag = FileMask; OutDir = _OutDir; } public FileMaskMonitor(string connectionString, string _InDir, string _OutDir, string FileMask, DateTime _LastMonitorDate) { ConnectionString = connectionString; DirName = InDir = _InDir; ImportFileMask = ExportFileMaskFlag = FileMask; OutDir = _OutDir; LastMonitorDate = _LastMonitorDate; } public FileMaskMonitor(string connectionString, string fileName, string dirName, string exportFileMask,string importFileFlag) { DirName = dirName; ConnectionString = connectionString; ImportFileMask = fileName; ExportFileMaskFlag = exportFileMask; ImportFileFlag = importFileFlag; } public override bool CheckImportCondition() { bool result = false; DataList = new List<string>(); DirectoryInfo di = new DirectoryInfo(DirName); FileInfo[] fi = di.GetFiles(ImportFileMask).OrderBy(q => q.FullName).ToArray(); result = File.Exists(FlagFile) && (fi.Count() > 0); if (result) { File.Delete(FlagFile); foreach (FileInfo fileName in fi) { DataList.Add(fileName.Name); } } return result; } public override bool CheckExportCondition() { //return File.Exists(ExportFileMaskFlag); bool result = false; DataList = new List<string>(); DirectoryInfo di = new DirectoryInfo(OutDir); FileInfo[] fi = di.GetFiles(ExportFileMaskFlag).OrderBy(q => q.FullName).ToArray(); result = File.Exists(FlagFile) && (fi.Count() > 0); if (result) { File.Delete(FlagFile); foreach (FileInfo fileName in fi) { DataList.Add(fileName.Name); } } return result; } public string FlagFile { get { if (ImportFileFlag == null) { FileStream fs= File.Create(DirName + @"\import.flg"); fs.Close(); return DirName + @"\import.flg"; } else if (ImportFileFlag == "") { FileStream fs = File.Create(DirName + @"\import.flg"); fs.Close(); return DirName + @"\import.flg"; } else return DirName + @"\" + ImportFileFlag; } } } }
using Assets.src.battle; using Assets.src.managers; using strange.extensions.command.impl; using UnityEngine; namespace Assets.src.commands { public class TryManualMoveToPositionCommand : Command { [Inject] public Vector3 Position { get; set; } [Inject] public ISelectionManager SelectionManager { get; set; } [Inject] public IGameManager GameManager { get; set; } public override void Execute() { //if (GameManager.IsControlBlocked()) // return; foreach (var selectedObject in SelectionManager.GetSelectedObjects()) { var unit = selectedObject.GetModel() as UnitModel; if (unit != null/* && unit.IsManualControl*/) { var ray = Camera.main.ScreenPointToRay(Position); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo, 1 << LayerMask.NameToLayer("Terrain"))) { unit.MovableBehaviour.SetMovePoint(new StaticTransform(hitInfo.point)); } } } } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace EmployeeTaskMonitor.Infrastructure.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Employee", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FirstName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), LastName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true), HiredDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "getdate()") }, constraints: table => { table.PrimaryKey("PK_Employee", x => x.Id); }); migrationBuilder.CreateTable( name: "Task", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), EmployeeId = table.Column<int>(type: "int", nullable: false), TaskName = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: true), StartTime = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "getdate()"), Deadline = table.Column<DateTime>(type: "datetime2", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Task", x => x.Id); table.ForeignKey( name: "FK_Task_Employee_EmployeeId", column: x => x.EmployeeId, principalTable: "Employee", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Task_EmployeeId", table: "Task", column: "EmployeeId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Task"); migrationBuilder.DropTable( name: "Employee"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ace; namespace unitTest_Engine_cs.ObjectSystem2D { class CameraObject : EngineTest { private CameraObject2D camera; public CameraObject() : base(60) { } protected override void OnStart() { var scene = new Scene(); var layer = new Layer2D(); var obj = new TextureObject2D(); camera = new CameraObject2D(); obj.Texture = Engine.Graphics.CreateTexture2D("Data/Texture/Sample1.png"); camera.Src = new RectI(100, 100, 312, 312); camera.Dst = new RectI(10, 10, 200, 160); layer.AddObject(obj); layer.AddObject(camera); scene.AddLayer(layer); Engine.ChangeScene(scene); } protected override void OnUpdating() { var dst = camera.Dst; dst.X += 3; camera.Dst = dst; } } }
using Capstone.Classes; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; namespace CapstoneTests { [TestClass] public class DrinkTest { [TestMethod] public void DrinkConstructorHappyTest() { Drink drink = new Drink("drink", 1M, "A2", 3); string expectedString = "drink"; string resultString = drink.Name; Assert.AreEqual(expectedString, resultString); expectedString = "A2"; resultString = drink.Slot; Assert.AreEqual(expectedString, resultString); Decimal expectedPrice = 1; Decimal resultPrice = drink.Price; Assert.AreEqual(expectedPrice, resultPrice); int expectedInventory = 3; int resultInventory = drink.InventoryCount; Assert.AreEqual(expectedInventory, resultInventory); Drink drink2 = new Drink("More Drink", 234M, "A5", 583858); expectedString = "More Drink"; resultString = drink2.Name; Assert.AreEqual(expectedString, resultString); expectedString = "A5"; resultString = drink2.Slot; Assert.AreEqual(expectedString, resultString); expectedPrice = 234M; resultPrice = drink2.Price; Assert.AreEqual(expectedPrice, resultPrice); expectedInventory = 583858; resultInventory = drink2.InventoryCount; Assert.AreEqual(expectedInventory, resultInventory); } [TestMethod] public void DrinkConstructorEdgeTest() { Drink drink = new Drink("", -34, "", int.MaxValue); string expectedString = ""; string resultString = drink.Name; Assert.AreEqual(expectedString, resultString); expectedString = ""; resultString = drink.Slot; Assert.AreEqual(expectedString, resultString); Decimal expectedPrice = 0; Decimal resultPrice = drink.Price; Assert.AreEqual(expectedPrice, resultPrice); int expectedInventory = int.MaxValue; int resultInventory = drink.InventoryCount; Assert.AreEqual(expectedInventory, resultInventory); Drink drink2 = new Drink(null, Decimal.MaxValue, null, -8358); expectedString = "Invalid Product Name"; resultString = drink2.Name; Assert.AreEqual(expectedString, resultString); expectedString = "Invalid Slot"; resultString = drink2.Slot; Assert.AreEqual(expectedString, resultString); expectedPrice = decimal.MaxValue; resultPrice = drink2.Price; Assert.AreEqual(expectedPrice, resultPrice); expectedInventory = 0; resultInventory = drink2.InventoryCount; Assert.AreEqual(expectedInventory, resultInventory); } [TestMethod] public void ProductOutputMessageTest() { Drink drink = new Drink("Drink", 3M, "A2", 3); string expected = "Glug Glug, Yum!"; string result = drink.ProductOutputMessage(); Assert.AreEqual(expected, result); } } }
using System.Linq; using NUnit.Framework; using NUnit.Framework.Constraints; namespace Codility.Tests { public class FrogRiverCrossingShould { [TestCase(5,new[] {1, 3, 1, 4, 2, 3, 5, 4}, ExpectedResult = 6)] [TestCase(5, new[] { 1, 3, 1, 3, 2, 5, 4, 5, 4 }, ExpectedResult = 6)] [TestCase(5, new[] { 1, 2, 3, 4, 5 }, ExpectedResult = 4)] [TestCase(5, new[] { 5, 4, 3, 2, 1 }, ExpectedResult = 4)] [TestCase(5, new[] { 1, 1, 1, 1, 1, 1, 5, 4 }, ExpectedResult = -1)] public int Find(int x,int[] inputSet) { return FrogRiverCrossing.Find(x, inputSet); } } }
using EduHome.Models.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EduHome.ViewModels { public class PostVM { public List<Post> Posts { get; set; } public List<Category> Categories { get; set; } } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebCore.Fileters { public class MyFormatFilterAttribute : FormatFilterAttribute { } }
namespace Stock_Exchange_Analyzer { public enum DataProviders { YahooFinance } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Mail; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Filters; using System.Web.Mvc; using Docller.Core.Common; namespace Docller.UI.Common { public class ExceptionHandlingAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { //Log it Logger.Log(HttpContext.Current != null ? new HttpContextWrapper(HttpContext.Current) : null, filterContext.Exception); string user = HttpContext.Current != null ? HttpContext.Current.User.Identity.Name : "No HttpContext"; Task.Run(() => { SmtpClient client = new SmtpClient(); client.Send("Error@Docller.com", "Info@Docller.com", "Errors found", string.Format("User: {0}\n Exception: {1}", user, filterContext.Exception.Message)); }); base.OnException(filterContext); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; public class DiningRoom : Room { IntRange diningTableBreadthRange = new IntRange(3, 5); IntRange diningTableLengthRange = new IntRange(6, 10); IntRange diningTableMarginRange = new IntRange(3, 4); int diningTableBreadth; int diningTableLength; int diningTableMargin; float chairGenerationChance = .5f; bool vertical; DiningRoomTileset tileSet; public DiningRoom() : base() { roomCode = RoomCode.DiningRoom; diningTableBreadth = diningTableBreadthRange.Random; diningTableLength = diningTableLengthRange.Random; diningTableMargin = diningTableMarginRange.Random; tileSet = (DiningRoomTileset)TileSet; } protected override void SetRoomDimensions() { vertical = (Random.value > 0.5f); int dim1 = diningTableMargin * 2 + diningTableBreadth; int dim2 = diningTableMargin * 2 + diningTableLength; if (vertical) { width = dim1; height = dim2; } else { width = dim2; height = dim1; } //Do this to not let the width and height get modified by dimension checking widthRange.m_Min = width; widthRange.m_Max = width; heightRange.m_Min = height; heightRange.m_Max = height; } public override void GenerateFurniture() { GenerateLightSwitch(); GenerateDiningTable(); GenerateChairs(); } void GenerateDiningTable() { //Corners TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(x + diningTableMargin, y + diningTableMargin, 0), tileSet.diningTableBottomLeft); TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(x + width - diningTableMargin - 1, y + diningTableMargin, 0), tileSet.diningTableBottomRight); TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(x + diningTableMargin, y + height - diningTableMargin - 1, 0), tileSet.diningTableTopLeft); TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(x + width - diningTableMargin - 1, y + height - diningTableMargin - 1, 0), tileSet.diningTableTopRight); for (int xPos = x + diningTableMargin + 1; xPos < x + width - diningTableMargin - 1; xPos++) { TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(xPos, y + diningTableMargin, 0), tileSet.diningTableBottomCenter); TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(xPos, y + height - diningTableMargin - 1, 0), tileSet.diningTableTopCenter); } for (int yPos = y + diningTableMargin + 1; yPos < y + height - diningTableMargin - 1; yPos++) { TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(x + diningTableMargin, yPos, 0), tileSet.diningTableMidLeft); TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(x + width - diningTableMargin - 1, yPos, 0), tileSet.diningTableMidRight); } for (int xPos = x + diningTableMargin + 1; xPos < x + width - diningTableMargin - 1; xPos++) { for (int yPos = y + diningTableMargin + 1; yPos < y + height - diningTableMargin - 1; yPos++) { TileSetRegistry.I.floorTilemaps[story].SetTile(new Vector3Int(xPos, yPos, 0), tileSet.diningTableMidCenter); } } Vector2 position = new Vector2(x + width / 2f - .5f, y + height / 2f - .5f); Furniture tableCollider = InstantiateFurniture(PrefabRegistry.I.boxOverlay.GetComponent<Furniture>(), position); if (vertical) tableCollider.transform.localScale = new Vector2(diningTableBreadth, diningTableLength); else tableCollider.transform.localScale = new Vector2(diningTableLength, diningTableBreadth); } void GenerateChairs() { for (int xPos = x + diningTableMargin + 1; xPos < x + width - diningTableMargin - 1; xPos++) { float rng = Random.value; if (rng < chairGenerationChance) { Furniture chair = InstantiateFurniture(tileSet.chair, new Vector2(xPos, y + diningTableMargin - 1)); if (chair) { chair.GetComponent<CardinalSprite>().UpdateDirection(Direction.South); } } rng = Random.value; if (rng < chairGenerationChance) { Furniture chair = InstantiateFurniture(tileSet.chair, new Vector2(xPos, y + height - diningTableMargin)); if (chair) { chair.GetComponent<CardinalSprite>().UpdateDirection(Direction.South); } } } for (int yPos = y + diningTableMargin + 1; yPos < y + height - diningTableMargin - 1; yPos++) { float rng = Random.value; if (rng < chairGenerationChance) { Furniture chair = InstantiateFurniture(tileSet.chair, new Vector2(x + diningTableMargin - 1, yPos)); if (chair) { chair.GetComponent<CardinalSprite>().UpdateDirection(Direction.East); } } rng = Random.value; if (rng < chairGenerationChance) { Furniture chair = InstantiateFurniture(tileSet.chair, new Vector2(x + width - diningTableMargin, yPos)); if (chair) { chair.GetComponent<CardinalSprite>().UpdateDirection(Direction.West); } } } } }
// Copyright (c) 2010 Michael B. Edwin Rickert // // See the file LICENSE.txt for copying permission. using System; using System.Drawing; using System.Linq; using System.Windows.Forms; using TtyRecMonkey.Properties; namespace TtyRecMonkey { public partial class ConfigurationForm : Form { public ConfigurationForm() { InitializeComponent(); numericUpDown1.Value = Configuration.Main.framerateControlTimeout; numericUpDown2.Value = Configuration.Main.TimeStepLengthMS; numericUpDown3.Value = Configuration.Main.MaxDelayBetweenPackets; radioButton1.Checked = Configuration.Main.OpenNone; radioButton2.Checked = Configuration.Main.OpenFileSelect; radioButton3.Checked = Configuration.Main.OpenDownload; } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void buttonSave_Click(object sender, EventArgs e) { Configuration.Main.framerateControlTimeout = (int)numericUpDown1.Value; Configuration.Main.TimeStepLengthMS = (int)numericUpDown2.Value; Configuration.Main.MaxDelayBetweenPackets = (int)numericUpDown3.Value; Configuration.Main.OpenNone = radioButton1.Checked; Configuration.Main.OpenFileSelect = radioButton2.Checked; Configuration.Main.OpenDownload = radioButton3.Checked; Configuration.Save(this); DialogResult = DialogResult.OK; Close(); } private void labelTargetChunksMemory_Click(object sender, EventArgs e) { } } }
using Application.Core; using Application.Core.Models; using System.Collections.Generic; namespace Application.Infrastructure.DAL { public static class DataSeeder { public static void SeedData(ApplicationDBContext context) { var equipmentTypes = new List<EquipmentTypes>{ new EquipmentTypes {Id = 1, Name = nameof(EnmEquipmentTypes.Heavy), PreDefinedDay = 0}, new EquipmentTypes {Id = 2, Name = nameof(EnmEquipmentTypes.Regular), PreDefinedDay = 2}, new EquipmentTypes {Id = 3, Name = nameof(EnmEquipmentTypes.Specialized), PreDefinedDay = 3}}; var rentalFeeTypes = new List<RentalFeeTypes> { new RentalFeeTypes() {Id = 1, FeeType = nameof(EnmFeeTypes.OneTimeRentalFee), Fee = 100}, new RentalFeeTypes() {Id = 2, FeeType = nameof(EnmFeeTypes.PremiumDailyFee), Fee = 60}, new RentalFeeTypes() {Id = 3, FeeType = nameof(EnmFeeTypes.RegularDailyFee), Fee = 40} }; var equipments = new List<Equipments> { new Equipments {Id = 1, Type = (int) EnmEquipmentTypes.Heavy, Name = "Caterpillar bulldozer"}, new Equipments {Id = 2, Type = (int) EnmEquipmentTypes.Regular, Name = "KamAZ truck"}, new Equipments {Id = 3, Type = (int) EnmEquipmentTypes.Heavy, Name = "Komatsu crane"}, new Equipments {Id = 4, Type = (int) EnmEquipmentTypes.Regular, Name = "Volvo steamroller"}, new Equipments {Id = 5, Type = (int) EnmEquipmentTypes.Specialized, Name = "Bosch jackhammer"} }; var users = new List<Users> { new Users {UserId = 1, UserName = "demo", Password = "demo"} }; context.EquipmentTypes.AddRange(equipmentTypes); context.RentalFeeTypes.AddRange(rentalFeeTypes); context.Equipments.AddRange(equipments); context.Users.AddRange(users); context.SaveChangesAsync(); } } }
using System; using System.Collections.Generic; using System.Text; using Hayaa.DataAccess; using Hayaa.BaseModel; using Hayaa.Security.Service.Config; /// <summary> ///代码效率工具生成,此文件不要修改 /// </summary> namespace Hayaa.Security.Service.Dao { internal partial class AppServiceDal : CommonDal { private static String con = ConfigHelper.Instance.GetConnection(DefineTable.DatabaseName); internal static int Update(AppService info) { string sql = "update AppService set Name=@Name,Title=@Title,AppId=@AppId,Status=@Status where AppServiceId=@AppServiceId"; return Update<AppService>(con, sql, info); } internal static bool Delete(List<int> IDs) { string sql = "delete from AppService where AppServiceId in @ids"; return Excute(con, sql, new { ids = IDs.ToArray() }) > 0; } internal static AppService Get(int Id) { string sql = "select * from AppService where AppServiceId=@AppServiceId"; return Get<AppService>(con, sql, new { AppServiceId = Id }); } internal static List<AppService> GetList(AppServiceSearchPamater pamater) { string sql = "select * from AppService " + pamater.CreateWhereSql(); return GetList<AppService>(con, sql, pamater); } internal static GridPager<AppService> GetGridPager(GridPagerPamater<AppServiceSearchPamater> pamater) { string sql = "select SQL_CALC_FOUND_ROWS * from AppService " + pamater.SearchPamater.CreateWhereSql() + " limit @Start,*@PageSize;select FOUND_ROWS();"; pamater.SearchPamater.Start = (pamater.Current - 1) * pamater.PageSize; pamater.SearchPamater.PageSize = pamater.PageSize; return GetGridPager<AppService>(con, sql, pamater.PageSize, pamater.Current, pamater.SearchPamater); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Emceelee.Shared { public class IndexedCollection<TKey, TValue> : ICollection<TValue> { private readonly IDictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(); private readonly Func<TValue, TKey> key; public IndexedCollection(Func<TValue, TKey> key) { this.key = key; } public TValue this[TKey key] { get { return dict[key]; } } public int Count => dict.Count; public bool IsReadOnly => false; public void Add(TValue item) { if (dict.ContainsKey(key(item))) { throw new ArgumentException("Key already exists in collection."); } dict.Add(key(item), item); } public void AddRange(IEnumerable<TValue> items) { foreach(var item in items) { if(dict.ContainsKey(key(item))) { throw new ArgumentException("Key already exists in collection."); } } foreach (var item in items) { dict.Add(key(item), item); } } public void Clear() { dict.Clear(); } public bool Contains(TValue item) { return dict.Values.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { if(array == null) { throw new ArgumentNullException(); } if(arrayIndex < 0) { throw new ArgumentOutOfRangeException(); } //array length 2 - arrayIndex 0 = 2 int remaining = array.Length - arrayIndex; if(remaining < Count) { throw new ArgumentException($"The number of elements is greater than the available space from index to the end of the array. "); } int currentIndex = arrayIndex; foreach(var value in dict.Values) { array[currentIndex++] = value; } } public IEnumerator<TValue> GetEnumerator() { return dict.Values.GetEnumerator(); } public bool Remove(TValue item) { bool value = false; var keys = dict.Where(p => p.Value.Equals(item)).Select(p => p.Key).ToList(); foreach(var key in keys) { dict.Remove(key); value = true; } return value; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Module1 { public partial class Module1 : Form { public Module1() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void btnSales_Click(object sender, EventArgs e) { lblMessage.Text = "Family wagon, immaculate condition $12,995"; } private void btnService_Click(object sender, EventArgs e) { lblMessage.Text = "Lube, oil, filter $25.99"; } private void btnDetail_Click(object sender, EventArgs e) { lblMessage.Text = "Complete detail $79.95 for most cars"; } private void btnEmployment_Click(object sender, EventArgs e) { lblMessage.Text = "Sales position, contact Mr. Mann 551-2134 x475"; } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ASPNet_MVC_AngularJS_SPA.Services { public class ActivityServices { AppDataEntities db = new AppDataEntities(); public int SaveActivity(Activity objActivity) { if (objActivity.ID > 0) { //save existing user Activity existingActivity = (from e in db.Activities select e).Where(e => e.ID == objActivity.ID).FirstOrDefault(); existingActivity.Activity_Name = objActivity.Activity_Name; existingActivity.Description = objActivity.Description; return db.SaveChanges(); } else { // add new user db.Activities.Add(objActivity); } return db.SaveChanges(); } public IList<Activity> GetAllActivities(int UserId) { IList<Activity> lstActivty = (from e in db.Activities select e).Where(e => e.UserId == UserId).ToList<Activity>(); return lstActivty; } } }
using UnityEngine; using UnityEditor; using Ardunity; [CustomEditor(typeof(HM10UI))] public class HM10UIEditor : Editor { [MenuItem("ARDUnity/Add Utility/UI/HM10UI", true)] static bool ValidateMenu() { if(Selection.activeGameObject == null) return false; return true; } [MenuItem("ARDUnity/Add Utility/UI/HM10UI", false, 10)] static void DoMenu() { Selection.activeGameObject.AddComponent<HM10UI>(); } SerializedProperty popupCanvas; SerializedProperty settingCommSocket; SerializedProperty ok; SerializedProperty cancel; SerializedProperty hm10; SerializedProperty deviceList; SerializedProperty deviceItem; void OnEnable() { popupCanvas = serializedObject.FindProperty("popupCanvas"); settingCommSocket = serializedObject.FindProperty("settingCommSocket"); ok = serializedObject.FindProperty("ok"); cancel = serializedObject.FindProperty("cancel"); hm10 = serializedObject.FindProperty("hm10"); deviceList = serializedObject.FindProperty("deviceList"); deviceItem = serializedObject.FindProperty("deviceItem"); } public override void OnInspectorGUI() { this.serializedObject.Update(); //HM10UI utility = (HM10UI)target; EditorGUILayout.PropertyField(hm10, new GUIContent("HM-10")); EditorGUILayout.PropertyField(popupCanvas, new GUIContent("popupCanvas")); EditorGUILayout.PropertyField(settingCommSocket, new GUIContent("settingCommSocket")); EditorGUILayout.PropertyField(deviceList, new GUIContent("deviceList")); EditorGUILayout.PropertyField(deviceItem, new GUIContent("deviceItem")); EditorGUILayout.PropertyField(ok, new GUIContent("ok")); EditorGUILayout.PropertyField(cancel, new GUIContent("cancel")); this.serializedObject.ApplyModifiedProperties(); } }
using System.Collections.Generic; using System.Linq; using Tomelt.ContentManagement; using Tomelt.ContentManagement.MetaData; using Tomelt.ContentManagement.MetaData.Builders; using Tomelt.ContentManagement.MetaData.Models; using Tomelt.ContentManagement.ViewModels; using Tomelt.Templates.Services; using Tomelt.Templates.ViewModels; namespace Tomelt.Templates.Settings { public class ShapePartSettingsEvents : ContentDefinitionEditorEventsBase { private readonly IEnumerable<ITemplateProcessor> _processors; public ShapePartSettingsEvents(IEnumerable<ITemplateProcessor> processors) { _processors = processors; } public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition) { if (definition.PartDefinition.Name != "ShapePart") yield break; var settings = definition.Settings.GetModel<ShapePartSettings>(); var model = new ShapePartSettingsViewModel { Processor = settings.Processor, AvailableProcessors = _processors.ToArray() }; yield return DefinitionTemplate(model); } public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel) { if (builder.Name != "ShapePart") yield break; var model = new ShapePartSettingsViewModel { AvailableProcessors = _processors.ToArray() }; updateModel.TryUpdateModel(model, "ShapePartSettingsViewModel", new[] { "Processor" }, null); builder.WithSetting("ShapePartSettings.Processor", model.Processor); yield return DefinitionTemplate(model); } } }
using Donnee; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoucheMiddlewareApplication { public class Performance { private CADClass cad; private DataSet data; private Mappage mapPerformance; public Performance() { cad = new CADClass(); data = new DataSet(); mapPerformance = new Mappage(); } /// <summary> /// permet l'execution de la requete select et retourne la derniere valeur /// </summary> /// <returns></returns> public DataSet selectLast() { this.data = cad.getRows(mapPerformance.selectLast()); return data; } } }
using System; using System.IO; using Phenix.Core; namespace Phenix.Test.使用指南._03._13._1 { class Program { //* 配置项属性 //* 注意需将字段定义为Nullable<T>类型,以便Phenix.Core.AppSettings用于区分是否已赋过值 private static bool? _test_InEncrypt; /// <summary> /// 测试用 /// 默认:false /// </summary> public static bool Test_InEncrypt { get { return Phenix.Core.AppSettings.GetProperty(ref _test_InEncrypt, false, true, true); } set { Phenix.Core.AppSettings.SetProperty(ref _test_InEncrypt, value, true, true); } } //* 配置项属性 //* 注意需将字段定义为Nullable<T>类型,以便Phenix.Core.AppSettings用于区分是否已赋过值 private static bool? _test; /// <summary> /// 测试用 /// 默认:false /// </summary> public static bool Test { get { return Phenix.Core.AppSettings.GetProperty(ref _test, false); } set { Phenix.Core.AppSettings.SetProperty(ref _test, value); } } static void Main(string[] args) { Console.WriteLine("请通过检索“//*”了解代码中的特殊处理"); Console.WriteLine("测试过程中的日志保存在:" + Phenix.Core.AppConfig.TempDirectory); Console.WriteLine(); Console.WriteLine("->请使用超级管理员运行本程序<-"); Console.Write("按回车键继续:"); Console.ReadLine(); Console.WriteLine(); Console.WriteLine("设为调试状态"); Phenix.Core.AppConfig.Debugging = true; Console.WriteLine(); //Console.WriteLine("模拟登陆"); //Phenix.Business.Security.UserPrincipal.User = Phenix.Business.Security.UserPrincipal.CreateTester(); //Phenix.Services.Client.Library.Registration.RegisterEmbeddedWorker(false); //Console.WriteLine(); Console.WriteLine("**** 测试类继承关系下,泛型虚拟父类的静态属性如何在各子类中setter、getter不同值的功能 ****"); Console.WriteLine("**** 利用类的本地配置功能 ****"); TestA.FirstDate = DateTime.MaxValue; Console.WriteLine("设置TestA.FirstDate=" + TestA.FirstDate); TestB.FirstDate = DateTime.MinValue; Console.WriteLine("设置TestB.FirstDate=" + TestB.FirstDate); Console.WriteLine("读取TestA.FirstDate=" + TestA.FirstDate); Console.WriteLine("**** 利用泛型类的静态属性特性 ****"); TestA.LastDate = DateTime.MaxValue; Console.WriteLine("设置TestA.LastDate=" + TestA.LastDate); TestB.LastDate = DateTime.MinValue; Console.WriteLine("设置TestB.LastDate=" + TestB.LastDate); Console.WriteLine("读取TestA.LastDate=" + TestA.LastDate); Console.Write("按回车键继续:"); Console.ReadLine(); Console.WriteLine(); Console.WriteLine("**** 测试加密(传inEncrypt=true参数)的配置功能 ****"); Test_InEncrypt = !Test_InEncrypt; Console.WriteLine("设置属性Test_InEncrypt=" + Test_InEncrypt); Console.WriteLine("请检查" + Phenix.Core.AppSettings.ConfigFilename + "配置文件中key='Phenix.Test.使用指南._03._13._1.Program.Test_InEncrypt.'的设置值是否已加密"); Console.Write("按回车键继续:"); Console.ReadLine(); Console.WriteLine(); const string key = "Phenix.Test.使用指南._03._13._1.Program.Test."; Console.WriteLine("**** 测试类的本地配置功能 ****"); Console.WriteLine("提取属性Test=" + Test); Console.WriteLine("配置文件存放在:" + Phenix.Core.AppSettings.ConfigFilename); Test = !Test; Console.WriteLine("设置属性Test=" + Test); Console.WriteLine("请检查" + Phenix.Core.AppSettings.ConfigFilename + "配置文件中key='" + key + "'的设置值是否等于" + Test); Console.Write("按回车键继续:"); Console.ReadLine(); Console.WriteLine(); Console.WriteLine("**** 测试修改本地配置存放文件功能 ****"); Phenix.Core.AppSettings.ConfigFilename = System.IO.Path.Combine(@"C:\\", Path.GetFileName(AppSettings.DefaultConfigFilename)); Console.WriteLine("修改本地配置存放文件为:" + Phenix.Core.AppSettings.ConfigFilename); Console.WriteLine("本方法,适用于使用 ClickOnce 来部署 Windows 窗体应用程序,以永久存放系统配置项内容"); Console.WriteLine("在正式应用中,该语句请紧跟在LogOn.Execute()语句执行完之后被调用!"); Test = !Test; Console.WriteLine("设置属性Test=" + Test); Console.WriteLine("请检查" + Phenix.Core.AppSettings.ConfigFilename + "配置文件中key='" + key + "'的设置值是否等于" + Test); Console.Write("按回车键继续:"); Console.ReadLine(); Console.WriteLine(); Console.WriteLine("**** 测试删除配置信息后会到缺省配置文件里取值 ****"); Phenix.Core.AppSettings.RemoveValue(key); Console.WriteLine("删除key='" + key + "'配置信息"); Console.WriteLine("请检查" + Phenix.Core.AppSettings.ConfigFilename + "配置文件中是否已被删?"); Console.Write("按回车键继续:"); Console.ReadLine(); Console.WriteLine(); Console.WriteLine("缺省配置文件为:" + Phenix.Core.AppSettings.DefaultConfigFilename); Console.WriteLine("读取key='" + key + "'配置信息为:" + Phenix.Core.AppSettings.ReadValue(key)); Console.WriteLine(); Console.WriteLine("要重置属性Test值,即重新从配置文件中取值,则需清空其字段值"); _test = null; Console.WriteLine("重置后,属性Test=" + Test + " " + (Test == (bool)Phenix.Core.Reflection.Utilities.ChangeType(Phenix.Core.AppSettings.ReadValue(key), typeof(bool)) ? "ok" : "error")); Console.WriteLine(); Console.WriteLine("结束"); Console.ReadLine(); } } }
using System; using System.Reflection; using iSukces.Code.Interfaces; namespace iSukces.Code.Serenity { public enum SerenityClassRole { Unknown, Row, Form } public class SerenityTypesHelper { public SerenityTypesHelper(Type clrType, SerenityClassRole role) { ClrType = clrType; var at = new AbstractType(clrType); var ns = ProcessNamespace(at.Namespace, role); TsType = at.MoveToNs(ns); } public static bool IsRowType(Type rowType) { return SerenityCodeSettings.GetSerenityRowType() .GetTypeInfo().IsAssignableFrom(rowType); } private static string ProcessNamespace(string ns, SerenityClassRole role) { switch (role) { case SerenityClassRole.Row: return TrimEnd(ns, ".Entities"); case SerenityClassRole.Form: return TrimEnd(ns, ".Forms"); case SerenityClassRole.Unknown: return ns; default: throw new ArgumentOutOfRangeException(nameof(role), role, null); } } private static string TrimEnd(string text, string ending) { if (string.IsNullOrEmpty(ending)) return text; if (text.EndsWith(ending, StringComparison.OrdinalIgnoreCase)) text = text.Substring(0, text.Length - ending.Length); return text; } public AbstractType TsType { get; } public Type ClrType { get; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; namespace Crystal.Plot2D { [DebuggerDisplay("Count = {Count}")] public sealed class FakePointList : IList<Point> { private int first; private int last; private int count; private Point startPoint; private bool hasPoints; private double leftBound; private double rightBound; private readonly List<Point> points; internal FakePointList(List<Point> points, double left, double right) { this.points = points; leftBound = left; rightBound = right; Calc(); } internal void SetXBorders(double left, double right) { leftBound = left; rightBound = right; Calc(); } private void Calc() { Debug.Assert(leftBound <= rightBound); first = points.FindIndex(p => p.X > leftBound); if (first > 0) { first--; } last = points.FindLastIndex(p => p.X < rightBound); if (last < points.Count - 1) { last++; } count = last - first; hasPoints = first >= 0 && last > 0; if (hasPoints) { startPoint = points[first]; } } public Point StartPoint { get { return startPoint; } } public bool HasPoints { get { return hasPoints; } } #region IList<Point> Members public int IndexOf(Point item) { throw new NotSupportedException(); } public void Insert(int index, Point item) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } public Point this[int index] { get { return points[first + 1 + index]; } set { throw new NotSupportedException(); } } #endregion #region ICollection<Point> Members public void Add(Point item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(Point item) { throw new NotSupportedException(); } public void CopyTo(Point[] array, int arrayIndex) { throw new NotSupportedException(); } public int Count { get { return count; } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public bool Remove(Point item) { throw new NotSupportedException(); } #endregion #region IEnumerable<Point> Members public IEnumerator<Point> GetEnumerator() { for (int i = first + 1; i <= last; i++) { yield return points[i]; } } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
using System; using AutoMapper; using XH.Commands.Projects; using XH.Domain.Projects; using XH.Infrastructure.Command; using XH.Infrastructure.Domain.Repositories; namespace XH.Command.Handlers { public class ProjectCommandHandler : ICommandHandler<CreateProjectCommand>, ICommandHandler<UpdateProjectCommand>, ICommandHandler<DeleteProjectCommand>, ICommandHandler<CreateProjectUserCommand>, ICommandHandler<UpdateProjectUserCommand>, ICommandHandler<DeleteProjectUserCommand> { private readonly IMapper _mapper; private readonly IRepository<Project> _projectRepository; public ProjectCommandHandler(IMapper mapper, IRepository<Project> projectRepository) { _mapper = mapper; _projectRepository = projectRepository; } public void Handle(CreateProjectUserCommand command) { // Check user name //var project = _projectRepository.Get(command.ProjectId); //if (project == null) //{ // throw new EntityNotFoundException("项目不存在"); //} //else //{ // // Check user name. // if (project.Users != null && project.Users.Any(it => (command.Email.IsNotNullOrEmpty() && command.Email.Equals(it.Email, StringComparison.OrdinalIgnoreCase)) // || it.UserName.Equals(command.UserName, StringComparison.OrdinalIgnoreCase))) // { // // exist same userName or userEmail // throw new DomainException("存在重复的用户名或者邮箱地址"); // } //} //var user = _mapper.Map<ProjectUser>(command); //user.Password = MD5Utility.GetMD5Hash(command.Password); //project.Users.Add(user); //_projectRepository.Update(project); } public void Handle(DeleteProjectUserCommand command) { // Check user name //var project = _projectRepository.Get(command.ProjectId); //if (project == null) //{ // throw new EntityNotFoundException("项目不存在"); //} //if (!project.Users.Any(it => it.Id == command.UserId)) //{ // throw new EntityNotFoundException("用户不存在"); //} //project.Users = project.Users.Where(it => it.Id != command.UserId).ToList(); //_projectRepository.Update(project); } public void Handle(UpdateProjectUserCommand command) { // Check user name //var project = _projectRepository.Get(command.ProjectId); //if (project == null) //{ // throw new EntityNotFoundException("项目不存在"); //} //else //{ // // Check user name. // if (project.Users != null && project.Users.Any(it => it.Id != command.UserId && // ((command.Email.IsNotNullOrEmpty() && command.Email.Equals(it.Email, StringComparison.OrdinalIgnoreCase)) // || it.UserName.Equals(command.UserName, StringComparison.OrdinalIgnoreCase)))) // { // // exist same userName or userEmail // throw new DomainException("存在重复的用户名或者邮箱地址"); // } //} //var existUser = project.Users.FirstOrDefault(it => it.Id == command.UserId); //if (existUser == null) //{ // throw new EntityNotFoundException("用户不存在"); //} //_mapper.Map(command, existUser); //if (command.ResetPassword) //{ // existUser.Password = MD5Utility.GetMD5Hash(command.NewPassword); //} //_projectRepository.Update(project); } public void Handle(CreateProjectCommand command) { CheckCreateOrUpdateCommand(command); var entity = _mapper.Map<Project>(command); _projectRepository.Insert(entity); } public void Handle(DeleteProjectCommand command) { var entity = _projectRepository.Get(command.Id); if (entity == null) { throw new EntryPointNotFoundException($"不存在Id:{command.Id} 的项目"); } _projectRepository.Delete(entity); } public void Handle(UpdateProjectCommand command) { CheckCreateOrUpdateCommand(command); var entity = _projectRepository.Get(command.Id); if (entity == null) { throw new EntryPointNotFoundException($"不存在Id:{command.Id} 的项目"); } _mapper.Map(command, entity); _projectRepository.Update(entity); } private void CheckCreateOrUpdateCommand(CreateOrUpdateProjectCommand command) { } } }