text
stringlengths
13
6.01M
using GDS.Dal; using GDS.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GDS.Entity.Result; using GDS.Comon; using GDS.Entity.Constant; namespace GDS.BLL { public class UsersBLL { IUsersDao<Users> dal; public UsersBLL() { dal = new ImplUsers() { }; } /// <summary> /// 获取分页数据 /// </summary> /// <param name="preq"></param> /// <returns></returns> public List<Users> GetDataByPage(PageRequest preq) { return dal.GetDataByPage<Users>(preq); } /// <summary> /// 获取全部数据 /// </summary> /// <returns></returns> public List<Users> GetDataAll() { return dal.GetDataAll<Users>(); } /// <summary> /// 根据Id获取数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public Users GetDataById(int id) { return dal.GetDataById<Users>(id); } /// <summary> /// 根据Id删除数据 /// </summary> /// <param name="id"></param> /// <returns></returns> public ResultEntity<int> DeleteDataById(int id) { ResultEntity<int> result; try { var repResult = dal.DeleteDataById<Users>(id); if (repResult) { result = new ResultEntity<int>(true, ConstantDefine.TipDelSuccess, 1); } else { result = new ResultEntity<int>(ConstantDefine.TipDelFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } /// <summary> /// 假删除数据 /// </summary> /// <param name="Ids"></param> /// <returns></returns> public ResultEntity<int> FalseDeleteDataByIds(int[] Ids) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.FalseDeleteDataByIds<Users>(Ids); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipDelSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipDelFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } // 添加 public ResultEntity<int> InsertUsers(Users uie) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Insert<Users>(uie); if (repResult != null) { IntRet = int.Parse(repResult.ToString()); } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } // 修改 public ResultEntity<int> UpdateUsers(Users uie) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Update<Users>(uie); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } public List<Users> GetUsersByDepartId(int departId) { return dal.GetUsersByDepartId(departId); } public List<Users> GetDataByUserName(string userName) { return dal.GetDataByUserName(userName); } public ResultEntity<int> UpdateDisable(int UId, bool Disable) { ResultEntity<int> result; try { int IntRet = 0; var repResult = dal.Update<Users>(new { Disable = Disable }, it => it.Id == UId); if (repResult) { IntRet = 1; } if (IntRet > 0) { result = new ResultEntity<int>(true, ConstantDefine.TipSaveSuccess, IntRet); } else { result = new ResultEntity<int>(ConstantDefine.TipSaveFail); } } catch (Exception ex) { Loger.LogErr(ex); result = new ResultEntity<int>(ex.Message); } return result; } } }
using UnityEngine; using System.Collections; /// <summary> /// 游戏风格化的Sprite /// </summary> [System.Serializable] public struct GameUISkin { public Sprite m_UIBtnNormal; public Sprite m_UIBtnDisable; } namespace Game.UI.Inner { [ExecuteInEditMode] public class GameUISpriteProvider : MonoBehaviour { public static GameUISpriteProvider instance; public static GameUISpriteProvider g_instance { get { if (instance == null) { Debug.LogError("No provider found , so i create one for you with no any sprite attached."); GameObject go = new GameObject("UISpriteProvider"); instance = go.AddComponent<GameUISpriteProvider>(); } return instance; } } /// <summary> /// 无阴影背景图 /// </summary> public Sprite m_UISprite; /// <summary> /// 圆形图片 /// </summary> public Sprite m_UIKnob; /// <summary> /// 输入框背景图 /// </summary> public Sprite m_UIInputFieldBG; /// <summary> /// 向下箭头 /// </summary> public Sprite m_UIDownArrow; /// <summary> /// 打勾标记图 /// </summary> public Sprite m_UICheckMark; /// <summary> /// 较灰色背景图 /// </summary> public Sprite m_UIBG; /// <summary> /// 游戏风格化定制UI /// </summary> public GameUISkin m_gameStyleUI; void Awake() { Debug.Log(this.gameObject.name + "awake"); instance = this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ScoreSquid.Web.Models; using ScoreSquid.Web.Context; namespace ScoreSquid.Web.Repositories.Commands { public interface IFixtureCommands { List<Fixture> GetAllFixtures(ScoreSquidContext context); Fixture GetFixturesByHomeTeamNameAndAwayTeamName(ScoreSquidContext context, string homeTeamName, string awayTeamName); void SaveFixture(ScoreSquidContext context, Fixture fixture); } }
using System; using System.Collections.Generic; namespace CC.Utilities.Services { public abstract class CompositeServiceBase<T>:ServiceBase { public bool SyncMasterWithSlaves{ get; set; } public bool Enabled{ get; set; } public T MasterService{ get; protected set; } public List<T> SlaveServices{ get; private set; } public CompositeServiceBase(T master) { MasterService = master; SlaveServices = new List<T>(); SyncMasterWithSlaves = true; } public CompositeServiceBase(T master, params T[] slaves):this(master) { SlaveServices.AddRange(slaves); } public void AddSlaveService(T service) { SlaveServices.Add(service); } } }
using AutoMapper; using LinqKit; using ServiceQuotes.Application.DTOs.Employee; using ServiceQuotes.Application.DTOs.Specialization; using ServiceQuotes.Application.Exceptions; using ServiceQuotes.Application.Filters; using ServiceQuotes.Application.Interfaces; using ServiceQuotes.Domain; using ServiceQuotes.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ServiceQuotes.Application.Services { public class EmployeeService : IEmployeeService { private readonly IMapper _mapper; private readonly IUnitOfWork _unitOfWork; public EmployeeService(IMapper mapper, IUnitOfWork unitOfWork) { _mapper = mapper; _unitOfWork = unitOfWork; } public async Task<List<GetEmployeeWithAccountImageResponse>> GetAllEmployees(GetEmployeesFilter filter) { // prepare filter predicate var predicate = PredicateBuilder.New<Employee>(true); if (!string.IsNullOrEmpty(filter?.SearchString)) { predicate = predicate.Or(p => p.FirstName.ToLower().Contains(filter.SearchString.ToLower())); predicate = predicate.Or(p => p.LastName.ToLower().Contains(filter.SearchString.ToLower())); } var specializationId = new Guid(); if (!string.IsNullOrEmpty(filter?.SpecializationId) && Guid.TryParse(filter?.SpecializationId, out specializationId)) { predicate = predicate.And(p => p.EmployeeSpecializations.Any(x => x.SpecializationId == specializationId)); } if (filter?.Role is not null) { predicate = predicate.And(p => p.Account.Role == filter.Role); } var employees = await _unitOfWork.Employees.FindWithSpecializations(predicate); return employees.Select(employee => new GetEmployeeWithAccountImageResponse() { Id = employee.Id, AccountId = employee.AccountId, FirstName = employee.FirstName, LastName = employee.LastName, Image = employee.Account.Image, Specializations = employee.EmployeeSpecializations .Select(es => new GetSpecializationResponse() { Id = es.Specialization.Id, Name = es.Specialization.Name }) .ToList() }) .ToList(); } public async Task<GetEmployeeWithAccountImageResponse> GetEmployeeById(Guid id) { var employee = await _unitOfWork.Employees.GetWithSpecializations(id); return new GetEmployeeWithAccountImageResponse() { Id = employee.Id, AccountId = employee.AccountId, FirstName = employee.FirstName, LastName = employee.LastName, Image = employee.Account.Image, Specializations = employee.EmployeeSpecializations .Select(es => new GetSpecializationResponse() { Id = es.Specialization.Id, Name = es.Specialization.Name }) .ToList() }; } public async Task<GetEmployeeResponse> CreateEmployee(CreateEmployeeRequest dto) { // validate if (await _unitOfWork.Accounts.Get(dto.AccountId) is null) throw new KeyNotFoundException("Account does not exist."); // map dto to new employee object var newEmployee = _mapper.Map<Employee>(dto); _unitOfWork.Employees.Add(newEmployee); _unitOfWork.Commit(); return _mapper.Map<GetEmployeeResponse>(newEmployee); } public async Task<GetEmployeeResponse> UpdateEmployee(Guid id, UpdateEmployeeRequest dto) { var employee = await _unitOfWork.Employees.Get(id); // validate if (employee is null) throw new KeyNotFoundException(); if (!string.IsNullOrEmpty(dto.FirstName) && employee.FirstName != dto.FirstName) employee.FirstName = dto.FirstName; if (!string.IsNullOrEmpty(dto.LastName) && employee.LastName != dto.LastName) employee.LastName = dto.LastName; _unitOfWork.Commit(); return _mapper.Map<GetEmployeeResponse>(employee); } public async Task<GetEmployeeWithSpecializationsResponse> AddSpecialization(Guid employeeId, Guid specializationId) { var employee = await _unitOfWork.Employees.GetWithSpecializations(employeeId); var specialization = await _unitOfWork.Specializations.Get(specializationId); // validate if (employee is null) throw new KeyNotFoundException("Employee does not exist."); if (specialization is null) throw new KeyNotFoundException("Specialization does not exist."); if (employee.EmployeeSpecializations.Any(es => es.SpecializationId == specialization.Id)) throw new AppException($"Specialization {specialization.Name} is already assigned to this employee."); employee.EmployeeSpecializations.Add(new EmployeeSpecialization { EmployeeId = employee.Id, SpecializationId = specialization.Id }); _unitOfWork.Commit(); return await GetEmployeeById(employee.Id); } public async Task RemoveSpecialization(Guid employeeId, Guid specializationId) { var employee = await _unitOfWork.Employees.GetWithSpecializations(employeeId); // validate if (employee is null) throw new KeyNotFoundException("Employee does not exist."); var specialization = employee.EmployeeSpecializations .FirstOrDefault(es => es.SpecializationId == specializationId); if (specialization is null) throw new KeyNotFoundException("Specialization not found in employee specializations."); employee.EmployeeSpecializations.Remove(specialization); _unitOfWork.Commit(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _unitOfWork.Dispose(); } } } }
namespace ShapeUpp.Domain.Constants { public enum BodyParts { Chest, Back, Legs, Shoulders, Arms, Abdominals } }
using GDS.BLL; using GDS.Comon; using GDS.Entity; using GDS.Entity.Result; using GDS.Query; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; namespace GDS.WebApi.Controllers { public class FlowController : BaseController { [AcceptVerbs(HttpVerbs.Get)] public ActionResult GetApprovalList() { var queryParams = new NameValueCollection(); if (!ParamHelper.CheckParaQ(ref queryParams)) { return Json(new ResponseEntity<int>(RegularFunction.RegularSqlRegexText), JsonRequestBehavior.AllowGet); } int userType = CurrenUserInfo.UserType; string loginName = CurrenUserInfo.LoginName; List<Department> departmentList = new List<Department>(); if (userType != GDS.Entity.Constant.ConstantDefine.Admin) //验证审批权限 { departmentList = new DepartmentBLL().GetDepartmentByAuditor(loginName); if (departmentList == null || departmentList.Count == 0) { return Json(new ResponseEntity<dynamic>(10, "权限不足", null), JsonRequestBehavior.AllowGet); } } var templateApprovalList = getTemplateApprovalList(queryParams, departmentList); var projectApprovalList = getPojectApprovalList(queryParams, departmentList); var approvalList = templateApprovalList.Select(template => { return new { Id = template.Id, ItemType = "模板", Name = template.Name, DepartId = template.DepartId, Description = template.Description, CreateAt = template.CreateTime, CreateTimeStr = template.CreateTimeStr, CreateBy = template.CreateBy, Status = template.Status }; }).ToList(); approvalList.AddRange( projectApprovalList.Select(project => { return new { Id = project.Id, ItemType = "项目", Name = project.Name, DepartId = project.BusinessDept, Description = project.Comments, CreateAt = project.CreateTime, CreateTimeStr = project.CreateTimeStr, CreateBy = project.CreateBy, Status = project.Status }; }).ToList() ); if (queryParams.AllKeys.Contains("SearchType") && !string.IsNullOrEmpty(queryParams["SearchType"])) { approvalList = approvalList.Where(approval => approval.ItemType == queryParams["SearchType"]).ToList(); } var response = new ResponseEntity<object>(true, string.Empty, approvalList.OrderByDescending(approval => approval.CreateAt)); return Json(response, JsonRequestBehavior.AllowGet); } private List<View_Template> getTemplateApprovalList(NameValueCollection queryParams, List<Department> departmentList) { try { var query = new TemplateQuery(queryParams); var sqlCondition = new StringBuilder(); sqlCondition.Append("ISNULL(IsDelete,0)!=1 and status=0");//Status审批状态为0(草稿),1同意,2拒绝 if (departmentList != null && departmentList.Count > 0) { sqlCondition.Append($" and DepartId in ({string.Join(",", departmentList.Select(x => x.Id))}) "); } //if (userType != GDS.Entity.Constant.ConstantDefine.Admin) //验证审批权限 //{ // var departmentList = new DepartmentBLL().GetDepartmentByAuditor(loginName); // if (departmentList != null && departmentList.Count > 0) // { // sqlCondition.Append($" and DepartId in ({string.Join(",", departmentList.Select(x => x.Id))}) "); // } // else // { // return Json(new ResponseEntity<dynamic>(10, "权限不足", null), JsonRequestBehavior.AllowGet); // } //} if (!string.IsNullOrEmpty(query.DepartId) && query.DepartId != "0") { sqlCondition.Append($" and DepartId = {query.DepartId}"); } if (!string.IsNullOrEmpty(query.ProjectType)) { sqlCondition.Append($" and ProjectType = {query.ProjectType}"); } if (!string.IsNullOrEmpty(query.Name)) { sqlCondition.Append($" and Name like '%{query.Name}%'"); } if (!string.IsNullOrEmpty(query.CreateBy)) { sqlCondition.Append($" and CreateBy like '%{query.CreateBy}%'"); } PageRequest preq = new PageRequest { TableName = " [View_Template] ", Where = sqlCondition.ToString(), Order = " Id DESC ", IsSelect = true, IsReturnRecord = true, PageSize = query.PageSize, PageIndex = query.PageIndex, FieldStr = "*" }; var result = new TemplateBLL().GetView_TemplateByPage(preq); result.ForEach(template => { template.CreateTimeStr = template.CreateTime.HasValue ? template.CreateTime.Value.ToString("yyyy-MM-dd") : string.Empty; }); //var response = new ResponseEntity<object>(true, string.Empty, // new DataGridResultEntity<View_Template> // { // TotalRecords = preq.Out_AllRecordCount, // DisplayRecords = preq.Out_PageCount, // ResultData = result // }); return result; //Json(response, JsonRequestBehavior.AllowGet); } catch (Exception ex) { return new List<View_Template>(); } } private List<View_Project> getPojectApprovalList(NameValueCollection queryParams, List<Department> departmentList) { try { var query = new ProjectQuery(queryParams); var sqlCondition = new StringBuilder(); sqlCondition.Append("ISNULL(IsDelete,0)!=1 and CurrentStatus=0"); //CurrentStatus审批状态为0(草稿) if (departmentList != null && departmentList.Count > 0) { sqlCondition.Append($" and DepartId in ({string.Join(",", departmentList.Select(x => x.Id))}) "); } //if (userType != GDS.Entity.Constant.ConstantDefine.Admin) //验证审批权限 //{ // var departmentList = new DepartmentBLL().GetDepartmentByAuditor(loginName); // if (departmentList != null && departmentList.Count > 0) // { // sqlCondition.Append($" and DepartId in ({string.Join(",", departmentList.Select(x => x.Id))}) "); // } // else // { // return Json(new ResponseEntity<dynamic>(10, "权限不足", null), JsonRequestBehavior.AllowGet); // } //} int userType = CurrenUserInfo.UserType; string loginName = CurrenUserInfo.LoginName; if (userType == GDS.Entity.Constant.ConstantDefine.ProjectManager) // { sqlCondition.Append($" and (createby = '{loginName}' or projectmanager = '{loginName}' or charindex(';{loginName};', ';' + TeamMembers + ';') > 0) "); } else if (userType == GDS.Entity.Constant.ConstantDefine.User) // { sqlCondition.Append($"and charindex(';{loginName};', ';' + TeamMembers + ';') > 0"); } if (!string.IsNullOrEmpty(query.DepartId) && query.DepartId != "0") { sqlCondition.Append($" and BusinessDept = {query.DepartId}"); } if (!string.IsNullOrEmpty(query.ProjectType)) { sqlCondition.Append($" and ProjectType = {query.ProjectType}"); } if (!string.IsNullOrEmpty(query.Name)) { sqlCondition.Append($" and Name like '%{query.Name}%'"); } if (!string.IsNullOrEmpty(query.CreateBy)) { sqlCondition.Append($" and CreateBy like '%{query.CreateBy}%'"); } PageRequest preq = new PageRequest { TableName = " [View_Project] ", Where = sqlCondition.ToString(), Order = " Id DESC ", IsSelect = true, IsReturnRecord = true, PageSize = query.PageSize, PageIndex = query.PageIndex, FieldStr = "*" }; var result = new ProjectBLL().GetView_ProjectByPage(preq); result.ForEach(project => { project.CreateTimeStr = project.CreateTime.HasValue ? project.CreateTime.Value.ToString("yyyy-MM-dd") : string.Empty; }); //var response = new ResponseEntity<object>(true, string.Empty, // new DataGridResultEntity<View_Project> // { // TotalRecords = preq.Out_AllRecordCount, // DisplayRecords = preq.Out_PageCount, // ResultData = result // }); return result; } catch (Exception ex) { return new List<View_Project>(); } } } }
using FontAwesome5.Extensions; using System; using System.Globalization; using System.Windows.Data; using System.Windows.Markup; namespace FontAwesome5.Converters { public class LabelConverter : MarkupExtension, IValueConverter { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is not EFontAwesomeIcon) { return null; } var icon = (EFontAwesomeIcon)value; var info = icon.GetInformation(); if (info == null) { return null; } return parameter is string format && !string.IsNullOrEmpty(format) ? string.Format(format, info.Label, info.Style) : info.Label; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
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 WindowsFormsApplication2 { public partial class Form4 : Form { public Form4() { InitializeComponent(); } int cerrar = 0; private void bt_ingresar_administracion_Click(object sender, EventArgs e) { UsuarioAdmin usuarioOB = new UsuarioAdmin(); usuarioOB.Usuario = this.txt_usuarioAdministracion.Text; usuarioOB.Contraseña = this.txt_contraseñaAdmonistracion.Text; if (usuarioOB.buscar() == true) { MessageBox.Show(usuarioOB.Mensaje, "Loguin..."); cerrar = 1; } else { MessageBox.Show(usuarioOB.Mensaje, "ERROR..."); cerrar = 0; } if (cerrar == 1) { this.Close(); } else { } } } }
using System.Collections.Generic; using Quark.Contexts; using Quark.Targeting; using Quark.Utilities; using UnityEngine; namespace Quark.Projectiles { /// <summary> /// Projectile class provides interface for MissileController objects to access to properties about the projectile /// It also retrieves necessary movement vector or position vector and moves the carrier object appropriately /// It is also responsible for handling the collisions and target checks /// </summary> public sealed class Projectile : MonoBehaviour { /// <summary> /// The near enough distance constant which indicates that a missile will consider itself reached to a target point. /// </summary> public static float NearEnough = 0.1F; /// <summary> /// Rotation of the caster Character when the projectile stage began. /// </summary> public Vector3 CastRotation; /// <summary> /// The Controller of this projectile object. /// </summary> public ProjectileController Controller { get; private set; } /// <summary> /// The Context of this projectile. /// </summary> public IProjectileContext Context { get; set; } /// <summary> /// This property calculates the latest position change of this Projectile. /// </summary> public Vector3 LastMovement { get { return transform.position - _previousPosition; } } #region Initialization /// <summary> /// This function creates a new projectile object from a prefab and a controller in a context towards a target. /// /// The created projectile will immediately start travelling towars its target. /// </summary> /// <param name="prefab">The prefab of a Projectile. The prefab shouldn't contain a Projectile component.</param> /// <param name="controller">A controller object to control the Projectile instance.</param> /// <param name="context">Context to create the Projectile instance in.</param> /// <param name="target">Target of the Projectile instance.</param> /// <returns>The new Projectile instance.</returns> public static Projectile Make(GameObject prefab, ProjectileController controller, ICastContext context, TargetUnion target) { GameObject instantiatedObject = (GameObject)Instantiate(prefab, Vector3.zero, Quaternion.identity); Projectile projectileComponent = instantiatedObject.AddComponent<Projectile>(); ProjectileContext pContext = new ProjectileContext(context, projectileComponent, target); controller.SetContext(pContext); instantiatedObject.transform.position = controller.InitialPoint(target); projectileComponent.Context = pContext; projectileComponent.Controller = controller; projectileComponent.Controller.SetProjectile(projectileComponent); return projectileComponent; } #endregion private Dictionary<int, bool> _collided; void FixedUpdate() { _collided = new Dictionary<int, bool>(); } void OnTriggerEnter(Collider c) { // Unity calls OnTriggerEnter for every collider on the hit object. // We store the hit objects in a dictionary every frame to // mistakenly processing one hit more than once. if (_collided.ContainsKey(c.gameObject.GetInstanceID())) return; Targetable hit = c.gameObject.GetComponent<Targetable>(); if (hit == null) // Hit object wasn't a Quark object. return; if (hit is Character) Context.OnHit(new TargetUnion(hit as Character)); else Context.OnHit(new TargetUnion(hit)); _collided.Add(c.gameObject.GetInstanceID(), true); } /// <summary> /// This field stores the position of the Projectile when the OnTravel event was raised the last time. /// </summary> private Vector3 _lastTravel; /// <summary> /// This field stores the position of the Projectile before the controller is called this frame. /// /// Used for determining the last movement vector upon hitting. /// </summary> private Vector3 _previousPosition; void Update() { _previousPosition = transform.position; Controller.Control(); if (Context.Target.Type == TargetType.Point && Controller.Finished) { Context.OnHit(Context.Target); return; } if (Utils.Distance2(transform.position, _lastTravel) >= Context.Spell.TravelingInterval) { _lastTravel = transform.position; Context.OnTravel(); } } } }
using Igorious.StardewValley.ShowcaseMod.ModConfig; using Microsoft.Xna.Framework; namespace Igorious.StardewValley.ShowcaseMod.Core.Layouts { internal class ShowcaseFixedLayout : ShowcaseGridLayoutBase { public ShowcaseFixedLayout(float scaleSize, Rectangle sourceRect, ItemGridProvider itemProvider, LayoutConfig config) : base(scaleSize, sourceRect, itemProvider, config) { } protected override int GetTopRow() => 0; protected override int GetBottomRow() => ItemProvider.Rows - 1; protected override int GetLeftColumn() => 0; protected override int GetRightColumn() => ItemProvider.Columns - 1; } }
/************************************************************************************************** DISPLAY CONTROL **************************************************************************************************/ #region Using using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml.Serialization; using System.Windows.Media; // reference to PresentationFramework #endregion namespace DesktopDisplay { public partial class DisplayCtrl : UserControl { #region Data Members private int MonitorNo; public DisplayConfig Config; public Screen MonitorRef; // preserve screen pointer when config is reconfigured private Timer Clock; private int timerElapse; private int timerCumulative; private const int TIMER_INCR = 6000; // 6 seconds // events to be sent to main form public delegate void ControlEvent(); public event ControlEvent FormDirty; public event ControlEvent UpdateWallpaper; #endregion #region Constructors public DisplayCtrl() { InitializeComponent(); } public DisplayCtrl(Screen p_screen, int p_monitorNo) { InitializeComponent(); this.MonitorNo = p_monitorNo; this.MonitorRef = p_screen; // initialize monitor info f_isPrimary.Text = "Primary: " + (p_screen.Primary ? "Yes" : "No"); string msg = string.Format("Width: {0} Height: {1} X: {2} Y: {3}", p_screen.Bounds.Width, p_screen.Bounds.Height, p_screen.Bounds.X, p_screen.Bounds.Y); f_geometry.Text = msg; // initialize the config this.Config = this.GetDataFromFile(); if (Config != null) { this.SetDataToUI(this.Config); if (Config.ImageDir != null) this.StartTimer(); } else { this.Config = new DisplayConfig(); } this.Config.ScreenRef = this.MonitorRef; } #endregion #region User Interface private void f_browse_Click(object sender, EventArgs e) { using (FolderBrowserDialog fbd = new FolderBrowserDialog()) { fbd.Description = "Choose folder for image rotation."; if (this.Config != null && this.Config.ImageDir != null) fbd.SelectedPath = Config.ImageDir; if (fbd.ShowDialog() != DialogResult.OK) return; // save data to UI and notify the main form f_rootFolder.Text = fbd.SelectedPath; if (FormDirty != null) FormDirty(); } } private void f_timerInterval_ValueChanged(object sender, EventArgs e) { if (FormDirty != null) FormDirty(); } private void f_marginLeft_ValueChanged(object sender, EventArgs e) { if (FormDirty != null) FormDirty(); } private void f_marginTop_ValueChanged(object sender, EventArgs e) { if (FormDirty != null) FormDirty(); } private void f_marginBottom_ValueChanged(object sender, EventArgs e) { if (FormDirty != null) FormDirty(); } private void f_marginRight_ValueChanged(object sender, EventArgs e) { if (FormDirty != null) FormDirty(); } #endregion #region Data Management private void SetDataToUI(DisplayConfig p_config) { f_rootFolder.Text = p_config.ImageDir; f_timerInterval.Value = p_config.ClockPeriod; f_marginTop.Value = p_config.Margin.Top; f_marginLeft.Value = p_config.Margin.Left; f_marginRight.Value = p_config.Margin.Right; f_marginBottom.Value = p_config.Margin.Bottom; } private DisplayConfig GetDataFromUI() { DisplayConfig createConfig = new DisplayConfig(); createConfig.ScreenRef = this.MonitorRef; createConfig.ImageDir = f_rootFolder.Text; createConfig.ClockPeriod = (int)f_timerInterval.Value; createConfig.Margin = new Padding( (int)f_marginLeft.Value, (int)f_marginTop.Value, (int)f_marginRight.Value, (int)f_marginBottom.Value); return createConfig; } public void SaveDataToFile() { Config = this.GetDataFromUI(); XmlSerializer cereal = new XmlSerializer(typeof(DisplayConfig)); string filePath = this.GetConfigSerialPath(this.MonitorNo); TextWriter writer = File.CreateText(filePath); cereal.Serialize(writer, this.Config); writer.Dispose(); } private DisplayConfig GetDataFromFile() { XmlSerializer cereal = new XmlSerializer(typeof(DisplayConfig)); string configPath = this.GetConfigSerialPath(this.MonitorNo); if (File.Exists(configPath)) { TextReader reader = File.OpenText(configPath); DisplayConfig createConfig = (DisplayConfig)cereal.Deserialize(reader); reader.Dispose(); return createConfig; } return null; } private string GetConfigSerialPath(int p_configNo) { string msg = Utility.StringFormat.GetExecutableRootPath(); string fileName = "config" + p_configNo + ".xml"; msg = Path.Combine(msg, fileName); return msg; } #endregion #region Image Management public void StartTimer() { this.timerElapse = (Config.ClockPeriod > 0 ? Config.ClockPeriod * 60 : 12) *1000; this.timerCumulative = 0; f_countdown.Value = 0; if (this.Clock != null) Clock.Stop(); Clock = new Timer(); Clock.Interval = TIMER_INCR; Clock.Tick += new EventHandler(Clock_Tick); Clock.Start(); this.Config.GoToNextImagePath(); this.UpdateStatus(); } private void Clock_Tick(object sender, EventArgs e) { timerCumulative += TIMER_INCR; int prog = (timerCumulative * 100) / timerElapse; f_countdown.Value = prog; if (timerCumulative >= timerElapse) { this.Config.GoToNextImagePath(); this.UpdateStatus(); timerCumulative = 0; f_countdown.Value = 0; // notify main form if (this.UpdateWallpaper != null) this.UpdateWallpaper(); } } private void UpdateStatus() { string folder, name; if (this.Config.FilePath != null) { folder = Utility.StringFormat.GetLastDirectoryOnly(this.Config.FilePath); name = Path.GetFileName(this.Config.FilePath); f_currImage.Text = Path.Combine(folder, name); } if (this.Config.PrevPath != null) { folder = Utility.StringFormat.GetLastDirectoryOnly(this.Config.PrevPath); name = Path.GetFileName(this.Config.PrevPath); f_previousImage.Text = Path.Combine(folder, name); } } #endregion } }
using LivrariaWEB.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LivrariaWEB.Data { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Livro> Livro { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<Livro>() .Property(p => p.Autor) .HasMaxLength(80); builder.Entity<Livro>() .Property(p => p.Nome) .HasMaxLength(80); base.OnModelCreating(builder); } } }
 namespace Jypeli.Effects { /// <summary> /// Järjestelmä liekeille /// </summary> public class Flame : ParticleSystem { private double addTime; /// <summary> /// Luo uuden liekin. /// </summary> /// <param name="image">Partikkelin kuva.</param> public Flame(Image image) : base(image, 180) { Angle = Angle.FromDegrees(90); BlendMode = BlendMode.Alpha; } /// <summary> /// Määritetään oletusarvot efektille /// </summary> protected override void InitializeParticles() { MinLifetime = 2.0; MaxLifetime = 2.2; MinScale = 70; MaxScale = 100; ScaleAmount = -2.0; AlphaAmount = 1.0; MinVelocity = 40; MaxVelocity = 70; MinAcceleration = 1; MaxAcceleration = 2; MinRotationSpeed = -MathHelper.PiOver4; MaxRotationSpeed = MathHelper.PiOver4; } /// <summary> /// Lasketaan liekin suunnalle satunnaisuutta /// </summary> /// <returns>Partikkelin suunta</returns> protected override Vector GiveRandomDirection() { return Vector.FromLengthAndAngle(1, Angle + Angle.FromDegrees(RandomGen.NextDouble(-MaxAngleChange, MaxAngleChange))); } /// <summary> /// Päivitetään liekkiä /// </summary> /// <param name="time"></param> public override void Update(Time time) { double t = time.SinceLastUpdate.TotalSeconds; addTime += t; if (addTime > 0.05) { base.AddEffect(Position, 2); addTime = 0; } base.Update(time); } /// <summary> /// Alustetaan partikkeli /// </summary> /// <param name="p">Partikkeli joka alustetaan</param> /// <param name="position">Sijainti johon alustetaan</param> protected override void InitializeParticle(Particle p, Vector position) { base.InitializeParticle(p, position); if (!IgnoreWind) p.Acceleration = Game.Wind; } } }
using IntegrationAdapters.MicroserviceComunicator; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace IntegrationAdapters.Controllers { public class ActionBenefitController : Microsoft.AspNetCore.Mvc.Controller { private readonly IActionBenefitService _actionBenefitService; public ActionBenefitController(IActionBenefitService actionBenefitService) { _actionBenefitService = actionBenefitService; } public async Task<IActionResult> Index() { return View(await _actionBenefitService.GetAll()); } public async Task<IActionResult> Details(int id) { return View(await _actionBenefitService.Get(id)); } [Route("ActionBenefit/MakePublic/{id}/{isPublic}")] public async Task<IActionResult> MakePublic(int id, bool isPublic) { await _actionBenefitService.SetPublic(id, isPublic); return RedirectToAction("Details", new { id = id }); } } }
namespace Waterskibaan { class WachtrijStarten : Wachtrij { public override int MaxLengteRij => 20; public override bool CheckAantal(int aantal) { return aantal <= MaxLengteRij; } public void OnInstructieAfgelopen(InstructieAfgelopenArgs args) { foreach (Sporter sporter in args.SportersKlaar) { SporterNeemPlaatsInRij(sporter); } } public override string ToString() { return $"Wachtrij starten: {GetAlleSporters().Count} wachtenden"; } } }
// This file is part of LAdotNET. // // LAdotNET is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // LAdotNET is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY, without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with LAdotNET. If not, see <https://www.gnu.org/licenses/>. using LAdotNET.Network; using LAdotNET.Network.Packets; using System; using System.Threading.Tasks; namespace LAdotNET.WorldServer.Network.Packets.Server.Init { class SMInitAchievementActive : Packet { private int PacketCount { get; set; } public SMInitAchievementActive(Connection connection, int type) : base(connection) { CompressionType = CompressionType.SNAPPY; OpCode = PacketFactory.ReverseLookup[GetType()]; PacketCount = type; } // Dunno what this does yet // 1.6.2.3 - 1.6.4.1 no change public override void Deserialize() { if (PacketCount == 0) { Data.WriteBytes(new byte[] { 0x00, 0x00, 0x18, 0x00, 0xA0, 0xD2, 0x1E, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xD2, 0x1E, 0x00, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xD2, 0x1E, 0x00, 0x03, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xD2, 0x1E, 0x00, 0x04, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0xD2, 0x1E, 0x00, 0x05, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x14, 0x2E, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x14, 0x2E, 0x00, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x14, 0x2E, 0x00, 0x03, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3A, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3B, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7E, 0x3D, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x72, 0x4C, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x72, 0x4C, 0x00, 0x02, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x72, 0x4C, 0x00, 0x03, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x72, 0x4C, 0x00, 0x04, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x72, 0x4C, 0x00, 0x05, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9C, 0xBD, 0x98, 0x00, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x6C, 0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }); } if(PacketCount == 1) { Data.WriteBytes(new byte[] { 0x23, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x04, 0x00, 0x05, 0x05, 0x00, 0x00, 0x06, 0x00, 0x00, 0x07, 0x00, 0x00, 0x08, 0x00, 0x00, 0x09, 0x00, 0x01, 0x0A, 0x00, 0x04, 0x0B, 0x00, 0x00, 0x0C, 0x00, 0x05, 0x0D, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x0F, 0x00, 0x05, 0x10, 0x00, 0x05, 0x11, 0x00, 0x22, 0x12, 0x00, 0x00, 0x13, 0x00, 0x05, 0x14, 0x00, 0x05, 0x15, 0x00, 0x01, 0x16, 0x00, 0x01, 0x17, 0x00, 0x01, 0x18, 0x00, 0x05, 0x19, 0x00, 0x00, 0x1A, 0x00, 0x0D, 0x1B, 0x00, 0x59, 0x1C, 0x00, 0x01, 0x1D, 0x00, 0x00, 0x1E, 0x00, 0x01, 0x1F, 0x00, 0x01, 0x20, 0x00, 0x00, 0x21, 0x00, 0x01, 0x22, 0x00, 0x01, 0x23, 0x00, 0x05, 0x00, 0x00 }); } } public override Task HandleAsync() { throw new NotImplementedException(); } public override void Serialize() { throw new NotImplementedException(); } } }
using System; using System.Threading; using OpenQA.Selenium; using Framework.Core.Common; using Tests.Data.Van.Input; using Tests.Pages.Van.Main.List; namespace Tests.Pages.Van.Main { public class CreateAListPage : BaseListPage { #region Page Element Declarations public string HeaderText = "Create A New Search"; public new By HeaderLocator = By.Id("ctl00_ContentPlaceHolderVANPage_HeaderText"); public new IWebElement Header { get { return _driver.FindElement(HeaderLocator); } } public By AgeRegDateSectionLocator = By.CssSelector("input#ImageButtonSectionAgeReg"); public IWebElement AgeRegDateSection { get { return _driver.FindElement(AgeRegDateSectionLocator); } } public By AgeFromInputLocator = By.CssSelector("input#AgeFrom"); public IWebElement AgeFromInput { get { return _driver.FindElement(AgeFromInputLocator); } } public IWebElement AgeToInput { get { return _driver.FindElement(By.CssSelector("input#AgeTo")); } } public IWebElement NameExpander { get { return _driver.FindElement(By.XPath("//input[@id='ctl00_ContentPlaceHolderVANPage_ImageButtonSectionName' and @src='/images/plus.gif']")); } } //""css=#ctl00_ContentPlaceHolderVANPage_ImageButtonSectionName"; public IWebElement LastNameInput { get { return _driver.FindElement(By.Name("LastName")); } } public IWebElement FirstNameInput { get { return _driver.FindElement(By.Name("FirstName")); } } public IWebElement SavePageLayoutLink { get { return _driver.FindElement(By.ClassName("SideBarLink")); } } public IWebElement CloseTourModalButton { get { return _driver.FindElement(By.CssSelector(".ui-widget-overlay.ui-front + div .tourfooter small")); } } public By SearchRunButtonLocator = By.Id("ctl00_ContentPlaceHolderVANPage_SearchRunButton"); public IWebElement SearchRunButton { get { return _driver.FindElement(SearchRunButtonLocator); } } public By ActivistCodesLocator = (By.Id("ImageButtonSectionActivistCodes")); public By ActivistcodeListboxLocator = (By.Name("ActivistCodeID")); public IWebElement ActivistCodes { get { return _driver.FindElement(By.Id("ImageButtonSectionActivistCodes")); } } public IWebElement ActivistcodeListbox { get { return _driver.FindElement(By.Name("ActivistCodeID")); } } public IWebElement RunSearchButton { get { return _driver.FindElementByExplicitWait(By.Id("ctl00_ContentPlaceHolderVANPage_SearchRunButton")); } } public By PreviewMyResultsButtonLocator = (By.Id("ResultsPreviewButton")); public IWebElement PreviewMyResultsButton { get {return _driver.FindElementByExplicitWait(PreviewMyResultsButtonLocator);}} #region CAL Membership Page Section public By MembershipSectionLocator = By.CssSelector("input#ImageButtonSectionGroups"); public IWebElement MembershipSection { get { return _driver.FindElement(MembershipSectionLocator); } } public By InternationalInputLocator = By.Name("Dist_InternationalCode"); public IWebElement InternationalInput { get { return _driver.FindElement(InternationalInputLocator); } } public By LocalInputLocator = By.Name("Dist_LocalCode"); public IWebElement LocalInput { get { return _driver.FindElement(LocalInputLocator); } } public By EmployerIdInputLocator = By.Name("Dist_EmployerID"); public IWebElement EmployerIdInput { get { return _driver.FindElement(EmployerIdInputLocator); } } public By WorksiteIdInputLocator = By.Name("Dist_WorksiteID"); public IWebElement WorksiteIdInput { get { return _driver.FindElement(WorksiteIdInputLocator); } } #endregion #endregion public CreateAListPage(Driver driver) : base(driver) { } #region Methods /// <summary> /// Opens the section for the passed name /// </summary> /// <param name="sectionName">Case-sensitive</param> public void OpenSectionByName(string sectionName) { var sectionLabelLocator = By.XPath(String.Format("//label[@class='PageSectionClickableTitle' and text()='{0}']", sectionName)); _driver.WaitUntilElementVisible(sectionLabelLocator); var sectionLabel = _driver.FindElement(sectionLabelLocator); _driver.Click(sectionLabel); } /// <summary> /// clicks section and verifies div displays /// </summary> public void ClickSectionAndVerifyDivDisplays(string section, string div) { _driver.Click(By.XPath(section)); //Assert.IsTrue(_driver.ElementExists(div)); } public void ClickCloseTourModalButton() { try { if (CloseTourModalButton.Displayed) CloseTourModalButton.Click(); } catch (Exception ) { } } /// <summary> /// searches by age min and max /// </summary> public void SearchByAge(int ageMin, int ageMax) { _driver.WaitUntilElementVisible(AgeRegDateSectionLocator); string min = ageMin.ToString(); string max = ageMax.ToString(); AgeRegDateSection.Click(); _driver.WaitUntilElementVisible(AgeFromInputLocator); if (ageMin>0) _driver.SendKeys(AgeFromInput, min); if (ageMin>0)_driver.SendKeys(AgeToInput, max); if ((ageMin > 0) && (ageMax > 0)) _driver.Click(RunSearchButton); ClickCloseTourModalButton(); } //todo make this work /// <summary> /// searches by first and last name /// </summary> public void SearchByName(string lastName, string firstName) { _driver.Click(NameExpander); //NameExpander.Click(); Thread.Sleep(5000); if (lastName!=null)_driver.SendKeys(LastNameInput, lastName); if (firstName!=null) _driver.SendKeys(FirstNameInput, firstName); if (firstName!=null && lastName!=null)_driver.Click(SearchButton); var list = new MyListPage(_driver); } #endregion public void SelectInternationInput(string input) { int count = 1; _driver.SelectOptionByText(InternationalInput, input); try { _driver.FindElement(By.CssSelector(".PSLoadingText div")); _driver.WaitForAttributeToDisplayValue(By.CssSelector(".PSLoadingText div"), "style", "none"); } catch (Exception) { } _driver.WaitForElementToDisplayBy(LocalInputLocator); var options = LocalInput.FindElements(By.TagName("option")); while (options.Count < 1 && count<=_driver.GetDefaultTimeOut()) { options = LocalInput.FindElements(By.TagName("option")); count++; Console.WriteLine("local input selector contains 0 options, waiting " + count + " seconds"); } } public void CreateNewSearch() { var data = new CutTurfData(); //_driver.WaitForElementPresent(ActivistCodes); _driver.SetImplicitWaitTimeout(10); _driver.WaitForElementToDisplayBy(ActivistCodesLocator); _driver.JavascriptClick(ActivistCodes); _driver.WaitForElementToDisplayBy(ActivistCodesLocator); _driver.SendKeys(ActivistcodeListbox, data.Activistcode); _driver.JavascriptClick(RunSearchButton); } /// <summary> /// This method runs a search with the default settings only /// </summary> public void ClickRunSearch() { _driver.WaitForElementToDisplayBy(ActivistCodesLocator); _driver.WaitForElementToDisplayBy(PreviewMyResultsButtonLocator); _driver.Click(RunSearchButton); //var myListPage = new MyListPage(_driver); //Assert.IsTrue(_driver.IsElementPresent(myListPage.HeaderText), "My List Header did not display"); } } }
using System; using Tomelt.ContentManagement.Handlers; using Tomelt.Core.Navigation.Models; using Tomelt.Data; namespace Tomelt.Core.Navigation.Handlers { public class AdminMenuPartHandler : ContentHandler { public AdminMenuPartHandler(IRepository<AdminMenuPartRecord> menuPartRepository) { Filters.Add(StorageFilter.For(menuPartRepository)); OnInitializing<AdminMenuPart>((ctx, x) => { x.OnAdminMenu = false; x.AdminMenuText = String.Empty; }); } } }
using NHibernate; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Services { public abstract class BaseService { private readonly Func<ISession> _lazySession; private ISession _session; protected BaseService(Func<ISession> session) { _lazySession = session; } public ISession CurrentSession { get { return _session ?? (_session = _lazySession()); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Windows.Forms; using XAPP.COMLIB; using System.IO; using System.Diagnostics; using System.Management; namespace ASSAMON { public partial class frmMain : Form { #region 变量 private COMLIB cm = new COMLIB(); private AccessControl accessControl = new AccessControl(); private Operations operations = new Operations(); private Constant constant = new Constant(); private Dictionary<IntPtr, String> dctMainWindow = new Dictionary<IntPtr, String>(); private Dictionary<IntPtr, String> dctASSA = new Dictionary<IntPtr, String>(); private Dictionary<IntPtr, IntPtr> dcthwdProId = new Dictionary<IntPtr, IntPtr>(); Dictionary<String, String> dctProcAct = new Dictionary<string, string>(); private StartUPType startUPType; /// <summary> /// /////////////////////////////////////////////////////////////////////////////////// /// </summary> private string RunningPath = System.AppDomain.CurrentDomain.BaseDirectory; List<ActiveInfo> lstAcitveInfo = new List<ActiveInfo>(); DoubleBufferListView doubleBufferlvActiveInfo = new DoubleBufferListView(); List<Dictionary<String, String>> lstActList = new List<Dictionary<string, string>>(); private List<String> lstStopTime = new List<string>(); Dictionary<String, IntPtr> dctProc = new Dictionary<String, IntPtr>(); private double killMem = 0; //Thread LogThread; private bool isRun = false; private static object LockObject = new Object(); private bool start = false; #endregion public frmMain() { InitializeComponent(); } #region Event private void btnTimer_Click(object sender, EventArgs e) { int interval = 10000; Int32.TryParse(cm.GetConfigurationData(constant.TimerInterval), out interval); timer1.Interval = interval; if (start == false) { timer1.Enabled = true; start = true; btnTimer.Text = "停止Timer"; btnTimer.BackColor = Color.LightGreen; tSSlblTimer.Text = "| Timer 运行中...."; } else { timer1.Enabled = false; start = false; btnTimer.Text = "开始Timer"; btnTimer.BackColor = Color.LightYellow; tSSlblTimer.Text = "| Timer 休息中...."; } } private void btnCloseSelected_Click(object sender, EventArgs e) { DeleteSelected(); } private void btnStartSelected_Click(object sender, EventArgs e) { //Auto Run Script: True startUPType = StartUPType.FIVE; tlsddbStartUpType.Text = StartUPType.FIVE.ToString(); startUPType = StartUPType.FIVE; StartAccounts(true); } private void btnLoadData_Click(object sender, EventArgs e) { LoadActiveData(); } private void btnCloseAll_Click(object sender, EventArgs e) { String saName = System.Configuration.ConfigurationManager.AppSettings["SAName"]; foreach (Process p in Process.GetProcessesByName(saName)) { AccessControl.KillDieProcess(p.Id); System.Threading.Thread.Sleep(100); } //记录句柄 String hwdFileSA = Path.Combine(RunningPath, "hwdFileSA.txt"); String hwdFileASSA = Path.Combine(RunningPath, "hwdFileASSA.txt"); String hwdFileAct = Path.Combine(RunningPath, "hwdFileAct.txt"); if (File.Exists(hwdFileSA)) { File.Delete(hwdFileSA); } if (File.Exists(hwdFileASSA)) { File.Delete(hwdFileASSA); } if (File.Exists(hwdFileAct)) { File.Delete(hwdFileAct); } System.Threading.Thread.Sleep(100); LoadActiveData(); } private void btnTest_Click(object sender, EventArgs e) { //LoadActiveData(); //CheckRunningActs(); /* String ss = String.Empty; String saName = System.Configuration.ConfigurationManager.AppSettings["SAName"]; foreach (Process p in Process.GetProcessesByName(saName)) { ss += GetCharAct(AccessControl.ReadSADataFromRAMString(p.Id, cm.GetConfigurationData("CharAct"))) + "\n"; } MessageBox.Show(ss); */ ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Process"); foreach (ManagementObject mo in searcher.Get()) { String a = mo["Name"].ToString().Trim() + "," + mo["ProcessId"].ToString().Trim() + "," + String.Format("{0}", mo["Status"]); if (a.Contains("sa_8001sf")) { MessageBox.Show(a); } } } private void btnSW_Click(object sender, EventArgs e) { //Auto Run Script: True startUPType = StartUPType.SHENGWANG; tlsddbStartUpType.Text = StartUPType.SHENGWANG.ToString(); startUPType = StartUPType.SHENGWANG; StartAccounts(true); } private void frmMain_Load(object sender, EventArgs e) { //Set APP Version string ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); tsslblVersion.Text = "VER: " + ver; //Timer timer1.Enabled = false; tSSlblTimer.Text = "| Timer 休息中...."; LoadAccounts(); InitialDoubleBufferListView(); Loadhwd(); foreach (StartUPType sup in Enum.GetValues(typeof(StartUPType))) { tlsddbStartUpType.DropDownItems.Add(sup.ToString()); } tlsddbStartUpType.Text = StartUPType.FIVE.ToString(); startUPType = StartUPType.FIVE; //右下角 int x = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Width - this.Width; int y = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Height - this.Height; Point p = new Point(x, y); this.PointToScreen(p); this.Location = p; } private void timer1_Tick(object sender, EventArgs e) { if (!isRun) { if (!lstStopTime.Contains(DateTime.Now.Hour.ToString())) { isRun = true; accessControl.ClickErrorWindow(constant.waitTime); refreshData(); CheckRunningActs(); isRun = false; } } } #endregion /* * Load Login Account */ private void LoadAccounts() { String accountFile = Path.Combine(RunningPath, constant.accountINI); using (StreamReader sr = new StreamReader(accountFile, Encoding.Default)) { String line; while ((line = sr.ReadLine()) != null) { lstccount.Items.Add(line.ToString()); } } var items = lstccount.Items; foreach (var item in items) { Dictionary<String, String> dctActList = new Dictionary<string, string>(); cm.GetUserNamePWD(item.ToString(), ref dctActList); lstActList.Add(dctActList); } } #region Custom View /* * Load Grid View */ private void InitialDoubleBufferListView() { doubleBufferlvActiveInfo.GridLines = true; doubleBufferlvActiveInfo.FullRowSelect = true; doubleBufferlvActiveInfo.HideSelection = false; doubleBufferlvActiveInfo.Location = new System.Drawing.Point(17, 110); doubleBufferlvActiveInfo.Name = "doubleBufferlvActiveInfo"; doubleBufferlvActiveInfo.Size = new System.Drawing.Size(750, 120); doubleBufferlvActiveInfo.TabIndex = 2; doubleBufferlvActiveInfo.UseCompatibleStateImageBehavior = false; doubleBufferlvActiveInfo.View = System.Windows.Forms.View.Details; doubleBufferlvActiveInfo.BringToFront(); this.Controls.Add(doubleBufferlvActiveInfo); doubleBufferlvActiveInfo.Clear(); //Initial Columns doubleBufferlvActiveInfo.Columns.Add("No.", 30); doubleBufferlvActiveInfo.Columns.Add("PID", 50); doubleBufferlvActiveInfo.Columns.Add("Memory", 100); doubleBufferlvActiveInfo.Columns.Add("名称", 70); doubleBufferlvActiveInfo.Columns.Add("帐号", 100); doubleBufferlvActiveInfo.Columns.Add("声望", 70); doubleBufferlvActiveInfo.Columns.Add("坐标", 70); doubleBufferlvActiveInfo.Columns.Add("地图", 50); doubleBufferlvActiveInfo.Columns.Add("句柄", 70); doubleBufferlvActiveInfo.Columns.Add("石头", 80); doubleBufferlvActiveInfo.Columns.Add("HP", 50); this.doubleBufferlvActiveInfo.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.doubleBufferlvActiveInfo_MouseDoubleClick); } private void doubleBufferlvActiveInfo_MouseDoubleClick(object sender, MouseEventArgs e) { //dctProc var items = doubleBufferlvActiveInfo.SelectedItems; foreach (ListViewItem item in items) { String pids = item.SubItems[1].Text; if (!String.IsNullOrEmpty(pids)) { IntPtr assaHwd = IntPtr.Zero; dctProc.TryGetValue(pids, out assaHwd); cm.BringTopASSA(assaHwd); } else { MessageBox.Show("SPID is null!"); } break; } } #endregion /* * 启动账号 */ private void StartAccounts(bool isStartScript) { //登录 Dictionary<String, String> dctLoginInfo = new Dictionary<string, string>(); foreach (int i in lstccount.SelectedIndices) { String item = lstccount.Items[i].ToString(); dctLoginInfo = new Dictionary<string, string>(); cm.GetUserNamePWD(item.ToString(), ref dctLoginInfo); StartStoneage(dctLoginInfo, isStartScript, i + 1); System.Threading.Thread.Sleep(3000); } //记录句柄 String hwdFileSA = Path.Combine(RunningPath, "hwdFileSA.txt"); String hwdFileASSA = Path.Combine(RunningPath, "hwdFileASSA.txt"); String hwdFileAct = Path.Combine(RunningPath, "hwdFileAct.txt"); //SA String content = String.Empty; if (File.Exists(hwdFileSA)) { File.Delete(hwdFileSA); } content = String.Empty; foreach (var item in dcthwdProId) { content += item.Key + ":" + item.Value + "\r\n"; } File.WriteAllText(hwdFileSA, content); //ASSA content = String.Empty; if (File.Exists(hwdFileASSA)) { File.Delete(hwdFileASSA); } content = String.Empty; foreach (var item in dctProc) { content += item.Key + ":" + item.Value + "\r\n"; } File.WriteAllText(hwdFileASSA, content); //Account content = String.Empty; if (File.Exists(hwdFileAct)) { File.Delete(hwdFileAct); } content = String.Empty; foreach (var item in dctProcAct) { content += item.Key + ":" + item.Value + "\r\n"; } File.WriteAllText(hwdFileAct, content); } private bool StartASSA(ref IntPtr mainHanlder, String sequence) { try { string assaExe = cm.GetConfigurationData(constant.assaEXE); string assaPath = cm.GetConfigurationData(constant.assaPath); if (!Directory.Exists(assaPath)) { assaPath = String.Format("{0}_{1}", assaPath, sequence); } int processID = cm.StartAPP(Path.Combine(assaPath, assaExe), assaPath); System.Threading.Thread.Sleep(constant.waitTime); mainHanlder = cm.GetWnd(processID, "ThunderRT6FormDC", cm.GetConfigurationData(constant.saClassName)); if (mainHanlder == IntPtr.Zero) { MessageBox.Show("Start Fail!"); return false; } //Load all the hwnd dctASSA.Clear(); dctASSA = accessControl.EnumWindowsCallback(mainHanlder); } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } return true; } /* * 启动石器 */ private void StartStoneage(Dictionary<String, String> dctLoginInfo, bool isStartScript, int seq) { //Start ASSA IntPtr mainHanlder = IntPtr.Zero; bool isDone = true; isDone = StartASSA(ref mainHanlder, dctLoginInfo["squence"]); if (!isDone) { MessageBox.Show("Initail ASSA Fail!"); return; } System.Threading.Thread.Sleep(constant.waitTime); //激活石器 IntPtr iBShiqi = cm.FindWindowEx(mainHanlder, cm.GetConfigurationData(constant.saStartButtonClassName), true); if (iBShiqi == IntPtr.Zero) { MessageBox.Show("Start Shiqi Fail!"); return; } System.Threading.Thread.Sleep(constant.waitTime); cm.MouseRightClick(iBShiqi); System.Threading.Thread.Sleep(constant.waitTime); //获取石器句柄 IntPtr saHanlder = cm.GetMainWindowhWnd("StoneAge", "StoneAge"); if (saHanlder == IntPtr.Zero) { MessageBox.Show("Get SA hWnd Fail!"); return; } //保存句柄 IntPtr sauPid = IntPtr.Zero; AccessControl.GetWindowThreadProcessId(saHanlder, ref sauPid); if (!dctProc.ContainsKey(sauPid.ToString())) { dctProc.Add(sauPid.ToString(), mainHanlder); } dcthwdProId.Add(sauPid, saHanlder); //Input username and Password operations.InputUserNameNPWD(dctLoginInfo["userName"], dctLoginInfo["password"], constant.waitTime); if (!dctProcAct.ContainsKey(sauPid.ToString())) { dctProcAct.Add(sauPid.ToString(), dctLoginInfo["userName"]); } //前置ASSA operations.PutASSATOTOP(mainHanlder, constant.waitTime); //点击资料显示 operations.MoveInformation(dctLoginInfo, dctASSA, constant.waitTime, seq, startUPType); //点击自动登陆 operations.CLickAutoLogin(dctASSA, constant.waitTime); if (isStartScript) { //点击脚本 IntPtr ibtScript = cm.GetHwndByValue(dctASSA, "脚本"); cm.MouseRightClick(ibtScript); System.Threading.Thread.Sleep(constant.waitTime); //运行脚本 if (startUPType == StartUPType.SHENGWANG) { operations.RunScript(dctLoginInfo["type"], constant.waitTime); } else { operations.RunScript(constant.waitTime); } //启动脚本 operations.ClickRunScript(mainHanlder, dctASSA, constant.waitTime); } //隐藏石器 operations.CliclHideASSA(mainHanlder, dctASSA, constant.waitTime); //Move main ASSA window if (startUPType.Equals(StartUPType.FIVE) || startUPType.Equals(StartUPType.ZHENGLI) || startUPType.Equals(StartUPType.LIANCHONG)) { operations.MoveStoneageWindows(mainHanlder, seq); } if (startUPType.Equals(StartUPType.SHENGWANG)) { SendKeys.SendWait("{F9}"); } LoadActiveData(); } private void LoadActiveData() { TaskBarUtil.RefreshNotification(); //SA PROID List<int> lstProID = new List<int>(); String saName = System.Configuration.ConfigurationManager.AppSettings["SAName"]; foreach (Process p in Process.GetProcessesByName(saName)) { lstProID.Add(p.Id); } //获取进程 List<ActiveInfo> lstAI = new List<ActiveInfo>(); List<String> lstSYSName = new List<string>(); //CLear the dataview doubleBufferlvActiveInfo.Items.Clear(); //dctProc foreach (int i in lstProID) { ActiveInfo ai = new ActiveInfo(); //PID ai.ProID = i; Process process = System.Diagnostics.Process.GetProcessById(i); //hwd IntPtr hwd = IntPtr.Zero; dcthwdProId.TryGetValue(new IntPtr(ai.ProID), out hwd); //Memory ai.Memory = process.WorkingSet64 / (1024.0 * 1024.0); if (ai.Memory < killMem) { dctProcAct.Remove(i.ToString()); //删除账号 //Get Hwd //Coding ////////////////////////////////////////// //AccessControl.SendMessage(hwd, Constant.WM_CLOSE, 0, 0);//get Handler AccessControl.KillDieProcess(i); //删除list 删除lv System.Threading.Thread.Sleep(1000); continue; } ListViewItem lvi = new ListViewItem(); lvi.Text = String.Format("{0}", doubleBufferlvActiveInfo.Items.Count + 1); lvi.SubItems.Add(i.ToString());//PID lvi.SubItems.Add(String.Format("{0}", ai.Memory));//Memory //名称 ai.Name = AccessControl.ReadSADataFromRAMString(i, cm.GetConfigurationData("CharName")); lvi.SubItems.Add(ai.Name);//名称 //帐号 //********************************************************************************** ai.Account = AccessControl.ReadSADataFromRAMString(i, cm.GetConfigurationData("CharAct")); String actMem = GetCharAct(ai.Account); String actStart = String.Empty; dctProcAct.TryGetValue(i.ToString(), out actStart); //如果内存名字为空登录没成功,取启动名字 if (String.IsNullOrEmpty(actMem)) { actMem = actStart; } //加入账号 if (!String.IsNullOrEmpty(actMem)) { lstSYSName.Add(actMem); } lvi.SubItems.Add(actMem);//帐号 //************************************************************************************* //声望 ai.ShengWang = AccessControl.ReadSADataFromRAMInt(i, cm.GetConfigurationData("addrSW")); lvi.SubItems.Add(String.Format("{0}", ai.ShengWang));//声望 //XY, 坐标 int x = AccessControl.ReadSADataFromRAMInt(i, cm.GetConfigurationData("addrX")); int y = AccessControl.ReadSADataFromRAMInt(i, cm.GetConfigurationData("addrY")); ai.XY = String.Format("{0},{1}", x, y); lvi.SubItems.Add(ai.XY);//坐标 //Map int map = AccessControl.ReadSADataFromRAMInt(i, cm.GetConfigurationData("addrMap")); lvi.SubItems.Add(String.Format("{0}", map));//地图 ai.MAP = String.Format("{0}", map); //hWnd ai.Hwnd = hwd; lvi.SubItems.Add(hwd.ToString()); //Stone int stone = AccessControl.ReadSADataFromRAMInt(i, cm.GetConfigurationData("CharStone")); ai.Stone = String.Format("{0}", stone); lvi.SubItems.Add(String.Format("{0}", stone));//石头 //HP int hp = AccessControl.ReadSADataFromRAMInt(i, cm.GetConfigurationData("CharHP")); ai.HP = String.Format("{0}", hp); lvi.SubItems.Add(String.Format("{0}", hp));//HP lstAI.Add(ai); this.doubleBufferlvActiveInfo.Items.Add(lvi); } } private bool CheckActAlreadyRunning(String act) { bool blExisted = false; String saName = System.Configuration.ConfigurationManager.AppSettings["SAName"]; foreach (Process p in Process.GetProcessesByName(saName)) { String actTmp = GetCharAct(AccessControl.ReadSADataFromRAMString(p.Id, cm.GetConfigurationData("CharAct"))); if (actTmp.Equals(act)) { blExisted = true; break; } } return blExisted; } private String GetCharAct(string addressAct) { foreach (Dictionary<String, String> dct in lstActList) { String str = String.Empty; dct.TryGetValue("userName", out str); int actLen = str.Length; if (addressAct.Length < actLen) continue; String tmpaddressAct = addressAct.Substring(0, actLen); if (tmpaddressAct.Equals(str)) { return str; } } return String.Empty; } private Dictionary<String, String> GetActDct(String act) { Dictionary<String, String> dctRet = new Dictionary<string, string>(); foreach (Dictionary<String, String> dct in lstActList) { if (dct.ContainsValue(act)) { dctRet = dct; break; } } return dctRet; } private void DeleteSelected() { foreach (ListViewItem item in this.doubleBufferlvActiveInfo.SelectedItems) { //second column PID /* int hwd = -1; int.TryParse(item.SubItems[8].Text, out hwd); if (hwd > 0) { AccessControl.SendMessage(new IntPtr(hwd), Constant.WM_CLOSE, 0, 0);//get Handler doubleBufferlvActiveInfo.Items.RemoveAt(item.Index); }*/ int proID = -1; int.TryParse(item.SubItems[1].Text, out proID); if (proID > 0) { AccessControl.KillDieProcess(proID); doubleBufferlvActiveInfo.Items.RemoveAt(item.Index); } } } /// <summary> /// 处理 SA, ASSA,账号 /// </summary> private void Loadhwd() { String hwdFileSA = Path.Combine(RunningPath, "hwdFileSA.txt"); String hwdFileASSA = Path.Combine(RunningPath, "hwdFileASSA.txt"); String hwdFileAct = Path.Combine(RunningPath, "hwdFileAct.txt"); String content = String.Empty; dcthwdProId.Clear(); dctProc.Clear(); dctProcAct.Clear(); //Handle Hwd String saName = System.Configuration.ConfigurationManager.AppSettings["SAName"]; List<int> lstProID = new List<int>(); foreach (Process p in Process.GetProcessesByName(saName)) { lstProID.Add(p.Id); } if (lstProID.Count > 0) { //SA hwd if (File.Exists(hwdFileSA)) { //Read File String[] lines = File.ReadAllLines(hwdFileSA); foreach (String s in lines) { if (String.IsNullOrEmpty(s)) continue; IntPtr prodID = IntPtr.Zero; IntPtr hwd = IntPtr.Zero; int tmpPID; String[] strs = s.Split(':'); Int32.TryParse(strs[0], out tmpPID); if (lstProID.Contains(tmpPID)) { prodID = new IntPtr(Convert.ToInt32(strs[0])); hwd = new IntPtr(Convert.ToInt32(strs[1])); dcthwdProId.Add(prodID, hwd); } } } //ASSA hwd if (File.Exists(hwdFileASSA)) { //Read File String[] lines = File.ReadAllLines(hwdFileASSA); foreach (String s in lines) { if (String.IsNullOrEmpty(s)) continue; IntPtr prodID = IntPtr.Zero; IntPtr hwd = IntPtr.Zero; int tmpPID; String[] strs = s.Split(':'); Int32.TryParse(strs[0], out tmpPID); if (lstProID.Contains(tmpPID)) { prodID = new IntPtr(Convert.ToInt32(strs[0])); hwd = new IntPtr(Convert.ToInt32(strs[1])); dctProc.Add(prodID.ToString(), hwd); } } } //ACT if (File.Exists(hwdFileAct)) { //Read File String[] lines = File.ReadAllLines(hwdFileAct); foreach (String s in lines) { if (String.IsNullOrEmpty(s)) continue; IntPtr prodID = IntPtr.Zero; String act = String.Empty; int tmpPID; String[] strs = s.Split(':'); Int32.TryParse(strs[0], out tmpPID); if (lstProID.Contains(tmpPID)) { prodID = new IntPtr(Convert.ToInt32(strs[0])); act = strs[1]; dctProcAct.Add(prodID.ToString(), act); } } } } else { if (File.Exists(hwdFileSA)) { File.Delete(hwdFileSA); } if (File.Exists(hwdFileASSA)) { File.Delete(hwdFileASSA); } if (File.Exists(hwdFileAct)) { File.Delete(hwdFileAct); } } } private void refreshData() { LoadActiveData(); } private void CheckRunningActs() { int processNum = 0; int.TryParse(cm.GetConfigurationData("ProcessNum"), out processNum); List<int> lstProID = new List<int>(); String saName = System.Configuration.ConfigurationManager.AppSettings["SAName"]; foreach (Process p in Process.GetProcessesByName(saName)) { lstProID.Add(p.Id); } if (lstProID.Count < processNum) { if (startUPType.Equals(StartUPType.SHENGWANG) || startUPType.Equals(StartUPType.FIVE)) { foreach (int i in lstccount.SelectedIndices) { String item = lstccount.Items[i].ToString(); String[] strs = item.ToString().Split('|'); String userAct = strs[0]; if (String.IsNullOrEmpty(userAct)) continue; if (!CheckActAlreadyRunning(userAct)) { Dictionary<String, String> dct = GetActDct(userAct); StartStoneage(dct, true, i + 1); System.Threading.Thread.Sleep(100); LoadActiveData(); } System.Threading.Thread.Sleep(3000); } } } } private void toolStripDropDownButton1_Click(object sender, EventArgs e) { } private void tlsddbStartUpType_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { string msg = String.Format("{0}", e.ClickedItem.Text); startUPType = (StartUPType)Enum.Parse(typeof(StartUPType), msg); this.tlsddbStartUpType.Text = msg; } } }
namespace DFC.ServiceTaxonomy.VersionComparison.Models.Parts { public class HtmlBodyPart { public string? Html { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; using LoowooTech.Stock.Tools; namespace LoowooTech.Stock { public partial class AttributeForm : Form { public AttributeForm(DataTable dataTable,string name) { InitializeComponent(); this.dataGridView1.DataSource = dataTable; this.Text = name; } private void button1_Click(object sender, EventArgs e) { //SaveFileDialog sf = new SaveFileDialog(); //sf.Filter = "Excel files(*.xls)|*.xlsx"; //if (sf.ShowDialog() == DialogResult.OK) //{ // if (dataGridView1.Rows.Count == 0)//判断是否有数据 // return;//返回 // IWorkbook excel = new HSSFWorkbook(); // ISheet sheet = excel.CreateSheet("sheet1"); // DataTable dt = (DataTable)dataGridView1.DataSource; // IRow headerRow = sheet.CreateRow(0); // foreach (DataColumn column in dt.Columns) // { // headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption); // } // int rowIndex = 1; // foreach (DataRow row in dt.Rows) // { // IRow dataRow = sheet.CreateRow(rowIndex); // foreach (DataColumn column in dt.Columns) // { // dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); // } // rowIndex++; // } // FileStream fl = new FileStream(sf.OpenFile().ToString(), FileMode.Append); // excel.Write(fl); // fl.Flush(); // fl.Close(); // MessageBox.Show("导出成功", "提示!"); //} ExportExcel ex = new ExportExcel(); ex.ExportToExcel(dataGridView1); //SaveFileDialog sf = new SaveFileDialog(); //sf.Filter = "EXCEL 文件(*.xls)|*.xls|Excel 文件(*.xlsx)|*.xlsx"; //HSSFWorkbook wb = new HSSFWorkbook(); //HSSFSheet sheet = (HSSFSheet)wb.CreateSheet("sheet1"); //if (sf.ShowDialog() == DialogResult.OK) //{ // if (dataGridView1.Rows.Count == 0) // { // return; // } // HSSFRow headRow = (HSSFRow)sheet.CreateRow(0); // for (int i = 0; i < dataGridView1.Columns.Count; i++) // { // HSSFCell headCell = (HSSFCell)headRow.CreateCell(i, CellType.String); // headCell.SetCellValue(dataGridView1.Columns[i].HeaderText); // } // for (int i = 0; i < dataGridView1.Rows.Count-1; i++) // { // HSSFRow row = (HSSFRow)sheet.CreateRow(i + 1); // for (int j = 0; j < dataGridView1.Columns.Count; j++) // { // HSSFCell cell = (HSSFCell)row.CreateCell(j); // if (dataGridView1[j, i].ValueType == typeof(string)) // { // cell.SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString()); // } // else // { // cell.SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString()); // } // } // } // for (int i = 0; i < dataGridView1.Columns.Count; i++) // { // sheet.AutoSizeColumn(i); // } // FileStream fs = new FileStream(sf.FileName, FileMode.OpenOrCreate, FileAccess.Write); // wb.Write(fs); // MessageBox.Show("导出成功"); //} } private void panel2_Resize(object sender, EventArgs e) { dataGridView1.Size = new Size(panel2.Bounds.Width, panel2.Bounds.Height); } private void AttributeForm_Load(object sender, EventArgs e) { dataGridView1.Size = new Size(panel2.Bounds.Width, panel2.Bounds.Height); } } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using TinhLuong.Models; using TinhLuongBLL; using System.Data.OleDb; namespace TinhLuong.Controllers { public class ImportMLLTBController : BaseController { // GET: ImportMLLTB SaveLog sv = new SaveLog(); [CheckCredential(RoleID = "IMPORT_EXCELPTTB_KDTM")] public ActionResult Index() { DMLoaiTB(); // sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Cac Khoan thu Nhap Ky 1"); return View(); } /// <summary> /// View data befor import /// </summary> /// <returns></returns> [CheckCredential(RoleID = "IMPORT_EXCELPTTB_KDTM")] public ActionResult Success() { DMLoaiTB(Session["LoaiTB"].ToString()); try { DataTable dt = (DataTable)Session["dtImport"]; if (dt.Rows.Count > 0 || dt != null) { string cl8 = dt.Rows[0]["DonViID"].ToString(); string cl9 = dt.Rows[0]["Nam"].ToString(); string cl10 = dt.Rows[0]["Thang"].ToString(); string cl11 = dt.Rows[0]["SLTB"].ToString(); string cl12 = dt.Rows[0]["TGMLL"].ToString(); return View(dt); } else if (dt.Rows.Count == 0 || dt == null) { setAlert("Cấu trúc tệp không chính xác hoặc không có dữ liệu để import", "error"); return Redirect("/import-mlltb"); } else { setAlert("Cấu trúc tệp không chính xác. Vui lòng chọn lại tệp!", "error"); return Redirect("/import-mlltb"); } } catch { setAlert("Cấu trúc tệp không chính xác. Vui lòng chọn lại tệp!", "error"); return Redirect("/import-mlltb"); } } /// <summary> /// import data to db /// </summary> /// <returns></returns> [CheckCredential(RoleID = "IMPORT_EXCELPTTB_KDTM")] public ActionResult ImportDB() { DataTable dt = (DataTable)Session["dtImport"]; string rows = ""; int dem = 0; if (dt.Rows.Count > 0) { try { if (new ImportExcelBLL().GetChotSo(int.Parse(dt.Rows[0]["Thang"].ToString()), int.Parse(dt.Rows[0]["Nam"].ToString()), Session[SessionCommon.DonViID].ToString(), "BangLuong") == false) { sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import phiếu báo mll thiết bị->Import khong Thanh Cong- Thang-" + dt.Rows[0]["Thang"].ToString() + "-nam-" + dt.Rows[0]["Nam"].ToString() + "-Do thang luong da chot"); setAlert("Dữ liệu đã chốt, không tiếp tục cập nhật được!", "error"); } else { bool delete = new ImportExcelBLL().Delete_MLLTB(int.Parse(dt.Rows[0]["Nam"].ToString()), int.Parse(dt.Rows[0]["Thang"].ToString()), Session["LoaiTB"].ToString()); if (delete) { for (int i = 0; i < dt.Rows.Count; i++) { try { var rs = new ImportExcelBLL().Insert_MLLTB(int.Parse(dt.Rows[i]["Nam"].ToString()), int.Parse(dt.Rows[i]["Thang"].ToString()), dt.Rows[i]["DonViID"].ToString(), Session["LoaiTB"].ToString(), int.Parse(dt.Rows[i]["TGMLL"].ToString()), int.Parse(dt.Rows[i]["SLTB"].ToString())); if (rs) dem++; else { rows = rows == "" ? rows + "" + ((i + 1).ToString()) : rows + ", " + ((i + 1).ToString()); } } catch(Exception ex) { rows = rows == "" ? rows + "" + ((i + 1).ToString()) : rows + ", " + ((i + 1).ToString()); continue; } } if (dem == dt.Rows.Count) { Session.Remove("dtImport"); sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import Thiết bị MLL->Import Thanh Cong"); setAlert("Import dữ liệu thành công", "success"); return Redirect("/import-mlltb"); } else if (0 < dem && dem < dt.Rows.Count) { string msg1 = " Dòng " + rows.ToString() + " import không thành công. Vui lòng import lại"; setAlertTime(msg1, "error"); sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import Thiết bị MLL->Import khong Thanh Cong- Thang-" + dt.Rows[0]["Thang"].ToString() + "-nam-" + dt.Rows[0]["Nam"].ToString() + "-Dong import k thanh cong-" + rows); return Redirect("/import-mlltb"); } else { sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import Thiết bị MLL->Import khong Thanh Cong"); setAlert("Import dữ liệu không thành công import không thành công. Vui lòng import lại", "error"); } } else setAlert("Import dữ liệu không thành công import không thành công. Vui lòng import lại", "error"); } }catch(Exception ex) { setAlert("Xảy ra lỗi: " + ex.Message, "error"); } } else { setAlert("Không có dữ liệu để import!", "error"); } return Redirect("/import-mlltb"); } /// <summary> /// read file import to get data /// </summary> /// <param name="file"></param> /// <returns></returns> [HttpPost] public ActionResult ImportexcelToDb(HttpPostedFileBase file,string LoaiTB) { Session.Add("LoaiTB", LoaiTB); if (file != null && file.ContentLength > 0) { string fileName = "fileUpload_" + Session[SessionCommon.Username].ToString() + "_" + DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second + "_" + file.FileName; string path1 = Path.Combine(Server.MapPath("~/Assets/Uploads/Import/"), RemoveUnicode.ConvertToUnsign2(fileName)); string extension = Path.GetExtension(file.FileName); string connString = ""; file.SaveAs(path1 + "" + extension); path1 = path1 + "" + extension; string[] validFileTypes = { ".xls", ".xlsx", ".csv" }; DataTable dt; if (validFileTypes.Contains(extension)) { if (extension == ".csv") { dt = Utility.ConvertCSVtoDataTable(path1); Session["dtImport"] = dt; } //Connection String to Excel Workbook else if (extension == ".xls") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 8.0;"; //connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; try { dt = Utility.ConvertXSLXtoDataTable(path1, connString); Session["dtImport"] = dt; } catch (Exception ex) { setAlert(ex.ToString(), "success"); } } else if (extension == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; dt = Utility.ConvertXSLXtoDataTable(path1, connString); Session["dtImport"] = dt; } DataTable dt1 = (DataTable)Session["dtImport"]; System.IO.File.Delete(path1); return Redirect("/import-mlltb/doc-file"); } else { setAlert("Vui lòng chỉ Upload tệp có định dạng .xls, .xlsx hoặc .csv", "error"); } } else { setAlert("Vui lòng chọn file", "error"); } return Redirect("/import-mlltb"); } public void DMLoaiTB(string selected = null) { List<SelectListItem> listItems = new List<SelectListItem>(); listItems.Add(new SelectListItem { Text = "BTS,NodeB", Value = "BTS_NODEB" }); listItems.Add(new SelectListItem { Text = "Băng rộng", Value = "BR" }); ViewBag.LoaiTB = new SelectList(listItems, "Value", "Text", selected); } } }
using LikDemo.Models; using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; namespace LikDemo.Services.Implementation { public class InvoicesService : IInvoicesService { private readonly IHttpClientFactory _httpClientFactory; public InvoicesService(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public async Task<ListInvoicesResponse> GetAll() { var client = _httpClientFactory.CreateClient("API"); var response = await client.GetFromJsonAsync<ListInvoicesResponse>("Invoices"); return response; } public async Task<HttpResponseMessage> CreateInvoice(CreateInvoiceRequest model) { var client = _httpClientFactory.CreateClient("API"); var response = await client.PostAsJsonAsync("Invoices", model); return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MoneyShare.Models; using MoneyShare.ViewModels; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace MoneyShare.Controllers { [Route("api/[controller]")] public class ResetPasswordController : Controller { private readonly UserManager<MemberModel> userManager; public ResetPasswordController(UserManager<MemberModel> userManager) { this.userManager = userManager; } // POST api/<controller> [HttpPost] public async Task<ActionResult> Post([FromBody] ResetPasswordViewModel model) { if (model.Password == model.ConfirmPassword) { var user = await userManager.FindByIdAsync(model.UserId); if (user != null) { var result = await userManager.ResetPasswordAsync(user, model.Token, model.Password); if (result.Succeeded) { return new OkResult(); } } } return new UnauthorizedResult(); } // PUT api/<controller>/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/<controller>/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Paralepipedo { class Program { static void Main(string[] args) { Paralepipedo para = new Paralepipedo(10,24,16); Console.WriteLine("The volume is " + para.Volume()); Console.WriteLine("The total area is " + para.TotalArea()); Console.WriteLine(para.ConvertToString()); Console.WriteLine(para.IsACube()); Console.WriteLine(para.Is3D()); Console.ReadKey(); } } }
using Kliiko.Ui.Tests.WebPages.StaticPages; using OpenQA.Selenium; using System.Collections.Generic; namespace Kliiko.Ui.Tests.WebPages.Dashboard.AccountProfile { //user.kliiko.diatomdemo.com:8080/dashboard#/account-profile class AccountProfilePage : WebPage { private static readonly By ButtonUpgradePlan = By.CssSelector(".btn.btn-dashboard-menu.ng-scope"); private static readonly By ButtonAccountManagers = By.CssSelector(".account-manager.pull-right"); private static readonly By PlaceHolderManualTxt = By.CssSelector(".col-md-6.dashboard-index.text-center"); private static readonly IList<By> ListLocators = new List<By>(); public static void ExpectWebElements() { if (ListLocators.Count == 0) { ListLocators.Add(ButtonUpgradePlan); ListLocators.Add(ButtonAccountManagers); ListLocators.Add(PlaceHolderManualTxt); } HeaderBlock.ExpectedWebElements(); FooterBlock.ExpectedWebElements(); } public static void ClickButtonUpgradePlan() { Web.Click(ButtonUpgradePlan); } public static void ClickButtonAccountManagers() { Web.Click(ButtonAccountManagers); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace LoginFrame { public partial class FrmQueryReward : Form { DataTable dsLog; public FrmQueryReward() //初始化组件 { InitializeComponent(); } private void dtp_publishDate_ValueChanged(object sender, EventArgs e) //选择日期 { this.txt_publishDate.Text = this.dtp_publishDate.Value.ToShortDateString(); } private void txt_publishDate_DoubleClick(object sender, EventArgs e) //双击日期框 清空 { this.txt_publishDate.Text = ""; } private void Btn_Query_Click(object sender, EventArgs e) //搜索条件 { string sqlstr = " where 1=1 "; if (this.Txt_No.Text != "") { sqlstr += " and U_No like '%" + this.Txt_No.Text + "%'"; } if (this.Txt_Number.Text != "") { sqlstr += " and U_Custom like '%" + this.Txt_Number.Text + "%'"; } if (this.txt_publishDate.Text != "") { sqlstr += " and convert(char(11),U_LoginDate,20) ='" + this.txt_publishDate.Text + "'"; } HWhere.Text = sqlstr; BindData(""); string rows = this.textBox1.Text; DAL.dalBook.Update("U_Row", rows, 5); } public void BindData(string strClass) { string Number = this.textBox1.Text; int number; if (int.TryParse(Number, out number)) { if (number < 40 && number > 10) { this.HPageSize.Text = Number; } } int DataCount = 0; int NowPage = 1; int AllPage = 0; int PageSize = Convert.ToInt32(HPageSize.Text); //每页显示行数 switch (strClass) //下一页 { case "next": NowPage = Convert.ToInt32(HNowPage.Text) + 1; break; case "up": NowPage = Convert.ToInt32(HNowPage.Text) - 1; break; case "end": NowPage = Convert.ToInt32(HAllPage.Text); break; case "refresh": NowPage = Convert.ToInt32(HNowPage.Text); break; default: break; } dsLog = DAL.performance.GetReward(NowPage, PageSize, out AllPage, out DataCount, HWhere.Text); if (dsLog.Rows.Count == 0 || AllPage == 1) { LBEnd.Enabled = false; LBHome.Enabled = false; LBNext.Enabled = false; LBUp.Enabled = false; } else if (NowPage == 1) { LBHome.Enabled = false; LBUp.Enabled = false; LBNext.Enabled = true; LBEnd.Enabled = true; } else if (NowPage == AllPage) { LBHome.Enabled = true; LBUp.Enabled = true; LBNext.Enabled = false; LBEnd.Enabled = false; } else { LBEnd.Enabled = true; LBHome.Enabled = true; LBNext.Enabled = true; LBUp.Enabled = true; } this.dataGridViewSummary1.DataSource = dsLog.DefaultView; this.dataGridViewSummary1.SummaryColumns = new string[] { "金额" }; this.dataGridViewSummary1.SummaryRowVisible = true; this.dataGridViewSummary1.SummaryRowForeColor = Color.White; PageMes.Text = string.Format("[每页{0}条 第{1}页/共{2}页 共{3}条]", PageSize, NowPage, AllPage, DataCount); HNowPage.Text = Convert.ToString(NowPage++); HAllPage.Text = AllPage.ToString(); } /*开始加载窗体后*/ private void FrmQueryReward_Load(object sender, EventArgs e) { this.checkBox1.Checked = DAL.dalBook.getBool(5); this.textBox1.Text = DAL.dalBook.getString(5); this.HPageSize.Text = DAL.dalBook.getString(5); if (checkBox1.Checked) BindData(""); } private void LBHome_Click(object sender, EventArgs e) { BindData(""); } private void LBUp_Click(object sender, EventArgs e) { BindData("up"); } private void LBNext_Click(object sender, EventArgs e) { BindData("next"); } private void LBEnd_Click(object sender, EventArgs e) { BindData("end"); } string UName; public void FrmUName_getUName(string UserName) { UName = UserName; this.Txt_Number.Text = UserName; } private void button_Custom_Click(object sender, EventArgs e) { FrmUName frm = new FrmUName(""); frm.getUName += new GetUName(FrmUName_getUName); frm.ShowDialog(); } private void Txt_Number_TextChanged(object sender, EventArgs e) { this.textBox_Name.Text = DAL.performance.getName(UName); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) DAL.dalBook.Update("U_Check", "1", 5); else DAL.dalBook.Update("U_Check", "0", 5); } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Estacionamento.Map; namespace Infra.Mapeamentos { public class MappingEstacionamentoVagas : EntityTypeConfiguration<EstacionamentoVagasMap> { public MappingEstacionamentoVagas() { // Primary Key this.HasKey(t => t.IdEstacionamento); // Properties //this.Property(t => t.IdUser) // .IsRequired() // .HasMaxLength(128); //this.Property(t => t.IdUserCancel) // .IsRequired() // .HasMaxLength(128); //this.Property(t => t.IdUserSuspensao) // .IsRequired() // .HasMaxLength(128); // Table & Column Mappings this.ToTable("EstacionamentoVagas"); // Relationships } } }
using BattleEngine.Actors; using BattleEngine.Actors.Units; using BattleEngine.Engine; using BattleEngine.Output; using BattleEngine.Utils; namespace BattleEngine.Modules { public class BattleUnitDieModule : BattleModule { private Vector<BattleObject> _temp = new Vector<BattleObject>(); public BattleUnitDieModule() { } override public void preTick(BattleContext context, int tick, int deltaTick) { _temp.length = 0; context.actors.units.getActors(typeof(BattleUnit), _temp); foreach (BattleUnit unit in _temp) { if (unit.isDied) { var evt = context.output.enqueueByFactory<UnitDieEvent>(); evt.tick = tick; evt.objectId = unit.objectId; var removeEvt = context.output.enqueueByFactory<UnitRemoveEvent>(); removeEvt.tick = tick; removeEvt.objectId = unit.objectId; unit.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Entity; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TMan.Helpers; namespace TMan { public partial class AdministratorDialog : RegularUserDialog { private string SelectedUserCredentialsSerialized; public AdministratorDialog() { InitializeComponent(); } private void AdministratorDialog_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void tabUsersManagement_Click(object sender, EventArgs e) { } private void tabUsersManagement_Enter(object sender, EventArgs e) { using (TManDBEntities entities = new TManDBEntities()) { cbAllUsers.Items.Clear(); CommonHelper.PopulateComboboxWithAllUsers(cbAllUsers, entities); } } private void cbAllUsers_SelectedIndexChanged(object sender, EventArgs e) { var userId = Convert.ToInt32(((System.Windows.Forms.ComboBox)(sender)).SelectedItem.ToString().Split(',')[1].Split(':')[1]); using (TManDBEntities entities = new TManDBEntities()) { var userFromDatabase = (from user in entities.TMUsers where user.UserId == userId select user).FirstOrDefault(); FillUpBasicUserInformation(userFromDatabase); SelectedUserCredentialsSerialized = string.Format(Properties.Resources.USER_SERIALIZED_TEMPL , userFromDatabase.UserId , userFromDatabase.Username , userFromDatabase.Password , userFromDatabase.Role); } } private void FillUpBasicUserInformation(TMUser userFromDatabase = null) { tbUserName.Text = userFromDatabase != null ? userFromDatabase.Username : string.Empty; tbPassword.Text = userFromDatabase != null ?userFromDatabase.Password : string.Empty; cbRole.Text = userFromDatabase != null ?userFromDatabase.Role : string.Empty; tbId.Text = userFromDatabase != null ?userFromDatabase.UserId.ToString() : string.Empty; } private void btnSaveUserChanges_Click(object sender, EventArgs e) { var latestUserValuesSerialized = string.Format(Properties.Resources.USER_SERIALIZED_TEMPL , tbId.Text , tbUserName.Text , tbPassword.Text , cbRole.Text); if (this.SelectedUserCredentialsSerialized == latestUserValuesSerialized) return; try { using (TManDBEntities entities = new TManDBEntities()) { entities.Database.Connection.Open(); var latestUserValuesSerializedSplitted = latestUserValuesSerialized.Split('_'); var user = new TMan.TMUser { UserId = Convert.ToInt32(latestUserValuesSerializedSplitted[0]), Username = latestUserValuesSerializedSplitted[1], Password = latestUserValuesSerializedSplitted[2], Role = latestUserValuesSerializedSplitted[3] }; entities.TMUsers.Attach(user); entities.Entry(user).State = EntityState.Modified; entities.SaveChanges(); } MessageBox.Show("Update was successful!", "Info", MessageBoxButtons.OK); } catch (Exception) { MessageBox.Show("Update failed", "Info", MessageBoxButtons.OK); } } private void btnAddNewUser_Click(object sender, EventArgs e) { var addNewUserDialog = new AddNewUserDialog(); addNewUserDialog.ShowDialog(); using (TManDBEntities entities = new TManDBEntities()) { cbAllUsers.Items.Clear(); CommonHelper.PopulateComboboxWithAllUsers(cbAllUsers, entities); } FillUpBasicUserInformation(); } private void btnDeleteUser_Click(object sender, EventArgs e) { if (tbId.Text == string.Empty) return; try { using (TManDBEntities entities = new TManDBEntities()) { entities.Database.Connection.Open(); TMUser userFOrDelete = new TMUser() { UserId = Convert.ToInt32(tbId.Text) }; entities.TMUsers.Attach(userFOrDelete); entities.TMUsers.Remove(userFOrDelete); entities.SaveChanges(); cbAllUsers.Items.Clear(); CommonHelper.PopulateComboboxWithAllUsers(cbAllUsers, entities); FillUpBasicUserInformation(); cbAllUsers.Text = string.Empty; } MessageBox.Show("The user was successfuly deleted!", "Info", MessageBoxButtons.OK); } catch (Exception ex) { MessageBox.Show("The user couldn't be deleted. See more:\n" + ex.Message, "Info", MessageBoxButtons.OK); } } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ImdbApi.Data; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Microsoft.AspNetCore.Authorization; namespace ImdbApi.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class MovieController : ControllerBase { List<Movie> movies = new List<Movie>(); Movie movie = new Movie(); public MovieController() { setupData(); } // GET: api/Movie [HttpGet] public string GetAll() { return JsonConvert.SerializeObject(movies); } // GET: api/Movie/5 [HttpGet("{rank}")] public string Get(int rank) { return JsonConvert.SerializeObject(movies.Find(m => m.Rank == rank)); } //Setup Data private void setupData() { movies = new List<Movie>(); Movie movie = new Movie(); string data = System.IO.File.ReadAllText(@"Data/imdb.json"); movies = JsonConvert.DeserializeObject<List<Movie>>(data); } } }
using System.Reflection; [assembly: AssemblyTitle("AdvancedLocationLoader")] [assembly: AssemblyDescription("Add new content to stardew valley without needing to learn C#!")] [assembly: AssemblyVersion("1.4.6")] [assembly: AssemblyFileVersion("1.4.6")]
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // On-screen help prompts, dynamically adapting to the situation public class ClueHUD : MonoBehaviour { public GameObject FPPTerminalPrompts; public GameObject HoveredOverNodePrompt; public GameObject HoveredOverParamPrompt; public GameObject EditingParamHoveredPrompt; public GameObject EditingParamUnhoveredPrompt; public GameObject CopyNodePrompt; public GameObject CopyPasteNodePrompt; public GameObject PasteNodePrompt; // Node linking prompts public GameObject LinkNodePrompt; public Text LinkNodeCaption; public GameObject currentPromptSet = null; public GameObject currentPromptCaller = null; public GameObject alwaysOnFlowChartPrompt = null; public GameObject alwaysOnCodeViewerPrompt = null; public GameObject promptBackgroundLeft = null; public GameObject promptBackgroundRight = null; private EditorProgram[] editors; public GameObject hoveredNode; public EditorProgram.LinkingMode potentialLinkingMode; // Start is called before the first frame update void Start() { List<EditorProgram> editorsInScene = new List<EditorProgram>(); foreach(GameObject obj in FindObjectsOfType<GameObject>()) { if(obj.GetComponent<EditorProgram>()) { editorsInScene.Add(obj.GetComponent<EditorProgram>()); } } editors = editorsInScene.ToArray(); } // Update is called once per frame void Update() { UpdatePrompts(new List<GameObject> { FPPTerminalPrompts, HoveredOverNodePrompt, HoveredOverParamPrompt, EditingParamHoveredPrompt, EditingParamUnhoveredPrompt }); } public void SetCurrentPrompt(GameObject promptSet, GameObject caller) { currentPromptSet = promptSet; currentPromptCaller = caller; } void UpdatePrompts(List<GameObject> promptSets) { EditorProgram currentEditor = null; alwaysOnFlowChartPrompt.SetActive(false); alwaysOnCodeViewerPrompt.SetActive(false); promptBackgroundLeft.SetActive(false); promptBackgroundRight.SetActive(false); foreach (EditorProgram editor in editors) { if (editor.EditorActive) { if (editor.editorMode == EditorProgram.EditorMode.FlowChart) { alwaysOnFlowChartPrompt.SetActive(true); promptBackgroundLeft.SetActive(true); } else { alwaysOnCodeViewerPrompt.SetActive(true); } currentEditor = editor; break; } } if (currentEditor && currentEditor.EditorActive && !currentEditor.editingNodeProperty && !currentEditor.linkingNodes) { if (CopyPasteNodePrompt.activeInHierarchy || CopyNodePrompt.activeInHierarchy || PasteNodePrompt.activeInHierarchy) { promptBackgroundRight.SetActive(true); } } else { promptBackgroundRight.SetActive(false); CopyPasteNodePrompt.SetActive(false); CopyNodePrompt.SetActive(false); PasteNodePrompt.SetActive(false); } if(currentEditor && currentEditor.EditorActive && currentEditor.linkingNodes && hoveredNode) { if(currentEditor.linkingNodeMode == EditorProgram.LinkingMode.NextNode) { if(!hoveredNode.GetComponent<ProgramStart>()) { LinkNodeCaption.text = "Set as next node"; LinkNodePrompt.SetActive(true); } if(hoveredNode == currentEditor.linkingNodesObjects[0]) { LinkNodeCaption.text = "Remove link"; LinkNodePrompt.SetActive(true); } } else { if (!hoveredNode.GetComponent<ProgramStart>()) { LinkNodeCaption.text = "Set as first node"; LinkNodePrompt.SetActive(true); } if (hoveredNode == currentEditor.linkingNodesObjects[0]) { LinkNodeCaption.text = "Remove link"; LinkNodePrompt.SetActive(true); } } } else if(currentEditor && currentEditor.EditorActive && !currentEditor.linkingNodes && hoveredNode && !currentEditor.editingNodeProperty && !currentEditor.choosingNode && !currentEditor.choosingFunctionCall) { if (!hoveredNode.GetComponent<ProgramEnd>()) { if (potentialLinkingMode == EditorProgram.LinkingMode.FirstBodyNode && hoveredNode.GetComponent<LogicalBlock>()) { LinkNodeCaption.text = hoveredNode.GetComponent<WhileLoop>() ? "Start loop" : (hoveredNode.GetComponent<ElseBlock>() ? "Start\nElse Block" : "Start\nIf statement"); LinkNodePrompt.SetActive(true); } else { LinkNodeCaption.text = "Connect to\nnext node"; LinkNodePrompt.SetActive(true); } } } else { LinkNodePrompt.SetActive(false); } foreach (GameObject promptSet in promptSets) { if (currentPromptSet != promptSet) { promptSet.SetActive(false); } else { if (currentEditor == null || (currentEditor != null && (!currentEditor.choosingNode && !currentEditor.choosingFunctionCall))) { promptSet.SetActive(true); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartLib; using KartObjects; using System.ComponentModel; namespace KartSystem { public class Recipe : SimpleDbEntity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Рецепты"; } } [DisplayName("Наименование товара или ТК")] public long IdGood { get; set; } [DisplayName("Брутто, г")] public double Brutto { get; set; } [DisplayName("Нетто, г")] public double Netto { get; set; } [DisplayName("Короткое наименование")] public string NameShort { get; set; } } }
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Flurl.Http; using Flurl.Http.Configuration; using Microsoft.Extensions.Logging; using Polly; using Polly.Contrib.WaitAndRetry; using Polly.Extensions.Http; using Polly.Timeout; using Sibusten.Philomena.Client.Logging; namespace Sibusten.Philomena.Client { public static class PhilomenaClientRetryLogic { public static void UseDefaultHttpRetryLogic() { ILogger logger = Logger.Factory.CreateLogger(typeof(PhilomenaClientRetryLogic)); // Use a jittered exponential backoff var delay = Backoff.DecorrelatedJitterBackoffV2 ( medianFirstRetryDelay: TimeSpan.FromSeconds(1), retryCount: 4 ); // Retry on transient http errors var defaultRetryPolicy = HttpPolicyExtensions .HandleTransientHttpError() .Or<TimeoutRejectedException>() .WaitAndRetryAsync(delay, (result, timeout, attempt, context) => { logger.LogWarning(result.Exception, "Request #{Attempt} failed. Retrying in {Timeout}", attempt, timeout); }); // Timeout requests var defaultTimeoutPolicy = Policy .TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(2)); // Wrap the default policies var defaultPolicy = Policy.WrapAsync(defaultRetryPolicy, defaultTimeoutPolicy); // Configure Flurl to use the backoff policy by overriding the HttpClientFactory FlurlHttp.Configure(settings => { settings.HttpClientFactory = new PollyHttpClientFactory(defaultPolicy); }); } /// <summary> /// A <see cref="DefaultHttpClientFactory"/> which wraps requests in a Polly policy /// </summary> public class PollyHttpClientFactory : DefaultHttpClientFactory { private AsyncPolicy<HttpResponseMessage> _retryPolicy; public PollyHttpClientFactory(AsyncPolicy<HttpResponseMessage> retryPolicy) { _retryPolicy = retryPolicy; } public override HttpMessageHandler CreateMessageHandler() { return new PolicyHandler(_retryPolicy) { InnerHandler = base.CreateMessageHandler() }; } public class PolicyHandler : DelegatingHandler { private AsyncPolicy<HttpResponseMessage> _retryPolicy; public PolicyHandler(AsyncPolicy<HttpResponseMessage> retryPolicy) { _retryPolicy = retryPolicy; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return _retryPolicy.ExecuteAsync(ct => base.SendAsync(request, ct), cancellationToken); } } } } }
using System; using System.Diagnostics; using System.Linq; using Android.App; using Android.Content.Res; using Android.Graphics; using Android.Graphics.Drawables; using Android.OS; using Android.Views; using Android.Widget; using MvvmCross.Binding.BindingContext; using MvvmCross.Core.ViewModels; using MvvmCross.Droid.Shared.Attributes; using ResidentAppCross.Droid.Views.AwesomeSiniExtensions; using ResidentAppCross.Droid.Views.Sections; using ResidentAppCross.ViewModels; using ResidentAppCross.ViewModels.Screens; using Orientation = Android.Widget.Orientation; /* namespace ResidentAppCross.Droid.Views { [Activity(Label = "Apartment Apps", MainLauncher = false, Icon = "@drawable/accounticon", NoHistory = false,WindowSoftInputMode = SoftInput.StateVisible | SoftInput.AdjustResize)] public class TestFormView : ViewBase { private FrameLayout _screenLayout; protected override void OnViewModelSet() { ActionBar.SetBackgroundDrawable(new ColorDrawable(AppTheme.SecondaryBackgoundColor)); base.OnViewModelSet(); SetContentView(ScreenLayout); var tx = FragmentManager.BeginTransaction(); tx.Add(ScreenLayout.Id,new TestForm(), "form"); tx.Commit(); */ // //ViewModel.PropertyChanged += ViewModelOnPropertyChanged; // //SetContentView(Resource.Layout.LoginViewLayout); // // var layout = new LinearLayout(this) // { // Id = 5, // Background = new ColorDrawable(AppTheme.DeepBackgroundColor), // Orientation = Orientation.Vertical // }; // // this.AddContentView(layout, // new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); // // var headerSection = new HeaderSection(this) // { // HeaderImageResource = Resource.Drawable.L_LocationOk, // HeaderImageColor = Color.ParseColor("#4199e6") // }; // var set = this.CreateBindingSet<TestFormView, TestFormViewModel>(); // set.Bind(headerSection.HeaderLabelView).For(l => l.Text).To(vm => vm.HeaderTitle); // set.Bind(headerSection.HeaderSubLabelView).For(l => l.Text).To(vm => vm.SubheaderTitle); // set.Apply(); // // layout.AddView(headerSection.ContentView); // // layout.AddView(new Space(this).WithWidthMatchParent().WithHeight(10)); // // var spinnerSelectionSection = new SpinnerSelectionSection(this) // { // HeaderText = "Spinner Selection Section" // }; // layout.AddView(spinnerSelectionSection.ContentView); // // spinnerSelectionSection.Spinner.BindTo(new List<string>() {"Hello, World", "Anything Else", "Finnally"}, // s => s, this); // //// layout.AddView(new Space(this).WithWidthMatchParent().WithHeight(10)); //// //// layout.AddView(new TextViewSection(this) //// { //// HeaderText = "Text View Section" //// }.ContentView); // // layout.AddView(new Space(this).WithWidthMatchParent().WithHeight(10)); // // var labelWithButtonSection = new LabelWithButtonSection(this) // { // HeaderText = "Label With Button Section", // ButtonText = "Open Dialog" // }; // // // var drawable = ContextCompat.GetDrawable(this, Resource.Drawable.L_LocationOk); // var misFotos = new[] // { // drawable, drawable, drawable, drawable, drawable, drawable, drawable, drawable, drawable, drawable, // drawable // }; // // // var imageBundle = new ImageBundleViewModel(); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "http://i.cbc.ca/1.3376224.1450794847!/fileImage/httpImage/image.jpg_gen/derivatives/4x3_620/tundra-tea-toss.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "https://timedotcom.files.wordpress.com/2015/12/scott-kelly-photograph-iss-9th-month02.jpg?quality=75&strip=color&w=838"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "https://timedotcom.files.wordpress.com/2015/12/top-100-photos-of-the-year-2015-087.jpg?quality=75&strip=color&w=838"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = new Uri("http://www.self.com/wp-content/uploads/2016/01/birth-photo-2.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "http://i2.cdn.turner.com/cnnnext/dam/assets/160107172135-33-week-in-photos-0107-restricted-super-169.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "http://www.telegraph.co.uk/content/dam/Travel/leadAssets/34/97/comedy-hamster_3497562a-large.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = new Uri("https://www.google.com/photos/about/images/auto-awesome/bkg-start.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = new Uri("https://www.google.com/photos/about/images/auto-awesome/motion-module/motion-1.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "http://images.nationalgeographic.com/wpf/media-live/photos/000/911/cache/man-ocean-phytoplankton_91111_600x450.jpg"), // }); // imageBundle.RawImages.Add(new ImageBundleItemViewModel() // { // Uri = // new Uri( // "http://i2.cdn.turner.com/cnnnext/dam/assets/160201140511-05-china-moon-surface-photos-super-169.jpg"), // }); // // // labelWithButtonSection.Button.Click += (sender, args) => // { // var fragment = new NotificationDialog(); // fragment.Items.Add(new NotificationDialogItem() {Title = "Hello"}); // fragment.Items.Add(new NotificationDialogItem() {Title = "Mister"}); // fragment.Items.Add(new NotificationDialogItem() {Title = "World"}); // fragment.Items.Add(new NotificationDialogItem() {Title = "Woop Woop"}); // fragment.Show(this.FragmentManager, "dialog"); // }; // // // layout.AddView(labelWithButtonSection.ContentView); // // layout.AddView(new Space(this).WithWidthMatchParent().WithHeight(10)); // // layout.AddView(new LabelWithLabelSection(this) // { // HeaderText = "Label With Label Section", // LabelText = "Some Info" // }.ContentView); // // layout.AddView(new Space(this).WithWidthMatchParent().WithHeight(10)); // // var photoGallerySection = new PhotoGallerySection(this) // { // HeaderText = "Photo Gallery Section", // ButtonText = "Add Photo" // }; // // photoGallerySection.BindTo(imageBundle); // layout.AddView(photoGallerySection.ContentView); /* } public FrameLayout ScreenLayout { get { if (_screenLayout == null) { _screenLayout = new FrameLayout(this) { Id = 1234 , }.WithBackgroundColor(AppTheme.DeepBackgroundColor).WithDimensionsMatchParent(); } return _screenLayout; } set { _screenLayout = value; } } } }*/
using System.Collections.Generic; using System.Linq; using AutoMapper; using XH.Commands.Security; using XH.Domain.Exceptions; using XH.Domain.Security; using XH.Infrastructure.Command; using XH.Infrastructure.Domain.Repositories; namespace XH.Command.Handlers { public class RolesCommandHandler : ICommandHandler<CreateRoleCommand>, ICommandHandler<UpdateRoleCommand>, ICommandHandler<DeleteRoleCommand> { private readonly IMapper _mapper; private readonly IRepository<Role> _roleRepository; private readonly IRepository<User> _userRepository; public RolesCommandHandler(IMapper mapper, IRepository<Role> roleRepository, IRepository<User> userRepository) { _mapper = mapper; _roleRepository = roleRepository; _userRepository = userRepository; } public void Handle(CreateRoleCommand command) { // Check name if (_roleRepository.Query(it => it.Name.ToLower() == command.Name.ToLower() && it.TenantId == command.TenantId).Any()) { throw new DomainException($"名称:{command.Name}已经存在"); } var role = _mapper.Map<Role>(command); role.Permissions = role.Permissions?.Distinct().ToList() ?? new List<string>(); _roleRepository.Insert(role); } public void Handle(UpdateRoleCommand command) { // Check id if (_roleRepository.Query(it => it.TenantId == command.TenantId && it.Id != command.Id && it.Name.ToLower() == command.Name.ToLower()).Any()) { throw new DomainException($"名称:{command.Name}已经存在"); } // Check exist var role = _roleRepository.Get(command.Id); if (role == null || role.TenantId != command.Id) { throw new EntityNotFoundException($"角色:{command.Id}不存在"); } _mapper.Map(command, role); role.Permissions = role.Permissions?.Distinct().ToList() ?? new List<string>(); _roleRepository.Update(role); } public void Handle(DeleteRoleCommand command) { var role = _roleRepository.Get(command.Id); if (role == null || role.TenantId != command.TenantId) { throw new EntityNotFoundException("角色不存在"); } // Check if any user correlate with this role if (_userRepository.Query(it => it.Roles != null && it.Roles.Contains(command.Id)).Any()) { throw new EntityCorrelatedWithOthersException($"角色:{role.Name}有关联的用户,不能删除"); } _roleRepository.Delete(command.Id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Xml; using IRAP.Global; namespace IRAP.Entities.MDM { /// <summary> /// 双环批次管理中质量检验项目 /// </summary> public class InspectionItem { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// 检验项目叶标识 /// </summary> public int T20LeafID { get; set; } /// <summary> /// 检验项目代码 /// </summary> public string T20Code { get; set; } /// <summary> /// 检验项目名称 /// </summary> public string T20Name { get; set; } /// <summary> /// 默认放大数量级 /// </summary> public int Scale { get; set; } /// <summary> /// 计量单位 /// </summary> public string UnitOfMeasure { get; set; } /// <summary> /// 历史记录 /// [RF25] /// [Row FactID="" Metric01=""/] /// [/RF25] /// </summary> public string DataXML { get; set; } public List<PPParamValue> ResolveDataXML() { string strProcedureName = string.Format( "{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name); List<PPParamValue> rlt = new List<PPParamValue>(); XmlDocument xdoc = new XmlDocument(); try { xdoc.LoadXml(DataXML); } catch (XmlException err) { WriteLog.Instance.Write(err.Message, strProcedureName); return new List<PPParamValue>(); } long factID = 0; string metric01 = ""; foreach (XmlNode node in xdoc.SelectNodes("RF25/Row")) { if (node.Attributes["FactID"] != null) factID = Tools.ConvertToInt64(node.Attributes["FactID"].Value, 0); else factID = 0; if (node.Attributes["Metric01"] != null) metric01 = node.Attributes["Metric01"].Value; else metric01 = ""; rlt.Add( new PPParamValue() { FactID = factID, Metric01 = metric01, }); } return rlt; } public InspectionItem Clone() { return MemberwiseClone() as InspectionItem; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; using System.Configuration; namespace PayRoll { public partial class Login : System.Web.UI.Page { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void btnsignin_Click(object sender, EventArgs e) { if (ddluser.SelectedValue == "Administrator") { con.Open(); SqlCommand cmd = new SqlCommand("select UserName,Password from Administrator where UserName='" + txtuname.Text + "' and Password='" + txtpwd.Text + "'", con); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { if (txtuname.Text == dr[0].ToString() && txtpwd.Text == dr[1].ToString()) { Session["luname"] = txtuname.Text; Session["lpass"] = txtpwd.Text; Response.Redirect("Dashboard.aspx"); } else { Response.Redirect("Login.aspx"); } } else { Response.Redirect("Login.aspx"); } con.Close(); } else if (ddluser.SelectedValue == "Employee") { con.Open(); SqlCommand cmd = new SqlCommand("select Name,Password from Employee where Name='" + txtuname.Text + "' and Password='" + txtpwd.Text + "'", con); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { //if (txtuname.Text == dr.GetValue(0).ToString() && txtpwd.Text == dr.GetValue(1).ToString()) //{ // Session["euname"] = txtuname.Text; // Session["epass"] = txtpwd.Text; // Response.Redirect("WorkSheet.aspx"); //} Response.Redirect("WorkSheet.aspx"); } else { Response.Redirect("Login.aspx"); } //else //{ // Response.Redirect("Login.aspx"); //} con.Close(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ServiceDeskSVC.DataAccess.Models; namespace ServiceDeskSVC.DataAccess { public interface IHelpDeskTasksStatusRepository { List<HelpDesk_TaskStatus> GetAllTaskStatuses(); bool DeleteTaskStatus(int id); int CreateTaskStatus(HelpDesk_TaskStatus taskStatus); int EditTaskStatus(int id, HelpDesk_TaskStatus taskStatus); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Worx.ApiExpress.Utils; namespace Worx.ApiExpress.Runtime { public class CacheService : BaseService, ICacheService { public CacheService() { this.ServiceType = ServiceType.DBCACHE; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; using Dapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using RestApiWithDapper.Interfaces; using RestApiWithDapper.Models; namespace RestApiWithDapper.Controllers { [Route("api/employee")] [ApiController] public class EmployeeController : ControllerBase { private readonly IDapper Idapper; public EmployeeController(IDapper idapper) { Idapper = idapper; } [HttpPost] public async Task<int> Create([FromBody] Employee employee) { var dbparams = new DynamicParameters(); dbparams.Add("@FirstName", employee.FirstName, DbType.String); dbparams.Add("@LastName", employee.LastName, DbType.String); dbparams.Add("@Department", employee.Department, DbType.String); dbparams.Add("@JobTitle", employee.JobTitle, DbType.String); dbparams.Add("@PhoneExtension", employee.PhoneExtension, DbType.String); dbparams.Add("@Salary", employee.Salary, DbType.String); dbparams.Add("@Bonus", employee.Bonus, DbType.String); var result = await Task.FromResult(Idapper.Insert<string>("SPInsertInfo", dbparams,commandType: CommandType.StoredProcedure)); return 0; } [HttpGet] public async Task<List<Employee>> Get() { var result = await Task.FromResult(Idapper.GetAll<Employee>("SPGetAllEmployeeData", null, commandType: CommandType.StoredProcedure)); return result; } [HttpGet("{Id:int}")] public async Task<Employee> Get(int Id) { var dbparams = new DynamicParameters(); dbparams.Add("@id", Id, DbType.Int32); var result = await Task.FromResult(Idapper.Get<Employee>($"SPGetParticularEmployee", dbparams, commandType: CommandType.StoredProcedure)); return result; } [HttpDelete("{Id:int}")] public async Task<int> Delete(int Id) { var dbparams = new DynamicParameters(); dbparams.Add("@id", Id, DbType.Int32); var result = await Task.FromResult(Idapper.Execute($"SPDeleteEmployee", dbparams, commandType: CommandType.StoredProcedure)); return result; } [HttpPut] public async Task<int> Update([FromBody] Employee employee) { var dbparams = new DynamicParameters(); dbparams.Add("@FirstName", employee.FirstName, DbType.String); dbparams.Add("@LastName", employee.LastName, DbType.String); dbparams.Add("@Department", employee.Department, DbType.String); dbparams.Add("@JobTitle", employee.JobTitle, DbType.String); dbparams.Add("@PhoneExtension", employee.PhoneExtension, DbType.String); dbparams.Add("@Salary", employee.Salary, DbType.String); dbparams.Add("@Bonus", employee.Bonus, DbType.String); dbparams.Add("@id", employee.EmployeeId, DbType.Int32); var updateArticle = await Task.FromResult(Idapper.Update<string>("SPUpdatEmployee", dbparams, commandType: CommandType.StoredProcedure)); return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using KartObjects.Entities.Documents; namespace KartSystem { public class RevaluationDocument:InvoiceDocument { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Акт переоценки"; } } public RevaluationDocument(Document document) { this.Comment = document.Comment; this.DateDoc = document.DateDoc; this.Id = document.Id; this.IdDocType = document.IdDocType; this.IdSupplier = document.IdSupplier; this.IdWarehouse = document.IdWarehouse; this.IsNew = document.IsNew; this.MarginSumDoc = document.MarginSumDoc; this.Number = document.Number; this.Status = document.Status; this.SumDoc = document.SumDoc; _docSpec = new List<InvoiceGoodSpecRecord>(); } public RevaluationDocument() { _docSpec = new List<InvoiceGoodSpecRecord>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DTO; using Dapper; using System.Data; namespace DAO { public class DB_KhachHang { public static List<DTO_KhachHang> getDSKhachHangTheoMa(string maKH) { DBConnect _dbContext = new DBConnect(); using (IDbConnection _dbConnection = _dbContext.CreateConnection()) { var output = _dbConnection.Query<DTO_KhachHang>($"select * from khachhang where makh='{maKH}'").ToList(); return output; } } } }
using System; namespace Mastermind.NET.Utility { public static class StringExtension { /// <summary> /// Convenience extension for checking if a string is null, empty, or whitespace, so you don't have to /// wrap everything in String.IsNullOrWhiteSpace(). /// </summary> /// <param name="checkString">String to be checked.</param> /// <returns>True if null, empty, or whitespace. Otherwise false.</returns> public static bool IsNullOrWhiteSpace(this string checkString) { return String.IsNullOrWhiteSpace(checkString); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PlantPlacesWebService { class ClassinMain { } }
namespace Sentry.Tests.Protocol.Exceptions; public class SentryStackTraceTests { [Fact] public void Frames_Getter_NotNull() { var sut = new SentryStackTrace(); Assert.NotNull(sut.Frames); } [Fact] public void Frames_Setter_ReplacesList() { var sut = new SentryStackTrace(); var original = sut.Frames; var replacement = new List<SentryStackFrame>(); sut.Frames = replacement; Assert.NotSame(original, replacement); Assert.Same(replacement, sut.Frames); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DistCWebSite.Core.Entities { [Table("M_Status")] public class M_Status { public int ID { get; set; } public int Status { get; set; } public int? OrderNo { get; set; } [StringLength(50)] public string Description { get; set; } } }
using AsyncClasses; using C1.C1Excel; using C1.Win.C1FlexGrid; using Clients.Clipboard; using Clipboard.Modals; using Common; using Common.Exceptions; using Common.Extensions; using Common.LFPEventArgs; using Common.Log; using Common.Presentation; using Common.Presentation.Controls; using Common.Presentation.Events; using Common.Presentation.Modals; using Contracts.Callback; using Entity; using SessionSettings; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Description; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using ViewMedia; namespace Clipboard { /// <summary> /// Class for Clipboard display and manipulation in Movies. /// </summary> public partial class ClipboardControl : UserControl, ICanCreateTab, IAsyncServiceCallback { #region Private Fields private bool mAddDiscreteIds = false; private DataTable mAddingIdsTable = null; private AddMultipleAssets mAddMultipleAssets = null; private string mAlreadyInClipboard = String.Empty; private AsyncClipboardProxy mAsyncProxy = null; private bool mCancel = false; private bool mChangingTemplate = false; private ClientPresentation mClientPresentation = null; private ClipboardTemplatePreferences mClipboardPreferences = null; private Dictionary<int, string> mColumnNamesInOrder = new Dictionary<int, string>(); private List<Tuple<string, string, Color>> mConformingColors = null; private int mConformingStatusIndex = 0; private string mControlName = "Clipboard"; private string mCurrentChannel = String.Empty; private string mCurrentTemplate = String.Empty; private bool mCurrentTemplateIsShared = false; private DataTable mDataSource = null; private bool mDetached = false; private bool mDetaching = false; private string mDirSCC = String.Empty; private bool mDoingOverwrite = false; private string mFilterString = String.Empty; private List<int> mIdsToBeAdded = new List<int>(); private List<int> mIdsToBeDeleted = null; private bool mInSetup = false; private bool mIsDirty = false; private bool mImportingFile = false; private string mImportingFilesDontExistList = String.Empty; private int mInstance = 0; private LastDeleteOperation mLastOperation = LastDeleteOperation.None; private string mLastTemplateUsed = String.Empty; private bool mLoading = false; private bool mLoadingTemplates = false; private object mLock = new object(); private string mNotesText = String.Empty; private IDetachable mParent = null; private bool mParentClosing = false; private DetachableTabPage mParentTab = null; private ClipboardProxy mProxy = null; private bool mReattaching = false; private int mRowIndex = 1; private ScreenPreferences mScreenPreferences = null; private int mStartIndex = 0; private bool mStylesSet = false; private TableLoader mTableLoader = null; //private byte[] mTempData = null; private SystemSearchTitles[] mTitles = null; private bool mUndoing = false; private DataTable mUndoTable = null; private ViewMediaForm mViewMedia = null; #endregion #region Public Delegates /// <summary> /// Event handler for updates of user preferences (both for grid and for Clipboard appearance). /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void UpdatePreferencesEventHandler(object sender, UpdateEventArgs e); #endregion #region Public Events /// <summary> /// Event fired when the user clicks the Attach button. /// </summary> public event DockRequestEventHandler DockRequested; /// <summary> /// Event fired when screen preferences have been updated. /// </summary> public event UpdatePreferencesEventHandler UpdateScreenPreferences; #endregion #region Constructors /// <summary> /// Creates a new instance of ClipboardControl. /// </summary> public ClipboardControl() { SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); InitializeComponent(); Logging.ConnectionString = Settings.ConnectionString; //Logging.MinimumLogLevel = (Common.Data.LogLevel)Enum.Parse(typeof(Common.Data.LogLevel), // ConfigurationManager.AppSettings["ClipboardLogLevel"]); //Necessary to allow opening of Movie Info from the grid. MainGrid.DisableCellDoubleClick = true; } #endregion #region Public Properties /// <summary> /// Gets or sets the ClientPresentation object for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ClientPresentation ClientPresentation { get { if (mClientPresentation == null) mClientPresentation = new ClientPresentation(); return mClientPresentation; } set { mClientPresentation = value; } } /// <summary> /// Gets or sets the name of this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ControlName { get { return mControlName; } set { mControlName = value; } } /// <summary> /// Gets or sets the current template name. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string CurrentTemplate { get { return mCurrentTemplate; } set { mCurrentTemplate = value; } } /// <summary> /// Gets or sets a flag indicating whether the current template is shared. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CurrentTemplateIsShared { get { return mCurrentTemplateIsShared; } set { mCurrentTemplateIsShared = value; } } /// <summary> /// Gets or sets the grid datasource for the current instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataTable DataSource { get { return mDataSource; } set { if (value != null) { mDataSource = value; mDataSource.AcceptChanges(); RestoreDataInGrid(); } } } /// <summary> /// Gets or sets a flag indicating whether the current instance is detached. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Detached { get { return mDetached; } set { if (mDetached != value) { mDetached = value; Detach.Visible = true; Attach.Visible = false; if (mDetached) { Detach.Visible = false; Attach.Visible = true; } } } } /// <summary> /// Gets or sets a flag indicating whether the Channel Header IDs group is visible. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool GroupVisible { get { return channelHeaderIdsGroup.Visible; } set { channelHeaderIdsGroup.Visible = value; } } /// <summary> /// Gets or sets the current index of this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Instance { get { return mInstance; } set { mInstance = value; } } /// <summary> /// Gets or sets the list of available channels for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public List<string> ItemList { get { return channels.Items.Cast<string>().ToList<string>(); } set { channels.Items.Clear(); channels.Items.AddRange(value.ToArray()); } } /// <summary> /// Gets or sets the index of the current channel for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int ItemSelectedIndex { get { return channels.SelectedIndex; } set { channels.SelectedIndex = value; } } /// <summary> /// Gets or sets the current channel for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ItemText { get { return mCurrentChannel; } set { mCurrentChannel = value; channels.SelectedIndex = channels.Items.IndexOf(mCurrentChannel); channels.SelectedText = mCurrentChannel; } } /// <summary> /// Gets or sets the name of the last imported document for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string LastImportedDocName { get { return lastDocumentLabel.LabelText; } set { lastDocumentLabel.LabelText = value; } } /// <summary> /// Gets or sets the list of available personal templates for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public List<string> MyTemplatesList { get { return myTemplates.Items.Cast<string>().ToList<string>(); } set { myTemplates.Items.Clear(); myTemplates.Items.AddRange(value.ToArray()); if (!mCurrentTemplateIsShared) { myTemplates.SelectedIndex = myTemplates.Items.IndexOf(mCurrentTemplate); myTemplates.SelectedText = mCurrentTemplate; } } } /// <summary> /// Gets or sets the index of the personal template selected for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int MyTemplatesSelectedIndex { get { return myTemplates.SelectedIndex; } set { myTemplates.SelectedIndex = value; } } /// <summary> /// Gets or sets the IDetachable form this instance belongs to. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new IDetachable Parent { get { return mParent; } set { mParent = value; } } /// <summary> /// Gets or sets the DetachableTabPage hosting this control. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DetachableTabPage ParentTab { get { return mParentTab; } set { mParentTab = value; } } /// <summary> /// Gets or sets the list of shared templates available for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public List<SharedTemplate> SharedTemplateList { get { return sharedTemplates.Items.Cast<SharedTemplate>().ToList<SharedTemplate>(); } set { sharedTemplates.DataSource = null; sharedTemplates.Items.Clear(); sharedTemplates.DataSource = value; if (mCurrentTemplateIsShared) sharedTemplates.SelectedIndex = sharedTemplates.Items.IndexOf(new SharedTemplate(Settings.User.Department, mCurrentTemplate)); } } /// <summary> /// Gets or sets the index of the shared template selected for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int SharedTemplatesSelectedIndex { get { return sharedTemplates.SelectedIndex; } set { sharedTemplates.SelectedIndex = value; } } /// <summary> /// Shows or hides the Attach and Detach buttons for this instance. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool ShowAttachDetachButtons { get { return Attach.Visible; } set { Attach.Visible = value; if (Attach.Visible) Detach.Visible = false; else Detach.Visible = true; } } #endregion #region Public Methods /// <summary> /// Adds the provided ID(s) to the grid. /// </summary> /// <param name="id">The ID to add, or a comma-delimited list of IDs.</param> public void AddId(string id) { string[] idVals = null; if (id.Contains(",")) idVals = id.Split(','); else { idVals = new string[1]; idVals[0] = id; } mIdsToBeAdded.Clear(); mAlreadyInClipboard = ""; foreach (string s in idVals) { string val = s; //Make sure we have a valid string. val = val.Trim(); if (String.IsNullOrEmpty(val)) continue; int idValue; if (Int32.TryParse(val, out idValue)) { if (mDataSource != null) { DataRow[] rows = mDataSource.Select("ID = " + val); if (rows.Length > 0) mAlreadyInClipboard += val + ","; else mIdsToBeAdded.Add(idValue); } else mIdsToBeAdded.Add(idValue); } } if (mAlreadyInClipboard.EndsWith(",")) mAlreadyInClipboard = mAlreadyInClipboard.Remove(mAlreadyInClipboard.LastIndexOf(",")); if (CheckIdsPresent()) AddIds(); } /// <summary> /// Returns a flag indicating whether the Clipboard is loading. /// </summary> /// <returns>True if the Clipboard is loading; otherwise false.</returns> public bool CheckLoad() { return mLoading; } public void ClearData() { mReattaching = true; DoClear(); mLoading = false; mIsDirty = false; mTableLoader = null; if (mUndoTable != null) mUndoTable.Dispose(); mUndoTable = null; lastDocumentLabel.LabelText = ""; mCurrentTemplate = ""; mCurrentTemplateIsShared = false; mCurrentChannel = ""; myTemplates.SelectedIndex = 0; sharedTemplates.SelectedIndex = 0; SetControlAvailability(false); mReattaching = false; } /// <summary> /// Closes the control and saves any changes to the grid column order and template. /// </summary> public void Close() { if (mTableLoader != null) mTableLoader.Dispose(); mTableLoader = null; if (mUndoTable != null) mUndoTable.Dispose(); mUndoTable = null; if (mAddingIdsTable != null) mAddingIdsTable.Dispose(); mAddingIdsTable = null; if (mViewMedia != null) mViewMedia.Dispose(); mViewMedia = null; //Exit without trying to process empty grids. if (MainGrid.Cols.Count == 1) return; if (mIsDirty) { Console.Beep(); if (MessageBox.Show("The column order has changed. Do you want to save the new layout?", "Clipboard", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { using (ClipboardTemplatePreferencesManager manager = new ClipboardTemplatePreferencesManager(Settings.ConnectionString, Settings.User)) { manager.IsDirty = true; UsersClipboard data = new UsersClipboard() { Username = Settings.UserName, Shared = mCurrentTemplateIsShared ? 1 : 0, Department = Settings.User.Department }; string currentTemplate = myTemplates.SelectedItem.ToString(); if (mCurrentTemplateIsShared) currentTemplate = sharedTemplates.SelectedItem.ToString(); data.Template_Name = currentTemplate; data = manager.LoadDataColsForSave(MainGrid, data); if (manager.SaveTemplate(Settings.UserName, currentTemplate, Settings.User.Department, mCurrentTemplateIsShared, manager.ChangedFromPersonal, data, true) > -1) MessageBox.Show("Template saved."); } } } if (!String.IsNullOrEmpty(mLastTemplateUsed)) ReleaseLock(mLastTemplateUsed); //Save the column widths (if applicable) for the grid. OpenProxy(); try { bool result = false; if (!mCurrentTemplateIsShared) { List<int> widths = new List<int>(); for (int i = 1; i < MainGrid.Cols.Count; i++) { if (!MainGrid.Cols[i].Name.Equals("viewButton")) widths.Add(MainGrid.Cols[i].Width); } result = mProxy.SaveColumnWidths(Settings.UserName, mCurrentTemplate, widths); } } catch (Exception e) { Logging.Log(e, "Clipboard", "Close"); } finally { CloseProxy(); Cursor = Cursors.Default; } if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; CloseAsyncProxy(); } /// <summary> /// Commits the changes from the last operation before the next Undo request is made or when the form is closing. /// </summary> public void CommitChanges() { if (mLastOperation == LastDeleteOperation.None) return; OpenProxy(); bool success = true; try { switch (mLastOperation) { case LastDeleteOperation.ClearGrid: OpenProxy(); try { success = mProxy.ClearClipboard(Settings.UserName, mInstance); if (!success) MessageBox.Show("Unable to clear Clipboard.", "Clipboard"); else { mIdsToBeAdded.Clear(); if (!mDoingOverwrite) SaveImportedDocName(""); } } catch (Exception e) { Logging.Log(new MoviesException("Exception clearing grid for Clipboard " + mInstance.ToString() + ".", e)); } finally { CloseProxy(); } break; //case LastDeleteOperation.ClearText: // break; case LastDeleteOperation.DeleteRows: success = true; foreach (int id in mIdsToBeDeleted) { success &= mProxy.DeleteRecordFromClipboard(Settings.UserName, id, mInstance); if (!success) { MessageBox.Show("Failed to delete ID " + id + ". Aborting operation.", "Clipboard"); break; } } break; } } catch (Exception e) { Logging.Log(e, "Clipboard", "CommitChanges"); } finally { CloseProxy(); mLastOperation = LastDeleteOperation.None; } } /// <summary> /// Handles completion of the asynchronous data load. /// </summary> /// <param name="data">The data to be loaded.</param> /// <param name="instance">The current Clipboard instance.</param> /// <param name="e">Any exceptions that occurred during processing.</param> /// <param name="cancelled">Flag indicating whether the load has been cancelled.</param> public void Completed(MemoryStream data, int instance, Exception e, bool cancelled, object userState = null) { try { Application.DoEvents(); mLoading = false; if (mParentClosing) return; if (cancelled) { MessageBox.Show("Load cancelled.", "Clipboard", MessageBoxButtons.OK); mCancel = true; SetControlAvailability(false); if (!MainGrid.IsDisposed) { MainGrid.BeginUpdate(); LoadColumnNames(mCurrentTemplate); MainGrid.EndUpdate(); } return; } Application.DoEvents(); mCancel = false; if (e != null) { SetControlAvailability(false); string exceptions = GetExceptions(e); ClientPresentation.ShowError(exceptions); return; } Application.DoEvents(); if (data != null) { using (DataTable table = new DataTable()) { data.Position = 0; table.ReadXml(data); if (mDataSource == null) mDataSource = table; else mDataSource.Merge(table); } } if (mAddDiscreteIds) { if (mAddingIdsTable != null) mDataSource.Merge(mAddingIdsTable); mDataSource.RemoveDuplicateRows("ID"); } Application.DoEvents(); mDataSource.AcceptChanges(); if (mAddingIdsTable != null) mAddingIdsTable.Dispose(); if (MainGrid.InvokeRequired) MainGrid.BeginInvoke(new Action(() => { MainGrid.DataSource = null; MainGrid.Rows.Count = 1; MainGrid.DataSource = mDataSource; Application.DoEvents(); })); else { MainGrid.DataSource = null; MainGrid.Rows.Count = 1; MainGrid.DataSource = mDataSource; Application.DoEvents(); } //Exit if there is no data to load. if (mDataSource.HasRows()) { SetUpGrid(); NameTab(); //Tell the DataTable to hold on to these changes. mDataSource.AcceptChanges(); } else NameTab(); if (InvokeRequired) { BeginInvoke(new Action(() => { notifyIcon.BalloonTipText = "Data for " + mCurrentTemplate + " has finished loading."; notifyIcon.BalloonTipTitle = "Clipboard Load Complete"; SetControlAvailability(false); })); } else { notifyIcon.BalloonTipText = "Data for " + mCurrentTemplate + " has finished loading."; notifyIcon.BalloonTipTitle = "Clipboard Load Complete"; SetControlAvailability(false); } if (mImportingFile) { OpenProxy(); try { string docName = mProxy.LoadLastDocName(); if (lastDocumentLabel.InvokeRequired) lastDocumentLabel.BeginInvoke(new Action(() => { if (!String.IsNullOrEmpty(docName)) lastDocumentLabel.LabelText = docName; toolTips.SetToolTip(lastDocumentLabel, lastDocumentLabel.LabelText); })); else { if (!String.IsNullOrEmpty(docName)) lastDocumentLabel.LabelText = docName; toolTips.SetToolTip(lastDocumentLabel, lastDocumentLabel.LabelText); } } catch (Exception ex) { Logging.Log(ex, "Clipboard", "Completed (importing file)"); } finally { CloseProxy(); } mImportingFile = false; if (!String.IsNullOrEmpty(mImportingFilesDontExistList)) { if (InvokeRequired) { BeginInvoke(new Action(() => { ClientPresentation.ShowNotification("The following IDs don't exist in Movies:\n\n" + mImportingFilesDontExistList.Remove(mImportingFilesDontExistList.LastIndexOf(",")), (Form)mParent); })); } else { ClientPresentation.ShowNotification("The following IDs don't exist in Movies:\n\n" + mImportingFilesDontExistList.Remove(mImportingFilesDontExistList.LastIndexOf(",")), (Form)mParent); } } } if (!String.IsNullOrEmpty(mAlreadyInClipboard.Trim()) && mAlreadyInClipboard.Contains(",")) { if (InvokeRequired) { BeginInvoke(new Action(() => { ClientPresentation.ShowNotification("The following IDs are already on the Clipboard:\n\n" + mAlreadyInClipboard.Remove(mAlreadyInClipboard.LastIndexOf(",")), (Form)mParent); })); } else { ClientPresentation.ShowNotification("The following IDs are already on the Clipboard:\n\n" + mAlreadyInClipboard.Remove(mAlreadyInClipboard.LastIndexOf(",")), (Form)mParent); } } if (InvokeRequired) BeginInvoke(new Action(() => { if (notifyIcon != null) { notifyIcon.ShowBalloonTip(1000); notifyIcon.Visible = false; } })); else { if (notifyIcon != null) { notifyIcon.ShowBalloonTip(1000); notifyIcon.Visible = false; } } } catch (Exception ex1) { ClientPresentation.ShowError(ex1.Message + "\n" + ex1.StackTrace); Logging.Log(ex1, "Clipboard", "Completed"); } finally { Cursor = Cursors.Default; if (InvokeRequired) BeginInvoke(new Action(() => { if (mParentTab != null) mParentTab.RestorePosition(); })); else { if (mParentTab != null) mParentTab.RestorePosition(); } mDoingOverwrite = false; if (!mCancel) //Keep the grid from refreshing because we want to preserve the column headers. { if (!MainGrid.IsDisposed && MainGrid.Rows.Count > 1) { LoadNotes(1); //mainGrid.SelectRow(1); } } if (!MainGrid.IsDisposed) MainGrid.AllowResizing = AllowResizingEnum.Both; // testing if this removing these makes stuff more responsive - Ryan //mainGrid.AutoSizeCols(); //mainGrid.AutoSizeRows(); //CloseAsyncProxy(); mCancel = false; mAddingIdsTable = null; mAddDiscreteIds = false; mAlreadyInClipboard = ""; mImportingFilesDontExistList = ""; } } /// <summary> /// Copies the selected rows to the Windows Clipboard. /// </summary> public void CopyToWindowsClipboard() { System.Windows.Forms.Clipboard.Clear(); StringBuilder textToCopy = new StringBuilder(); if (MainGrid.Rows.Selected.Count == 0) textToCopy.AppendLine(idLabel.LabelText); else { for (int i = 0; i < MainGrid.Rows.Selected.Count; i++) { string text = MainGrid[MainGrid.Rows.Selected[i].Index, "ID"].ToString(); textToCopy.AppendLine(text); } } System.Windows.Forms.Clipboard.SetText(textToCopy.ToString()); } /// <summary> /// Attaches a detached tab to the main form. /// </summary> public void DoAttach() { if (DockRequested != null) DockRequested(this, new AttachEventArgs(mInstance)); Attach.Visible = false; Detach.Visible = true; } /// <summary> /// Clears the grid of all data. /// </summary> public void DoClear() { if (mDetaching || mDetached || mChangingTemplate) return; if (mReattaching || (!mLoading && (MessageBox.Show("Are you sure you want to clear the Clipboard?", "Clipboard", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)) || mLoading) { //Perform the last delete operation before doing this one. CommitChanges(); notes.Text = ""; if (mDataSource != null) { if (!mDoingOverwrite) mRowIndex = mDataSource.Rows.Count; else mRowIndex = 1; //Remove the data source. We will hold on to the original datatable for undo purposes. mUndoTable = mDataSource.Copy(); mDataSource.Clear(); } if (MainGrid.DataSource != null) MainGrid.DataSource = null; mLastOperation = LastDeleteOperation.ClearGrid; CommitChanges(); mLastOperation = LastDeleteOperation.ClearGrid; //Remove formatting from the grid. MainGrid.Clear(ClearFlags.All); mStylesSet = false; MainGrid.Rows.Count = 1; MainGrid.Cols.Count = 1; MainGrid.Cols.Frozen = 0; //Clear the tooltips. toolTips.SetToolTip(titleLabel, ""); toolTips.SetToolTip(channels, ""); ClearNotes(); LoadColumnNames(mCurrentTemplate); MainGrid.Redraw = true; } } /// <summary> /// Detaches a tab from the main form. /// </summary> public void DoDetach() { mDetached = false; mDetaching = true; mParentTab.TabParent.Detach(mParentTab.Text, new DetachedForm()); mDetached = true; mDetaching = false; Detach.Visible = false; Attach.Visible = true; } /// <summary> /// Exports data to a file. /// </summary> /// <param name="fileType">The file type to create (.txt, .xls, or .xlsx).</param> public void Export(string fileType) { string exportFileName = String.Empty; try { if (fileType.Equals("Excel")) { if (ImportExport.Export(MainGrid, fileType, ref exportFileName, "Excel", "", false, false, true)) { PostProcessExcelFile(exportFileName); MessageBox.Show("Export complete."); } } else { if (ImportExport.Export(MainGrid, fileType, ref exportFileName)) { PostProcessTextFile(exportFileName); MessageBox.Show("Export complete."); } } } catch (Exception e) { Logging.Log(e, "Clipboard", "Export"); MessageBox.Show("Exception exporting " + exportDialog.FileName + ":\n" + e.Message); } } /// <summary> /// Gets the value of the AssetId textbox for consumption outside the current control. /// </summary> /// <returns></returns> public string GetAssetIds() { return assetId.Text; } /// <summary> /// Imports data from an Excel file. /// </summary> public void ImportExcel() { DialogResult dr = QueryAddOverwrite(); if (dr != DialogResult.OK && dr != DialogResult.Cancel) return; if (dr == DialogResult.OK) Import("Excel", true); else Import("Excel", false); } /// <summary> /// Imports data from a text file. /// </summary> public void ImportText() { DialogResult dr = QueryAddOverwrite(); if (dr != DialogResult.OK && dr != DialogResult.Cancel) return; if (dr == DialogResult.OK) Import("Text", true); else Import("Text", false); } /// <summary> /// Reverts the last undoable operation. /// </summary> public void PerformUndo() { mUndoing = true; switch (mLastOperation) { case LastDeleteOperation.ClearText: notes.Text = mNotesText; mNotesText = String.Empty; break; case LastDeleteOperation.ClearGrid: mRowIndex = 1; Cursor = Cursors.AppStarting; try { MainGrid.DataSource = null; mDataSource.Clear(); MainGrid.Rows.Count = 1; MainGrid.DataSource = mDataSource = mUndoTable.Copy(); SetUpGrid(); NameTab(); if (mDataSource.HasRows()) { foreach (DataRow dr in mDataSource.Rows) { mIdsToBeAdded.Add(Convert.ToInt32(dr["ID"])); } AddIdsToStaging(); } } finally { Cursor = Cursors.Default; } break; case LastDeleteOperation.DeleteRows: RestoreRows(); break; } //Reset the last operation so we don't end up repeating the same restore. if (mUndoTable != null) mUndoTable.Dispose(); mUndoing = false; mLastOperation = LastDeleteOperation.None; } /// <summary> /// Reloads the grid asynchronously. /// </summary> public async void Reload() { if (mLoading) return; try { Cursor = Cursors.AppStarting; MainGrid.BeginUpdate(); //mainGrid.AutoResize = false; MainGrid.Enabled = false; MainGrid.AllowEditing = true; MainGrid.Cols.Frozen = 0; MainGrid.Clear(ClearFlags.All); if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; if (MainGrid.Cols.Contains("viewButton")) MainGrid.Cols.Remove("viewButton"); mRowIndex = 1; // Fix the issue where a user is removing an ID and then refreshing to keep the ID from reappearing // which should only happen if the user clicked the Undo button. if (mLastOperation == LastDeleteOperation.DeleteRows && mUndoing == false) { foreach (int id in mIdsToBeDeleted) { if (mIdsToBeAdded.Contains(id)) { mIdsToBeAdded.Remove(id); } } } CommitChanges(); mLoading = true; ClearNotes(); CreateTableLoader(mCurrentTemplate); OpenAsyncProxy(); SetControlAvailability(true); mCancel = false; SendDataToLoad(); await mAsyncProxy.LoadClipboardAsync(mTableLoader); } catch (FaultException fe) { if (!fe.Message.Equals("A task was canceled.")) { ClientPresentation.ShowError(fe.Message + "\n" + fe.StackTrace); Logging.Log(new AsyncDataLoadException("Async load faulted.", fe)); mLoading = false; } //Reset if we are not cancelling. This preserves the column headers if the user has requested a cancel. if (!mCancel) SetControlAvailability(false); CloseAsyncProxy(); } catch (Exception e) { //Reset if we are not cancelling. This preserves the column headers if the user has requested a cancel. if (!mCancel) SetControlAvailability(false); //Ignore the CommunicationException, since it usually results from an "unexpected" response from the //server after the load is complete. if (!(e is CommunicationException) && !(e is ProtocolException)) ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e.GetType().ToString() + "\n" + e.Message + "\n" + e.StackTrace, "Clipboard", "Reload"); mLoading = false; mCancel = true; CloseAsyncProxy(); } } /// <summary> /// Refreshes the template lists. /// </summary> /// <param name="templateName">The current template.</param> /// <param name="shared">Flag indicating whether the current template is shared or personal.</param> public void ReloadTemplates(string templateName, bool shared) { OpenProxy(); try { LoadTemplates(templateName, shared); } finally { CloseProxy(); } } /// <summary> /// Reports the progress of an asynchronous data load. /// </summary> /// <param name="total">The total number of records to load.</param> /// <param name="current">The current number of records loaded.</param> /// <param name="notFound">The name(s) of (an) asset(s) not found in the database.</param> /// <param name="instance">The current Clipboard instance.</param> /// <param name="data">The data to load in the grid.</param> /// <param name="userState">Additional information that may be passed in.</param> public void ReportProgress(int total, int current, string notFound, int instance, MemoryStream data, bool cancelled, object userState) { if (total == 0) return; try { if (userState == null) { if (data != null) { using (DataTable table = new DataTable("Clipboard")) { using (XmlTextReader reader = new XmlTextReader(data)) { //Make sure we are at the beginning of the stream. data.Position = 0; table.ReadXml(data); } if (mDataSource == null) { mDataSource = table.Clone(); mDataSource.TableName = "Clipboard"; } mDataSource.Merge(table); } } } //else //{ // if (Convert.ToBoolean(userState) == false) // { // data.Position = 0; // if (mTempData == null) // mTempData = data.GetBuffer(); // else // { // byte[] bytes = new byte[mTempData.Length]; // mTempData.CopyTo(bytes, 0); // byte[] buffer = data.GetBuffer(); // mTempData = new byte[bytes.Length + buffer.Length]; // bytes.CopyTo(mTempData, 0); // buffer.CopyTo(mTempData, bytes.Length); // } // } // else // { // data.Position = 0; // int dataLength = 0; // if (mTempData == null) // { // mTempData = new byte[data.Length]; // dataLength = mTempData.Length; // } // else // dataLength = mTempData.Length + (int)data.Length; // using (MemoryStream ms = new MemoryStream(dataLength)) // { // byte[] bytes = new byte[mTempData.Length]; // mTempData.CopyTo(bytes, 0); // byte[] buffer = data.GetBuffer(); // mTempData = new byte[bytes.Length + buffer.Length]; // bytes.CopyTo(mTempData, 0); // buffer.CopyTo(mTempData, bytes.Length); // ms.Write(mTempData, 0, mTempData.Length); // using (DataTable table = new DataTable("Clipboard")) // { // using (XmlTextReader reader = new XmlTextReader(ms)) // { // //Make sure we are at the beginning of the stream. // ms.Position = 0; // table.ReadXml(ms); // } // if (mDataSource == null) // { // mDataSource = table.Clone(); // mDataSource.TableName = "Clipboard"; // } // mDataSource.Merge(table); // } // } // mTempData = null; // } //} if (mDataSource != null) mDataSource.AcceptChanges(); UpdateProgressBar(total, current); if (!notifyIcon.Visible) notifyIcon.Visible = true; notifyIcon.BalloonTipTitle = "Clipboard #" + mInstance.ToString() + " Load Status"; notifyIcon.BalloonTipText = String.Format("{0} of {1} loaded.", current.ToString(), total.ToString()); if (!String.IsNullOrEmpty(notFound)) { if (!notFound.StartsWith("[")) mImportingFilesDontExistList += notFound + ", "; else mAlreadyInClipboard = notFound.Replace("[", "").Replace("]", ""); } } catch (Exception e) { ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e, "Clipboard", "ReportProgress current=" + current + ", total=" + total); SetControlAvailability(false); } } /// <summary> /// Refreshes the grid when the datasource has been copied to a new instance. /// </summary> public void RestoreDataInGrid() { MainGrid.DataSource = null; MainGrid.Rows.Count = 1; MainGrid.DataSource = mDataSource; SetUpGrid(); mDataSource.AcceptChanges(); } /// <summary> /// Saves the contents of the Notes textbox to the database. /// </summary> public void SaveNotes() { if (String.IsNullOrEmpty(idLabel.LabelText)) { MessageBox.Show("You must select an asset or enter an asset ID in the 'Add Asset' textbox.", "Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } OpenProxy(); try { if (!mProxy.SaveNotes(Settings.UserName, Convert.ToInt32(idLabel.LabelText), mInstance, notes.Text)) MessageBox.Show("Failed to save notes for ID " + idLabel.LabelText + ".", "Clipboard"); else MessageBox.Show("Notes saved."); } finally { CloseProxy(); } } /// <summary> /// Submits a cancellation request to the asynchronous process. /// </summary> public void SendCancel(bool fromParent) { Logging.Log("SendCancel", "Clipboard", "ClipboardControl.SendCancel"); mParentClosing = fromParent; mCancel = true; if (mAsyncProxy != null && mAsyncProxy.State != CommunicationState.Faulted) { Thread thread = new Thread(new ParameterizedThreadStart(SendCancelRequest)); thread.Start(mAsyncProxy); } else MessageBox.Show("Load cancelled.", "Clipboard", MessageBoxButtons.OK); } /// <summary> /// Loads the grid with data and formats its cells. /// </summary> public void SetUpGrid(bool detached = false) { MainGrid.Visible = false; MainGrid.BeginUpdate(); MainGrid.Enabled = false; //mainGrid.AutoResize = false; MainGrid.AllowEditing = true; MainGrid.Cols.Frozen = 0; try { //Add styles to the grid. if (!mStylesSet) { ClientPresentation.SetCellStyles(MainGrid); mStylesSet = true; } if (MainGrid.Cols.Count < 1) return; if (!detached) { if (MainGrid.DataSource == null) MainGrid.DataSource = mDataSource; } Application.DoEvents(); FormatGrid(); Application.DoEvents(); //Marshal the grid here if necessary. if (MainGrid.InvokeRequired) MainGrid.BeginInvoke(new Action(() => { MainGrid.Visible = true; MainGrid.AllowEditing = false; //mainGrid.AutoResize = true; MainGrid.Redraw = true; MainGrid.Enabled = true; MainGrid.EndUpdate(); })); else { MainGrid.Visible = true; MainGrid.AllowEditing = false; //mainGrid.AutoResize = true; MainGrid.Redraw = true; MainGrid.Enabled = true; MainGrid.EndUpdate(); } mColumnNamesInOrder.Clear(); //Load the default order of the columns. foreach (Column column in MainGrid.Cols) mColumnNamesInOrder.Add(column.Index, column.Name); } catch (Exception e) { ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e, "Clipboard", "SetUpGrid"); } finally { MainGrid.Visible = true; } } #endregion #region Private Methods /// <summary> /// Handles the AddAsset.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddAsset_Click(object sender, EventArgs e) { mAddDiscreteIds = (assetId.Text.Trim().Length > 0); AddId(assetId.Text); } /// <summary> /// Adds asset records to the grid asynchronously. /// </summary> private async void AddIds() { AddIdsToStaging(); if (!mAddDiscreteIds) { if (MainGrid.DataSource != null) MainGrid.DataSource = null; MainGrid.Clear(ClearFlags.All); MainGrid.Rows.Count = 1; if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; } else { if (mDataSource != null) { mRowIndex = mDataSource.Rows.Count; mAddingIdsTable = mDataSource.Copy(); } if (mRowIndex < 1) mRowIndex = 1; } await LoadData(); if (assetId.Text.Length > 0) { assetId.Text = ""; this.assetId.Focus(); } } /// <summary> /// Adds the loaded IDs to the database. /// </summary> private void AddIdsToStaging() { OpenProxy(); try { //Logging.Log("Adding IDs to Staging.", "Clipboard", "AddIdsToStaging"); for (int i = 0; i < mIdsToBeAdded.Count; i++) { //Check to see if this ID exists on the Movie table. if (!mProxy.CheckMovieExists(mIdsToBeAdded[i])) { if (mImportingFile) mImportingFilesDontExistList += mIdsToBeAdded[i] + "\n"; else MessageBox.Show("The ID " + mIdsToBeAdded[i] + " doesn't exist.", "Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //If it exists, add it to the Staging table. mProxy.AddToStaging(mIdsToBeAdded[i], mInstance); } } catch (Exception e) { Logging.Log(e, "Clipboard", "AddIdsToStaging"); } finally { CloseProxy(); } } /// <summary> /// Loads the result of the AddMultipleAssets operation into the assetId textbox. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddMultipleAssets_ShowModal(object sender, ModalEventArgs e) { if (e.DialogResult == DialogResult.OK) assetId.Text = e.ResultText.Replace("\r\n", ",").Replace("\n", ","); } /// <summary> /// Shows the AddMultipleAssets modal dialog. /// </summary> private void AddMultipleIds() { if (mAddMultipleAssets == null || mAddMultipleAssets.IsDisposed) { mAddMultipleAssets = new AddMultipleAssets(mParent.Parameters, (SkinnableFormBase)mParent); mAddMultipleAssets.ShowModal += AddMultipleAssets_ShowModal; } mAddMultipleAssets.Show(); } /// <summary> /// Handles the AddMultiples.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddMultiples_Click(object sender, EventArgs e) { AddMultipleIds(); } /// <summary> /// Handles the AssetId.KeyUp event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AssetId_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return) { mAddDiscreteIds = (assetId.Text.Trim().Length > 0); AddId(assetId.Text); } else e.Handled = true; } /// <summary> /// Handles the AssetId.TextChanged event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AssetId_TextChanged(object sender, EventArgs e) { mAddDiscreteIds = (assetId.Text.Trim().Length > 0); } /// <summary> /// Handles requests to reattach the tab to the form. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Attach_Click(object sender, EventArgs e) { DoAttach(); } /// <summary> /// Handles the Cancel.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CancelLoad_Click(object sender, EventArgs e) { SendCancel(false); } /// <summary> /// Changes the tooltip displayed over the Channels combobox. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Channels_SelectedIndexChanged(object sender, EventArgs e) { toolTips.SetToolTip(channels, channels.SelectedItem.ToString()); mCurrentChannel = channels.SelectedItem.ToString(); } /// <summary> /// Checks if there are any valid IDs present to be added to the Clipboard. /// </summary> /// <returns>True if there are valid IDs; otherwise false.</returns> private bool CheckIdsPresent() { if (mAlreadyInClipboard.Trim().Length > 0) { Console.Beep(); MessageBox.Show("The following IDs are already in the Clipboard:\n" + mAlreadyInClipboard, "Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Information); } if (mIdsToBeAdded.Count == 0) { Console.Beep(); MessageBox.Show("There are no valid IDs to add.", "Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Information); this.assetId.Focus(); return false; } return true; } /// <summary> /// Handles the ClearList.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClearList_Click(object sender, EventArgs e) { DoClear(); } /// <summary> /// Clears data from the Notes group. /// </summary> private void ClearNotes() { notes.Clear(); idLabel.LabelText = ""; titleLabel.LabelText = ""; toolTips.SetToolTip(titleLabel, ""); } /// <summary> /// Handles commands sent via the keyboard. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClipboardControl_KeyUp(object sender, KeyEventArgs e) { if ((e.Modifiers & Keys.Control) != 0) //Ctrl + key { if (e.KeyCode == Keys.Z) PerformUndo(); else e.Handled = true; } else if ((e.Modifiers & Keys.Alt) != 0) { if ((e.Modifiers & Keys.Shift) != 0) //Alt + Shift + key { switch (e.KeyCode) { case Keys.T: Export("Text"); break; case Keys.X: Export("Excel"); break; default: e.Handled = true; break; } } else { switch (e.KeyCode) //Alt + key { case Keys.A: AddId(GetAssetIds()); break; case Keys.C: DoClear(); break; case Keys.D: DoDetach(); break; case Keys.E: Reload(); break; case Keys.I: CopyToWindowsClipboard(); break; case Keys.L: case Keys.Escape: SendCancel(true); break; case Keys.S: SaveNotes(); break; case Keys.T: ImportText(); break; case Keys.U: PerformUndo(); break; case Keys.X: ImportExcel(); break; default: e.Handled = true; break; } } } else { switch (e.KeyCode) { case Keys.F5: Reload(); break; case Keys.Return: if (assetId.Focused) AddId(GetAssetIds()); else e.Handled = true; break; default: e.Handled = true; break; } } } /// <summary> /// Handles the Control.Load event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClipboardControl_Load(object sender, EventArgs e) { mLoading = true; LoadControl(); } /// <summary> /// Saves the results of the ClipboardPreferences operation. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClipboardPreferences_ShowModal(object sender, ModalEventArgs e) { if (e.DialogResult == DialogResult.OK) { mLoadingTemplates = true; string[] vals = e.ResultText.Split('|'); bool shared = false; string name = ""; if (vals.Length > 1) { name = vals[0]; shared = Convert.ToBoolean(vals[1]); } SaveGridPreferences(name, shared); } } /// <summary> /// Opens the ClipboardPreferences modal dialog. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClipboardPreferences_Click(object sender, EventArgs e) { SetClipboardPreferences(); } private void CloseProxy() { if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted) { Thread.Sleep(30); mProxy.Close(); } mProxy = null; } /// <summary> /// Closes the asynchronous proxy. /// </summary> private void CloseAsyncProxy() { if (mAsyncProxy != null) { try { //if (mAsyncProxy.InnerChannel.State == CommunicationState.Opened) //{ // if (System.Diagnostics.Debugger.IsAttached) // Logging.Log("Waiting to close inner channel.", "Clipboard", "CloseAsyncProxy"); Thread.Sleep(1000); // if (System.Diagnostics.Debugger.IsAttached) // Logging.Log("Closing inner channel.", "Clipboard", "CloseAsyncProxy"); // mAsyncProxy.InnerChannel.Close(new TimeSpan(0, 0, 30)); //} if (mAsyncProxy.State == CommunicationState.Opened) { if (System.Diagnostics.Debugger.IsAttached) Logging.Log("Attempting to close asynchronous proxy.", "Clipboard", "CloseAsyncProxy"); mAsyncProxy.Close(); } } catch (TimeoutException) { mAsyncProxy.Abort(); if (System.Diagnostics.Debugger.IsAttached) Logging.Log("Close() operation has timed out.", "Clipboard", "CloseAsyncProxy"); } catch (ObjectDisposedException) { Logging.Log("Asynchronous proxy has been disposed.", "Clipboard", "CloseAsyncProxy"); } catch (ProtocolException) { mAsyncProxy.Abort(); if (System.Diagnostics.Debugger.IsAttached) Logging.Log("Unexpected message sent through channel.", "Clipboard", "CloseAsyncProxy"); } catch (Exception e) { mAsyncProxy.Abort(); Logging.Log(e, "Clipboard", "CloseAsyncProxy"); } } } /// <summary> /// Handles the CopyIds.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CopyIds_Click(object sender, EventArgs e) { CopyToWindowsClipboard(); } /// <summary> /// Creates a TableLoader for this instance, or sets the template on the existing instance. /// </summary> /// <param name="template">The template to set.</param> private void CreateTableLoader(string template) { if (mTableLoader == null) mTableLoader = new TableLoader(Settings.ConnectionString, Settings.UserName, template, mInstance, Settings.User.Department); else mTableLoader.Template = template; mTableLoader.SharedTemplate = mCurrentTemplateIsShared; mTableLoader.AddDiscreteIdsOnly = mAddDiscreteIds; mTableLoader.KeyNames.Clear(); if (mConformingColors != null) { foreach (Tuple<string, string, Color> tuple in mConformingColors) { mTableLoader.KeyNames.Add(tuple.Item2); } } if (mCurrentTemplateIsShared) sharedTemplates.Text = template; else myTemplates.Text = template; Logging.Log("TableLoader template=" + mTableLoader.Template, "Clipboard", "ClipboardControl.CreateTableLoader"); } /// <summary> /// Handles the Detach.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Detach_Click(object sender, EventArgs e) { DoDetach(); } /// <summary> /// Handles the ExportExcelFile.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ExportExcelFile_Click(object sender, EventArgs e) { Export("Excel"); } /// <summary> /// Handles the ExportTextFile.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ExportTextFile_Click(object sender, EventArgs e) { Export("Text"); } /// <summary> /// Applies styles and formats to the grid. /// </summary> private void FormatGrid() { //The top row is fixed and contains the column headers. mRowIndex = 1; //Add button column if needed. if (!MainGrid.Cols.Contains("viewButton")) { Column col = MainGrid.Cols.Add(); col.Name = "viewButton"; } //The way the asynchronous code is written, this method may get called a second time, rearranging //the columns in the grid. It causes an error to get thrown, so we are just going to log the error. //It does not affect the result of the asynchronous load. try { foreach (Column column in MainGrid.Cols) { SetDefaultColumnWidth(column); SetColumnStyle(column); } } catch (InvalidOperationException) { Logging.Log("Column collection modified from another thread.", "Clipboard", "FormatGrid"); } //Only set column widths if the template is a user template. if (!mCurrentTemplateIsShared) SetUserColumnWidths(); if (mDataSource != null) { try { for (int i = mRowIndex; i <= mDataSource.Rows.Count; i++) { if (i >= MainGrid.Rows.Count) MainGrid.Rows.Add(); foreach (Column col in MainGrid.Cols) { SetCellStyle(i, col); } } } catch (Exception ex1) { MessageBox.Show(ex1.Message + "\n" + ex1.StackTrace); } } MainGrid.Cols.Frozen = 1; if (MainGrid.Cols.Contains("ID")) MainGrid.Cols["ID"].AllowFiltering = AllowFiltering.None; //Move the View Media column to the end of the grid if it is present in the column list. if (MainGrid.Cols.Contains("viewButton")) { if (MainGrid.Cols["viewButton"].Index != MainGrid.Cols.Count - 1) MainGrid.Cols["viewButton"].Move(MainGrid.Cols.Count - 1); MainGrid.Cols["viewButton"].AllowFiltering = AllowFiltering.None; } } /// <summary> /// Gets a string representation of exceptions thrown during an operation. /// </summary> /// <param name="exception">The base exception.</param> /// <returns>A string representation of the exception information, including any inner exceptions.</returns> private string GetExceptions(Exception exception) { StringBuilder sb = new StringBuilder(); sb.AppendLine(exception.ToString()); if (exception.InnerException != null) sb.AppendLine(GetExceptions(exception.InnerException)); return sb.ToString(); } /// <summary> /// Imports data asynchronously into the grid. /// </summary> /// <param name="fileType">The type of file to import from (.txt, .xls, or .xlsx).</param> /// <param name="add"></param> /// <remarks>Replaces Replace() and Add() in VB6.</remarks> private async void Import(string fileType, bool add) { try { string importFileName = String.Empty; if (!add) { mDoingOverwrite = true; mIdsToBeAdded.Clear(); } if ((mIdsToBeAdded = ImportExport.Import(MainGrid, fileType, ref importFileName)).Count > 0) { Cursor = Cursors.AppStarting; ClearNotes(); mRowIndex = 1; MainGrid.DataSource = null; if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; MainGrid.Clear(ClearFlags.Content | ClearFlags.Style); MainGrid.Rows.Count = 1; OpenProxy(); if (!add) mProxy.ClearClipboard(Settings.UserName, mInstance); else { //Keep track of where we are in the datasource for updates. if (mDataSource != null) mRowIndex = mDataSource.Rows.Count; if (mRowIndex < 1) mRowIndex = 1; } try { mProxy.SaveImportedDocName(importFileName); } catch (Exception e) { Logging.Log(e, "Clipboard", "Import (doc name)"); } finally { CloseProxy(); } mImportingFile = true; mImportingFilesDontExistList = ""; CreateTableLoader(mCurrentTemplate); CloseAsyncProxy(); OpenAsyncProxy(); SetControlAvailability(true); try { mLoading = true; mCancel = false; SendDataToLoad(); await mAsyncProxy.LoadClipboardAsync(mTableLoader); } catch (FaultException fe) { //Reset if we are not cancelling. This preserves the column headers if the user has requested a cancel. if (!mCancel) SetControlAvailability(false); if (!fe.Message.Equals("A task was canceled.")) { ClientPresentation.ShowError(fe.Message + "\n" + fe.StackTrace); Logging.Log(new AsyncDataLoadException("Async load faulted.", fe)); mLoading = false; } } catch (Exception e) { //Reset if we are not cancelling. This preserves the column headers if the user has requested a cancel. if (!mCancel) SetControlAvailability(false); //Ignore the CommunicationException, since it usually results from an "unexpected" response from the //server after the load is complete. if (!(e is CommunicationException)) ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e.GetType().ToString() + "\n" + e.Message + "\n" + e.StackTrace, "Clipboard", "Import"); mLoading = false; mCancel = true; CloseAsyncProxy(); } } } catch (Exception ex) { ClientPresentation.ShowError(ex.Message + "\n" + ex.StackTrace); Logging.Log(ex, "Clipboard", "Import"); mLoading = false; //Reset if we are not cancelling. This preserves the column headers if the user has requested a cancel. if (!mCancel) SetControlAvailability(false); Cursor = Cursors.Default; } } /// <summary> /// Handles the ImportExcel.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ImportExcel_Click(object sender, EventArgs e) { ImportExcel(); } /// <summary> /// Handles the ImportText.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ImportText_Click(object sender, EventArgs e) { ImportText(); } /// <summary> /// Loads the names of the columns in the currently selected template. /// </summary> private void LoadColumnNames(string templateName) { if (MainGrid.DataSource != null) MainGrid.DataSource = null; try { OpenProxy(); List<string> fieldNames = mProxy.GetSelectedColumnNames(templateName, Settings.UserName, Settings.User.Department); MainGrid.Rows.Count = 1; MainGrid.Cols.Count = fieldNames.Count; MainGrid.SetData(0, 0, ""); for (int i = 1; i < fieldNames.Count; i++) { MainGrid.SetData(0, i, fieldNames[i]); } MainGrid.Rows.Fixed = 1; } finally { CloseProxy(); mLoading = false; } } /// <summary> /// Loads the Clipboard Control asynchronously. /// </summary> private async void LoadControl() { if (DesignMode) return; bool load = true; //We don't want to load the Clipboard for every tab that is added. if (mInstance == 1) load = QueryLoadClipboard(); else load = false; SetUpForm(); if (!load) { LoadColumnNames("Default"); MainGrid.Redraw = true; return; } OpenAsyncProxy(); CreateTableLoader("Default"); await LoadData(); } /// <summary> /// Gets data for the Clipboard asynchronously. /// </summary> /// <returns></returns> private async Task LoadData() { try { mCurrentTemplate = myTemplates.SelectedItem.ToString(); if (mCurrentTemplateIsShared) mCurrentTemplate = ((SharedTemplate)sharedTemplates.SelectedItem).TemplateName; mTableLoader.Template = mCurrentTemplate; mTableLoader.AddDiscreteIdsOnly = mAddDiscreteIds; Cursor = Cursors.AppStarting; SetControlAvailability(true); mLoading = true; mCancel = false; SendDataToLoad(); await mAsyncProxy.LoadClipboardAsync(mTableLoader); } catch (FaultException<AsyncDataLoadException> adle) { Cursor = Cursors.Default; Logging.Log(adle, "Clipboard", "LoadData"); ClientPresentation.ShowError(GetExceptions(adle)); SetControlAvailability(false); mAsyncProxy.Abort(); } catch (FaultException fe) { Cursor = Cursors.Default; if (!fe.Message.Equals("A task was canceled.")) { Logging.Log(new AsyncDataLoadException("Async load faulted.", fe)); string message = "FaultException:\n"; message += fe.Message; message += "\nStack trace: " + fe.StackTrace; message += "\nInner Exception: "; if (fe.InnerException != null) message += fe.InnerException.Message + " - " + fe.InnerException.StackTrace; ClientPresentation.ShowError(fe.Message + "\n" + fe.StackTrace); } SetControlAvailability(false); mAsyncProxy.Abort(); } catch (Exception e) { Cursor = Cursors.Default; //Reset if we are not cancelling. This preserves the column headers if the user has requested a cancel. if (!mCancel) SetControlAvailability(false); //Ignore the CommunicationException, since it usually results from an "unexpected" response from the //server after the load is complete. if (!(e is CommunicationException)) ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e.GetType().ToString() + "\n" + e.Message + "\n" + e.StackTrace, "Clipboard", "LoadData"); mLoading = false; mCancel = true; CloseAsyncProxy(); } } /// <summary> /// Loads the selected user template. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LoadMyTemplate_Click(object sender, EventArgs e) { mCurrentTemplateIsShared = false; Reload(); } /// <summary> /// Loads notes for the selected asset. /// </summary> /// <param name="rowIndex">The row number of the selected asset.</param> private void LoadNotes(int rowIndex) { if (MainGrid.DataSource == null) return; idLabel.LabelText = ""; titleLabel.LabelText = ""; idLabel.LabelText = MainGrid[rowIndex, "ID"].ToString(); int id = Convert.ToInt32(idLabel.LabelText); OpenProxy(); try { titleLabel.LabelText = mProxy.GetNotesTitle(id); notes.Text = mProxy.GetNotes(id, Settings.UserName, mInstance); toolTips.SetToolTip(titleLabel, titleLabel.LabelText); } catch (Exception e) { Logging.Log(e, "Clipboard", "LoadNotes"); } finally { CloseProxy(); } } /// <summary> /// Loads the selected shared template. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LoadSharedTemplate_Click(object sender, EventArgs e) { mCurrentTemplateIsShared = true; Reload(); } /// <summary> /// Loads the template combos. /// </summary> /// <param name="templateName">The name of the template to display in the selected dropdown.</param> private void LoadTemplates(string templateName, bool shared) { //Get user's templates. myTemplates.Items.Clear(); string[] userTemplates = mProxy.LoadMyClipboardTemplates(); myTemplates.Items.AddRange(userTemplates); if (!shared) myTemplates.SelectedIndex = myTemplates.Items.IndexOf(templateName); else myTemplates.SelectedIndex = 0; //If there is no personal template that matches templateName for the current user, //pick the first one in the list. if (myTemplates.SelectedIndex == -1) myTemplates.SelectedIndex = 0; //Get shared templates. sharedTemplates.DataSource = null; sharedTemplates.Items.Clear(); OpenProxy(); try { SharedTemplate[] sharedTemplateList = mProxy.LoadSharedClipboardTemplates(Settings.User.Department); sharedTemplates.DataSource = sharedTemplateList; sharedTemplates.DisplayMember = "TemplateName"; sharedTemplates.ValueMember = "Department"; if (shared) { SharedTemplate st = new SharedTemplate() { TemplateName = templateName, Department = Settings.User.Department }; sharedTemplates.SelectedIndex = sharedTemplates.Items.IndexOf(st); } else sharedTemplates.SelectedIndex = 0; if (sharedTemplates.SelectedIndex == -1) { if (sharedTemplates.Items.Count > 0) sharedTemplates.SelectedIndex = 0; } mCurrentTemplate = templateName; mCurrentTemplateIsShared = shared; } finally { CloseProxy(); } } /// <summary> /// Updates the database to indicate that the specified shared template is in use. /// </summary> /// <param name="templateName">The name of the template to lock.</param> private void LockSharedTemplate(string templateName) { OpenProxy(); try { if (!mProxy.UpdateSharedTemplateLastUser(templateName, Settings.User.Department, Settings.UserName)) { MessageBox.Show("Failed to lock shared template '" + templateName + "'.", "Lock Template", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception e) { Logging.Log(e, "Clipboard", "LockSharedTemplate"); } finally { CloseProxy(); } } /// <summary> /// Reorders the columns on the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_AfterDragColumn(object sender, DragRowColEventArgs e) { mIsDirty = true; mColumnNamesInOrder.Clear(); //Load the new column order. foreach (Column column in MainGrid.Cols) mColumnNamesInOrder.Add(column.Index, column.Name); } /// <summary> /// Reorders rows on the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_AfterDragRow(object sender, DragRowColEventArgs e) { if (e.Position < 1) e.Cancel = true; } /// <summary> /// Resizes all rows based on the size of the selected row. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_AfterResizeRow(object sender, RowColEventArgs e) { ResizeRows(e.Row); } /// <summary> /// Prepares the grid for dragging and dropping. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_BeforeMouseDown(object sender, BeforeMouseDownEventArgs e) { EnhancedFlexGrid grid = sender as EnhancedFlexGrid; HitTestInfo hti = grid.HitTest(e.X, e.Y); if (hti.Type.Equals(HitTestTypeEnum.RowHeader)) { try { int index = hti.Row; mStartIndex = index; grid.Select(index, 0, index, grid.Cols.Count - 1, false); mParentTab.TabParent.SourceGrid = grid; DataTable dt = grid.DataSource as DataTable; DragDropEffects dd = grid.DoDragDrop(dt.Rows[index - 1], DragDropEffects.Move); if (dd.Equals(DragDropEffects.Move)) { if (!mParentTab.TabParent.SourceGrid.Equals(grid)) grid.Rows.Remove(index); } } catch (Exception ex) { Logging.Log(ex, "Clipboard", "MainGrid.BeforeMouseDown"); } } } /// <summary> /// Selects an asset. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_Click(object sender, EventArgs e) { if (mLoading || mCancel) return; if (MainGrid.Rows.Count < 2 || MainGrid.Cols.Count < 2) return; HitTestInfo hti = MainGrid.HitTest(MainGrid.PointToClient(new Point(MousePosition.X, MousePosition.Y))); if (hti.Row < 1 || hti.Column < 1) return; LoadNotes(hti.Row); if (hti.Column == MainGrid.Cols["viewButton"].Index) { //We don't want to use the result of the user clicking the View Media column header. if (hti.Row == -1) return; ViewMedia(hti.Row); } } /// <summary> /// Handles the MainGrid.DoubleClick event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_DoubleClick(object sender, EventArgs e) { if (MainGrid.Rows.Count < 2) return; if (MainGrid.RowIndex < 1) return; OpenMovieInfo(MainGrid.RowIndex); } /// <summary> /// Performs a drag/drop operation on the main grid when the user moves a row. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_DragDrop(object sender, DragEventArgs e) { EnhancedFlexGrid grid = sender as EnhancedFlexGrid; grid.BeginUpdate(); grid.Redraw = false; try { Point point = grid.PointToClient(new Point(e.X, e.Y)); HitTestInfo hti = grid.HitTest(point.X, point.Y); int index = hti.Row; if (index < 0) index = grid.Rows.Count; if (index < 1) index = 1; grid.DataSource = null; if (mParentTab.TabParent.SourceGrid != null) { DataRow row = (DataRow)e.Data.GetData(typeof(DataRow)); if (mParentTab.TabParent.SourceGrid.Equals(grid)) //Same grid. { mDataSource.MoveRow(mStartIndex - 1, index - 1); } else { mIdsToBeAdded.Clear(); if (row["ID"].GetType() != typeof(DBNull)) mIdsToBeAdded.Add(Convert.ToInt32(row["ID"])); //Load the default template if there is not data in the grid already. if (mDataSource == null) mDataSource = row.Table.Clone(); grid.DataSource = mDataSource; if (CheckIdsPresent()) AddIds(); } } } catch (Exception ex) { Logging.Log(ex, "Clipboard", "MainGrid.DragDrop"); } finally { grid.Clear(ClearFlags.All); if (grid.DataSource == null) grid.DataSource = mDataSource; FormatGrid(); grid.Redraw = true; grid.EndUpdate(); } } /// <summary> /// Handles dragging of a row in the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_DraggingRow(object sender, DragRowColEventArgs e) { if (e.Position < 1) e.Cancel = true; } /// <summary> /// Provides feedback during drag/drop operations. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainGrid_DragOver(object sender, DragEventArgs e) { if (mParentTab.TabParent.SourceGrid != null) { if (e.Data.GetDataPresent(typeof(DataRow))) e.Effect = DragDropEffects.Move; } } /// <summary> /// Handles the MyTemplates.SelectedIndexChanged event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MyTemplates_SelectedIndexChanged(object sender, EventArgs e) { if (myTemplates.SelectedIndex == -1) return; if (mLoading || mInSetup) return; if (mLoadingTemplates && mCurrentTemplateIsShared) return; mChangingTemplate = true; //Suppress the request to clear the Clipboard. mCurrentTemplate = myTemplates.Text; if (QueryLoadClipboard()) { mLastTemplateUsed = mCurrentTemplate; mCurrentTemplateIsShared = false; Reload(); } else { if (!String.IsNullOrEmpty(mLastTemplateUsed)) mCurrentTemplate = mLastTemplateUsed; if (!mDetached && !mDetaching) LoadColumnNames(mCurrentTemplate); else if (mDetached) { //LoadColumnNames(mCurrentTemplate); mCurrentTemplateIsShared = false; Reload(); } } mChangingTemplate = false; } /// <summary> /// Sets the parent tab text to be that of the current template. /// The parent tab is null if we are detached. /// </summary> private void NameTab() { if (mParentTab != null) { if (mParentTab.InvokeRequired) mParentTab.BeginInvoke(new Action(() => { mParentTab.Name = mInstance.ToString() + " - " + mCurrentTemplate; })); else mParentTab.Name = mInstance.ToString() + " - " + mCurrentTemplate; } } /// <summary> /// Handles keyboard commands on the Notes textbox. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Notes_KeyUp(object sender, KeyEventArgs e) { if ((e.Modifiers & Keys.Control) != 0) { switch (e.KeyCode) { case Keys.A: notes.SelectAll(); break; case Keys.C: notes.Copy(); break; case Keys.V: notes.Text = System.Windows.Forms.Clipboard.GetText(); break; case Keys.X: CommitChanges(); //Save the content for restoration. mNotesText = notes.Text; notes.Cut(); mLastOperation = LastDeleteOperation.ClearText; break; default: e.Handled = true; break; } } else e.Handled = true; } /// <summary> /// Shows the current status of the asynchronous load. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NotifyIcon_Click(object sender, EventArgs e) { notifyIcon.ShowBalloonTip(1000); } /// <summary> /// Activates the owner of the current NotifyIcon instance. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NotifyIcon_DoubleClick(object sender, EventArgs e) { if (((Form)mParentTab.TabParent.Parent).WindowState == FormWindowState.Minimized) ((Form)mParentTab.TabParent.Parent).WindowState = FormWindowState.Normal; ((Form)mParentTab.TabParent.Parent).Activate(); } /// <summary> /// Creates the asynchronous proxy. /// </summary> private void OpenAsyncProxy() { if (mAsyncProxy != null && (mAsyncProxy.State == CommunicationState.Opened || mAsyncProxy.State == CommunicationState.Created)) mAsyncProxy.Close(); //Assign the server endpoint address dynamically. string name = "AsyncClipboard"; string server = Settings.GetAsyncSessionServer(); ServiceEndpoint endpoint = Settings.Endpoints[name]; Logging.Log("The binding name is " + endpoint.Binding.Name, "Clipboard", "OpenAsyncProxy"); endpoint.Address = new EndpointAddress(new Uri(Settings.AsyncBaseAddresses[name].Replace("localhost", server)), EndpointIdentity.CreateSpnIdentity("")); //A state of "Faulted" usually means that the user cancelled the previous load. if (mAsyncProxy == null || mAsyncProxy.State == CommunicationState.Closed || mAsyncProxy.State == CommunicationState.Faulted) mAsyncProxy = new AsyncClipboardProxy(new InstanceContext(this), endpoint); if (mAsyncProxy.State == CommunicationState.Closed) mAsyncProxy.Open(); //Set inner timeouts to prevent the system from hanging during a load. //Even though we have already set these in the proxy itself, this here is a sanity move. ((IContextChannel)mAsyncProxy.InnerChannel).OperationTimeout = TimeSpan.FromMinutes(30); ((IContextChannel)mAsyncProxy.InnerDuplexChannel).OperationTimeout = TimeSpan.FromMinutes(30); } /// <summary> /// Opens the MovieInfo VB6 module with the selected ID. /// </summary> private void OpenMovieInfo(int rowIndex) { string id = MainGrid.GetData(rowIndex, "ID").ToString(); Settings.OpenOCX(Module.MovieInfo, id); mParentTab.RestorePosition(); } /// <summary> /// Creates the synchronous proxy. /// </summary> private void OpenProxy() { if (mProxy == null || mProxy.State != CommunicationState.Opened) { mProxy = new ClipboardProxy(Settings.Endpoints["Clipboard"]); mProxy.Open(); mProxy.CreateClipboardMethods(Settings.ConnectionString, Settings.UserName, mInstance, Settings.User.Department); } } /// <summary> /// Removes the "View Media" column from the worksheet. /// </summary> /// <param name="exportFileName">The fully-qualified name of the file to process.</param> private void PostProcessExcelFile(string exportFileName) { using (C1XLBook book = new C1XLBook()) { FileFormat format = FileFormat.Biff8; //Excel 97-2003 (.xls) format. if (exportFileName.EndsWith(".xlsx")) format = FileFormat.OpenXml; book.Load(exportFileName, format, true); XLSheet sheet = book.Sheets[0]; int index = 0; for (int i = 0; i < sheet.Columns.Count; i++) { if (sheet[1, i].Value == null) continue; if (sheet[1, i].Value.ToString().Equals("View Media")) { index = i; break; } } sheet.Columns.RemoveAt(index); // Remove blank 1st column sheet.Columns.RemoveAt(0); // Freezes the 1st column. // (In the grid 2 columns are frozen and we don't want that in the export.) sheet.Columns.Frozen = 1; book.Save(exportFileName, format); } } /// <summary> /// Removes the "View Media" column from the file. /// </summary> /// <param name="exportFileName">The fully-qualified name of the file to process.</param> private void PostProcessTextFile(string exportFileName) { string tempFileName = exportFileName + ".tmp"; //Make a temporary copy of the exported file and delete the original. File.Copy(exportFileName, tempFileName); File.Delete(exportFileName); string line = ""; using (TextReader reader = File.OpenText(tempFileName)) { using (TextWriter writer = File.CreateText(exportFileName)) { while ((line = reader.ReadLine()) != null) { writer.WriteLine(line.Replace(";View Media", "")); } writer.Flush(); } } //Delete the temporary file. File.Delete(tempFileName); } /// <summary> /// Displays a message box asking the user if he or she would like to add to the grid or overwrite the /// existing data on import. /// </summary> /// <returns>The result of the user's selection.</returns> private DialogResult QueryAddOverwrite() { Console.Beep(); return LFPMessageBox.Show("Add to the grid or overwrite?", "Import", "Add", "Overwrite"); } /// <summary> /// Asks the user if he or she would like to load the Clipboard. /// </summary> /// <returns>True if the Clipboard should load; otherwise false.</returns> private bool QueryLoadClipboard() { if (mDetaching || mDetached) return false; if (!mLoadingTemplates && !mChangingTemplate) { Console.Beep(); if (MessageBox.Show("Do you want to load the Clipboard?", "Load Clipboard?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { if (String.IsNullOrEmpty(mCurrentTemplate)) mCurrentTemplate = "Default"; //DoClear(); //Requirement as specified in Clipboard Bug List from 07302015. LoadColumnNames(mCurrentTemplate); //If uncommenting the line above, comment out this line. mLoading = false; mLastOperation = LastDeleteOperation.None; return false; } return true; } return true; } /// <summary> /// Handles the Refresh.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Refresh_Click(object sender, EventArgs e) { Reload(); } /// <summary> /// Releases the user's lock on a shared template. /// </summary> /// <param name="templateName">The name of the template to release.</param> private void ReleaseLock(string templateName) { OpenProxy(); try { string lastUser = mProxy.GetSharedTemplateLastUser(templateName, Settings.User.Department); if (!String.IsNullOrEmpty(lastUser)) { //Clear the lock if the current user was the last user to use the template. if (lastUser.Equals(Settings.UserName)) { if (!mProxy.UpdateSharedTemplateLastUser(templateName, Settings.User.Department, "")) { MessageBox.Show("Failed to release lock on shared template '" + templateName + "'.", "Release Lock", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } catch (Exception e) { Logging.Log(e, "Clipboard", "SetReleaseLock"); } finally { CloseProxy(); } } /// <summary> /// Handles the RemoveHighlightedItems.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RemoveHighlightedItems_Click(object sender, EventArgs e) { RemoveSelectedItems(); } /// <summary> /// Removes the selected assets from the grid, saving the IDs for a possible restore. /// </summary> private void RemoveSelectedItems() { if (MainGrid.DataSource == null) return; Console.Beep(); if (MessageBox.Show("Are you sure you want to remove these IDs?", "Clipboard", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return; //Perform the last delete operation before doing this one. CommitChanges(); //We can handle non-contiguous range selections. //Save the selected IDs for restore. mIdsToBeDeleted = new List<int>(); MainGrid.BeginUpdate(); MainGrid.Redraw = false; bool rowsRemoved = false; //This only gets Ctrl selected rows. We need to get both Ctrl and Shift selected rows List<int> rowIndexes = new List<int>(); for (int i = 1; i < MainGrid.Rows.Count; i++) { if (MainGrid.Rows[i].Selected) { rowIndexes.Add(i); } } //Sort the indexes so that we remove the bottommost row first. rowIndexes.Reverse(); for (int i = 0; i < rowIndexes.Count; i++) { object data = MainGrid.GetData(rowIndexes[i], "ID"); int id; if (data != null && Int32.TryParse(data.ToString(), out id)) { mIdsToBeDeleted.Add(id); MainGrid.Rows.Remove(rowIndexes[i]); rowsRemoved = true; } } // Return list to original order in case a user performs an Undo mIdsToBeDeleted.Reverse(); if (rowsRemoved) { mDataSource.AcceptChanges(); MainGrid.Redraw = true; MainGrid.ClearSelections(); MainGrid.EndUpdate(); try { OpenProxy(); ClearNotes(); } finally { mProxy.Close(); } mLastOperation = LastDeleteOperation.DeleteRows; } } /// <summary> /// Resizes the rows to fit their content. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ResizeAllRows_Click(object sender, EventArgs e) { if (MainGrid.DataSource == null) return; //if (resizeAllRows.Checked) // ResizeRows(1); } /// <summary> /// Resizes all the rows in the Clipboard based on the height of the first selected row. /// </summary> /// <param name="rowIndex">The index of the current row.</param> private void ResizeRows(int rowIndex) { MainGrid.BeginUpdate(); MainGrid.AutoResize = false; MainGrid.Redraw = false; try { int height = MainGrid.Rows[rowIndex].Height; if (resizeAllRows.Checked) { for (int i = 1; i < MainGrid.Rows.Count; i++) { MainGrid.Rows[i].Height = height; } } } finally { MainGrid.Redraw = true; MainGrid.AutoResize = true; MainGrid.EndUpdate(); } } /// <summary> /// Restores previously deleted assets to the grid. /// </summary> /// <returns>True if successful; otherwise false.</returns> private bool RestoreRows() { bool result = true; //Restore the deleted rows to the grid. try { foreach (int id in mIdsToBeDeleted) { if (!mIdsToBeAdded.Contains(id)) mIdsToBeAdded.Add(id); } Reload(); mLastOperation = LastDeleteOperation.None; } catch (Exception e) { Logging.Log(e); result = false; } return result; } /// <summary> /// Saves the user's grid preferences to the database. /// </summary> /// <param name="templateName">The name of the new template to display.</param> /// <param name="shared">Flag indicating whether the selected template is shared or personal.</param> private void SaveGridPreferences(string templateName, bool shared) { if (String.IsNullOrEmpty(templateName.Trim())) { templateName = (!String.IsNullOrEmpty(mCurrentTemplate.Trim()) ? mCurrentTemplate : "Default"); shared = mCurrentTemplateIsShared; } //Saving should be done already when the user closes the Preferences form. ReloadTemplates(templateName, shared); } /// <summary> /// Saves the name of the last imported document to the database. /// </summary> /// <param name="docName">The full path and file name to save.</param> private void SaveImportedDocName(string docName) { OpenProxy(); try { string result = mProxy.SaveImportedDocName(docName); lastDocumentLabel.LabelText = result; } catch (Exception e) { Logging.Log(e, "Clipboard", "SaveImportedDocName"); } finally { CloseProxy(); } } /// <summary> /// Handles the SaveNotes.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SaveNotes_Click(object sender, EventArgs e) { SaveNotes(); } /// <summary> /// Saves the user's screen preferences (appearance of FancyGroupBox, number of tabs, etc.) to the database. /// </summary> /// <param name="resultText">The preferences, as a pipe-delimited string.</param> private void SaveScreenPreferences(string resultText) { string[] values = resultText.Split('|'); if (Settings.SaveScreenPreferences(values[0], values[1], values[2], values[3], "Clipboard")) { if (UpdateScreenPreferences != null) UpdateScreenPreferences(this, new UpdateEventArgs(values)); } } /// <summary> /// Handles the ScreenPreferences.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ScreenPreferences_Click(object sender, EventArgs e) { SetScreenPreferences(); } /// <summary> /// Processes the result of the user's selection of screen preferences. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ScreenPreferences_ShowModal(object sender, ModalEventArgs e) { if (e.DialogResult == DialogResult.OK) SaveScreenPreferences(e.ResultText); } /// <summary> /// Sends a cancellation request on another thread. /// </summary> /// <param name="asyncProxy">The asynchronous proxy.</param> private void SendCancelRequest(object asyncProxy) { ((AsyncClipboardProxy)asyncProxy).CancelClipboardAsync(); } /// <summary> /// Passes asset IDs to the asynchronous loader. /// </summary> private void SendDataToLoad() { //if (Environment.MachineName.Contains("NBIDEV2")) // Logging.Log("Number of IDs to load: " + mIdsToBeAdded.Count.ToString(), "Clipboard", "SendDataToLoad"); if (mIdsToBeAdded.Count < 1) return; if (mAsyncProxy == null || mAsyncProxy.State != CommunicationState.Opened) OpenAsyncProxy(); //Load the IDs in chunks, since WCF errors out if the message size is too big. List<int> chunk = new List<int>(); for (int i = 0; i < mIdsToBeAdded.Count; i++) { chunk.Add(mIdsToBeAdded[i]); if (i > 0 && i % 100 == 0) { //Lock this update to prevent the system from throwing an ArgumentException relating to //array length. lock (mLock) mAsyncProxy.SendNextChunk(chunk); chunk.Clear(); } } //Get the remaining IDs. lock (mLock) mAsyncProxy.SendNextChunk(chunk); chunk.Clear(); } /// <summary> /// Sets the text and color of a cell in the grid. /// </summary> /// <param name="rowIndex">The index of the row the cell belongs to.</param> /// <param name="column">The column the cell belongs to.</param> private void SetCellStyle(int rowIndex, Column column) { if (rowIndex < 0) return; if (column.Index < 0) return; try { //Format cells for statuses. switch (column.Name) { case "viewButton": MainGrid.SetCellStyle(rowIndex, column.Index, "View Media"); break; case "Expiry": case "B'cast Rights": case "Internet Rights": case "IPTV Rights": case "VOD Rights": case "Wireless Rights": case "Hotel Rights": if (MainGrid.GetData(rowIndex, column.Index).ToString().Equals("In Perp.")) MainGrid.SetCellStyle(rowIndex, column.Index, "Passed"); else { string cellString = MainGrid.GetData(rowIndex, column.Index).ToString(); if (cellString.Contains(" ")) cellString = cellString.Remove(cellString.IndexOf(' ')); if (!String.IsNullOrEmpty(cellString.Trim())) { DateTime tempDate = Convert.ToDateTime(cellString); if (tempDate < DateTime.Now) MainGrid.SetCellStyle(rowIndex, column.Index, "Failed"); else MainGrid.SetCellStyle(rowIndex, column.Index, "Passed"); } } break; case "AM QC": case "FCP QC": case "DVP Status": string statusText = MainGrid.GetData(rowIndex, column.Index).ToString(); if (statusText.EndsWith("18")) { MainGrid.SetData(rowIndex, column.Index, statusText.Replace("18", "")); MainGrid.SetCellStyle(rowIndex, column.Index, "18 Month QC"); } else { if (statusText.Equals("NOA") || statusText.Equals("No Asset") || statusText.Equals("No AM")) MainGrid.SetCellStyle(rowIndex, column.Index, "No Asset"); else { if (statusText.Equals("Under Review")) MainGrid.SetCellStyle(rowIndex, column.Index, "Failed"); else MainGrid.SetCellStyle(rowIndex, column.Index, statusText); } } break; case "FCPXML Exists": case "XML-CC Delivered": string text = MainGrid.GetData(rowIndex, column.Index).ToString(); if (text.StartsWith("|")) //"|Passed" { text = text.Replace("|", ""); MainGrid.SetData(rowIndex, column.Index, text); MainGrid.SetCellStyle(rowIndex, column.Index, text); } else //"Date|status" { string[] vals = text.Split('|'); //Restore the date value to the cell. MainGrid.SetData(rowIndex, column.Index, vals[0]); if (vals.Length > 1) { if (!vals[1].Equals("xml")) MainGrid.SetCellStyle(rowIndex, column.Index, vals[1]); } } break; case "SCC Exists": string scc = MainGrid.GetData(rowIndex, column.Index).ToString(); if (scc.Equals("Yes")) MainGrid.SetCellStyle(rowIndex, column.Index, "Passed"); else MainGrid.SetCellStyle(rowIndex, column.Index, "Failed"); break; case "Conforming Status": string conformingText = MainGrid.GetData(rowIndex, column.Index).ToString(); if (!String.IsNullOrEmpty(conformingText)) { string colorName = "Conforming-" + conformingText; MainGrid.SetCellStyle(rowIndex, column.Index, colorName); } break; } } catch (Exception e) { ClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); Logging.Log(e, "Clipboard", "SetCellStyle row=" + rowIndex + ", Column=" + column.Name + " index=" + column.Index); } } /// <summary> /// Invokes the ClipboardPreferences dialog. /// </summary> private void SetClipboardPreferences() { if (mClipboardPreferences == null || mClipboardPreferences.IsDisposed) { mClipboardPreferences = new ClipboardTemplatePreferences(Settings.User, Settings.ConnectionString, (SkinnableFormBase)mParent, mLastTemplateUsed); mClipboardPreferences.ShowModal += ClipboardPreferences_ShowModal; } else mClipboardPreferences.SetLastTemplateUsed(mLastTemplateUsed); mClipboardPreferences.Show(); } /// <summary> /// Formats a column based on its content. /// </summary> /// <param name="column">The column to format.</param> private void SetColumnStyle(Column column) { CellStyle cs = null; if (!MainGrid.Styles.Contains("wrap")) { cs = MainGrid.Styles.Add("wrap"); cs.WordWrap = true; } if (!MainGrid.Styles.Contains("left")) { cs = MainGrid.Styles.Add("left"); cs.TextAlign = TextAlignEnum.LeftCenter; } if (!MainGrid.Styles.Contains("center")) { cs = MainGrid.Styles.Add("center"); cs.TextAlign = TextAlignEnum.CenterCenter; } if (!MainGrid.Styles.Contains("wrapleft")) { cs = MainGrid.Styles.Add("wrapleft"); cs.TextAlign = TextAlignEnum.LeftCenter; cs.WordWrap = true; } int index = MainGrid.Cols[column.Name].Index; switch (column.Name) { case "viewButton": //Turn off filtering for this column. It is unnecessary. MainGrid.Cols[index].AllowFiltering = AllowFiltering.None; break; case "ID": case "Alt Next Door ID": case "Xcode Source ID": case "Xcode Source ID Aspect Ratio": case "Alt. HD/SD ID": case "Upcoming VOD Pitches": case "Scene Counter": case "On Archive": case "Submit for WMV Screener": case "XML-CC Delivered": case "DAM - SOM": case "DAM - EOM": case "DAM - TRT": case "FCP - SOM": case "FCP - EOM": case "FCP - TRT": case "Comp Source": MainGrid.Cols[index].Style = MainGrid.Styles["left"]; //We do not need to filter by ID, since by definition each value is unique. //TODO: Perhaps build a custom range filter for this column. if (column.Name.Equals("ID")) MainGrid.Cols[index].AllowFiltering = AllowFiltering.None; break; case "Has Anal": case "Next Door": case "No XXX": case "Title On Asset": case "HD": case "International Only": case "Titles Approved": case "DVP Status": case "SCC Last Modified On": case "SCC Exists": MainGrid.Cols[index].Style = MainGrid.Styles["center"]; break; case "Release Schedules": case "Sub-Rating": case "Alt. HD/SD ID - Air Dates": case "Alt. HD/SD ID - Upcoming VOD Pitches": case "Alt Next Door ID - Air Dates": case "Alt Next Door ID - Upcoming VOD Pitches": case "Compliance Statement": case "AM QC": case "FCP QC": case "Notes - Movie Info": case "Notes - Conforming": case "Notes - Materials": case "Media Assets": case "Master ID": case "Actors - Female": case "Actors - Male": MainGrid.Cols[index].Style = MainGrid.Styles["wrap"]; if (column.Name.Equals("Alt. HD/SD ID - Upcoming VOD Pitches") || column.Name.Equals("Alt Next Door ID - Upcoming VOD Pitches")) MainGrid.Cols[index].Style = MainGrid.Styles["wrapleft"]; break; } if (column.Name.Contains("Synopsis")) MainGrid.Cols[index].Style = MainGrid.Styles["wrap"]; } /// <summary> /// Enables or disables controls on the current instance based on ProgressBar visibility (indicating a data load /// is in progress). /// </summary> /// <param name="progressBarVisible">Flag indicating whether the ProgressBar is visible.</param> private void SetControlAvailability(bool progressBarVisible) { MainGrid.Enabled = true; assetGroup.Enabled = copyIds.Enabled = true; templatesGroup.Enabled = notesGroup.Enabled = true; channelHeaderIdsGroup.Enabled = true; if (mCancel) { if (MainGrid.DataSource != null) MainGrid.DataSource = null; if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; MainGrid.Rows.Count = 1; MainGrid.Cols.Count = 1; } foreach (Control c in this.Controls) { if (c is ToolStrip) { ToolStrip ts = c as ToolStrip; foreach (ToolStripItem item in ts.Items) { if (item is ToolStripButton || item is ToolStripDropDownButton) item.Enabled = true; if (item.Name == "cancelLoad") item.Enabled = false; } } } if (loadProgress.InvokeRequired) loadProgress.BeginInvoke(new Action(() => { loadProgress.Visible = progressBarVisible; loadProgress.PercentValue = 0; loadProgress.TotalValue = 0; })); else { loadProgress.Visible = progressBarVisible; loadProgress.PercentValue = 0; loadProgress.TotalValue = 0; } if (progressBarVisible) { assetGroup.Enabled = copyIds.Enabled = false; templatesGroup.Enabled = notesGroup.Enabled = false; channelHeaderIdsGroup.Enabled = false; MainGrid.ClearSelections(); MainGrid.Enabled = false; cancelLoad.Enabled = true; notifyIcon.Visible = true; notifyIcon.Text = "Clipboard #" + mInstance.ToString(); foreach (Control c in this.Controls) { if (c is ToolStrip) { ToolStrip ts = c as ToolStrip; foreach (ToolStripItem item in ts.Items) { //We want the user to be able to cancel the load and also to work on preferences //while loading. if (item is ToolStripButton || item is ToolStripDropDownButton) { if (item.Name != "screenPreferences" && item.Name != "clipboardPreferences" && item.Name != "cancelLoad") item.Enabled = false; } } } } } else { Application.DoEvents(); mLoading = false; if (!MainGrid.IsDisposed) { MainGrid.Visible = true; MainGrid.Redraw = true; //mainGrid.AutoResize = true; MainGrid.AllowEditing = false; MainGrid.EndUpdate(); } } } /// <summary> /// Sets the default column widths based on the size of the column contents. /// </summary> /// <param name="column">The name of the column to set.</param> private void SetDefaultColumnWidth(Column column) { OpenProxy(); //Get titles. try { if (mTitles == null) mTitles = mProxy.GetTitles(); } catch (Exception e) { Logging.Log(e, "Clipboard", "SetDefaultColumnWidth (GetTitles)"); } finally { CloseProxy(); } switch (column.Name) { case "Notes - Movie Info": case "Notes - Conforming": column.Width = 400; break; case "Release Schedules": case "Received Language QC": case "Channels": case "Header IDs in Order": case "Alt. HD/SD ID - Upcoming VOD Pitches": case "Alt Next Door ID - Upcoming VOD Pitches": case "Timeline Complete - History Dates": case "Fix not QC'd - History Dates": column.Width = 125; break; case "FCP Status - 1st QC": case "FCP Status - 2nd QC": case "FCP Status - Delivery QC": case "FCP Status - Archive QC": case "Genre": case "Who Checked Timeline Complete": case "MSO Title - AT&T - Broadcast": case "MSO Title - AT&T - VOD": case "MSO Title - Cablevision - Broadcast": case "MSO Title - Cablevision - VOD": case "MSO Title - Charter - Broadcast": case "MSO Title - Charter - VOD": case "MSO Title - Comcast - Broadcast": case "MSO Title - Comcast - VOD": case "MSO Title - DirecTV - Broadcast": case "MSO Title - DirecTV - VOD": case "MSO Title - DISH - Broadcast": case "MSO Title - DISH - VOD": case "MSO Title - Time Warner - Broadcast": case "MSO Title - Time Warner - VOD": case "MSO Title - Verizon - Broadcast": case "MSO Title - Verizon - VOD": case "Full Length Double Feature": case "Interstitial Type": case "Director": case "Licensor": case "Studio": case "B'cast Rights": case "Internet Rights": case "IPTV Rights": case "VOD Rights": case "Wireless Rights": case "Hotel Rights": case "Upcoming VOD Pitches": case "Submit for WMV Screener": case "XML-CC Delivered": case "In Edit - Editor": case "Timeline Complete - Editor": case "Fix not QC'd - Editor": column.Width = 185; break; case "F.A.D.": case "N.A.D.": case "L.A.D.": case "Air Dates": case "License Start Date": case "Compliance Statement": case "SCC Last Modified On": case "Linear N.A.D.": case "Media Available - Date": case "In Edit - Date": case "Timeline Complete - Date": case "Fix not QC'd - Date": column.Width = 150; break; case "Actors - Female": case "Actors - Male": case "Country of Origin": case "Materials Complete Date": case "Type": case "Has Box Cover Images": case "Editor": case "OFRB Certification": case "Structure": case "Location - Air Master": case "Location - DMG": case "Location - FCP Project": case "Location - Digital Air Master": case "Location - Hard Drive": case "Location - Studio Master Backup": case "Location - Digital Studio Master Backup": case "Location - Original Footage": case "NAD": case "Alt. HD/SD ID": case "Xcode Source ID": case "Xcode Source ID Aspect Ratio": case "Titles Approved": case "Media Assets": case "Aspect Ratio": case "Master ID": case "Frame Rate": case "Resolution": case "File Format": case "International Only": case "Alt. HD/SD ID - F.A.D.": case "Alt. HD/SD ID - N.A.D.": case "Alt. HD/SD ID - L.A.D.": case "Alt. HD/SD ID - Air Dates": case "Alt Next Door ID - F.A.D.": case "Alt Next Door ID - N.A.D.": case "Alt Next Door ID - L.A.D.": case "Alt Next Door ID - Air Dates": column.Width = 100; break; case "Conforming Status": column.Width = 100; mConformingStatusIndex = MainGrid.Cols["Conforming Status"].Index; break; case "Pixilation Type": case "Materials Complete": case "Language": case "Movie Created By": case "Movie Created On": case "Movie Last Updated": case "Movie Updated By": case "OFRB #": case "On Archive": case "MRG Title": case "Alt Next Door ID": case "Title On Asset": case "AM QC": case "FCP QC": case "Expiry": column.Width = 90; break; case "ID": case "Produced": case "Runtime": case "Rating": case "Sub-Rating": case "Retired": case "Hidden": case "Extended": case "NTSC Use Only": case "HD": case "Is Gay": case "Squirting": case "No XXX": case "FCPXML Exists": case "SCC Exists": case "DAM - SOM": case "DAM - EOM": case "DAM - TRT": case "FCP - SOM": case "FCP - EOM": case "FCP - TRT": case "On RPS": case "Next Door": column.Width = 90; break; default: foreach (SystemSearchTitles sst in mTitles) { if (column.Name.Equals(sst.TitleName)) column.Width = 175; } break; } if (column.Name.Contains("Synopsis")) column.Width = 125; } /// <summary> /// Invokes the ScreenPreferences dialog. /// </summary> private void SetScreenPreferences() { if (mScreenPreferences == null || mScreenPreferences.IsDisposed) { mScreenPreferences = new ScreenPreferences(mParent.Parameters, (SkinnableFormBase)mParent, "Clipboard", "clipboard", true); mScreenPreferences.ShowModal += ScreenPreferences_ShowModal; } mScreenPreferences.Show(); } /// <summary> /// Populates the controls on the form. /// </summary> private void SetUpForm() { mInSetup = true; //separator8.Visible = detach.Visible = true; //detach.Enabled = attach.Enabled = true; OpenProxy(); try { //Get media path for SCC. mDirSCC = mProxy.GetMediaPath("SCC"); //Only display the Header IDs group for MPD, Tech Ops, and BIS. BIS can see everything. if (Settings.User.Department.Equals("Media Distribution") || Settings.User.Department.Equals("BIS") || Settings.User.Department.Equals("Technical")) channelHeaderIdsGroup.Visible = true; //Do not load the next two items if the Header group is hidden. if (channelHeaderIdsGroup.Visible) { //Load Channels combobox. string[] vodChannels = mProxy.GetVODChannels(); if (vodChannels != null && vodChannels.Length > 0) { channels.Items.Clear(); channels.Items.AddRange(vodChannels); channels.SelectedIndex = 0; } //Set the default date in the header date picker. headers.Value = DateTime.Now; } string docName = mProxy.LoadLastDocName(); if (!String.IsNullOrEmpty(docName)) lastDocumentLabel.LabelText = docName; LoadTemplates("Default", false); mConformingColors = ClientPresentation.AssignConforming(); //Set up the TableLoader using the user's default template. CreateTableLoader(myTemplates.SelectedItem.ToString()); //Set the text on the first tab to be "Default". if (mParentTab != null) { if (mParentTab.TabParent != null) { if (((DetachableTabControl)mParentTab.TabParent).TabPages.Count <= 2) mParentTab.Text = myTemplates.SelectedItem.ToString(); } } OpenProxy(); } catch (Exception e) { Logging.Log(e, "Clipboard", "SetUpForm"); } finally { CloseProxy(); //channelHeaderIdsGroup.Left -= 20; mInSetup = false; } } /// <summary> /// Sets the widths of the columns in the grid based on the user's preferences. /// </summary> private void SetUserColumnWidths() { OpenProxy(); UsersClipboard uc = null; try { uc = mProxy.GetMyTemplate(mCurrentTemplate, Settings.UserName, Settings.User.Department); } catch (Exception e) { Logging.Log(e, "Clipboard", "SetUserColumnWidths"); } finally { CloseProxy(); } if (uc != null) { Type t = uc.GetType(); PropertyInfo[] properties = t.GetProperties(); for (int i = 1; i < MainGrid.Cols.Count; i++) { if (!MainGrid.Cols[i].Name.Equals("viewButton")) { try { //If there is no value, or the width is 0, use the default value in SetDefaultColumnWidth(). PropertyInfo pi = properties.Where(x => x.Name.Contains(i.ToString() + "_Width")).First(); object o = pi.GetValue(uc); if (o != null) { int width = Convert.ToInt32(o); if (width > 0) MainGrid.Cols[i].Width = width; } } catch (InvalidOperationException) //No value for this column. { continue; } } } } } /// <summary> /// Handles the SharedTemplates.Enter event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SharedTemplates_Enter(object sender, EventArgs e) { //Save this value for locking purposes in case a shared template owner tries to delete the //template while it is in use. mLastTemplateUsed = ((SharedTemplate)sharedTemplates.SelectedItem).TemplateName; } /// <summary> /// Handles the SharedTemplates.SelectedIndexChanged event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SharedTemplates_SelectedIndexChanged(object sender, EventArgs e) { if (mInSetup) return; if (sharedTemplates.SelectedIndex == -1) return; if (mLoading) return; if (mLoadingTemplates && !mCurrentTemplateIsShared) return; mChangingTemplate = true; //Suppress the request to clear the Clipboard. if (QueryLoadClipboard()) { ReleaseLock(mLastTemplateUsed); //mLastTemplateUsed = mCurrentTemplate; LockSharedTemplate(mCurrentTemplate); mCurrentTemplate = ((SharedTemplate)sharedTemplates.SelectedItem).TemplateName; mLastTemplateUsed = mCurrentTemplate; mCurrentTemplateIsShared = true; Reload(); } else { mCurrentTemplate = mLastTemplateUsed; if (!mDetaching && !mDetached) LoadColumnNames(mCurrentTemplate); else if (mDetached) { //LoadColumnNames(mCurrentTemplate); mCurrentTemplateIsShared = true; Reload(); } } mChangingTemplate = false; } /// <summary> /// Handles the Undo.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Undo_Click(object sender, EventArgs e) { PerformUndo(); } /// <summary> /// Handles the UpdateHeaderIds.Click event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateHeaderIds_Click(object sender, EventArgs e) { UpdateHeaderIdsInOrderColumn(); } /// <summary> /// Puts the header IDs in order if they are available. /// </summary> private void UpdateHeaderIdsInOrderColumn() { //Only do this if the "Header IDs in Order" column is in the grid. if (MainGrid.Cols.IndexOf("Header IDs in Order") > 0) { MainGrid.BeginUpdate(); //mainGrid.AutoResize = false; MainGrid.Redraw = false; string channel = channels.SelectedItem.ToString(); DateTime scheduleDate = headers.Value; OpenProxy(); try { for (int i = 1; i < MainGrid.Rows.Count; i++) { int id = Convert.ToInt32(MainGrid.GetData(i, "ID")); string headerIds = mProxy.GetHeaderIds(id, channel, scheduleDate); if (!String.IsNullOrEmpty(headerIds)) MainGrid.SetData(i, MainGrid.Cols["Header IDs in Order"].Index, headerIds); } } catch (Exception e) { Logging.Log(e, "Clipboard", "UpdateHeaderIdsInOrderColumn"); } finally { CloseProxy(); MainGrid.Redraw = true; //mainGrid.AutoResize = true; MainGrid.EndUpdate(); } MainGrid.Refresh(); } } /// <summary> /// Updates the progress bar during data load. /// </summary> /// <param name="total">The total number of records to load.</param> /// <param name="current">The number of records loaded so far.</param> private void UpdateProgressBar(int total, int current) { if (loadProgress.InvokeRequired) loadProgress.BeginInvoke(new Action(() => { loadProgress.TotalValue = total; loadProgress.PercentValue = (current * 100) / total; })); else { loadProgress.TotalValue = total; loadProgress.PercentValue = (current * 100) / total; } } /// <summary> /// Opens the selected media file. /// </summary> /// <param name="rowIndex">The row containing the clicked "View Media" button.</param> private void ViewMedia(int rowIndex) { int id = Convert.ToInt32(MainGrid[rowIndex, "ID"]); if (mViewMedia == null || mViewMedia.IsDisposed) mViewMedia = new ViewMediaForm(((SkinnableFormBase)mParent).Parameters, (SkinnableFormBase)mParent, id); //The View Media form might be disposed if there the asset ID has an associated video file that is already opened. if (!mViewMedia.IsDisposed) mViewMedia.Show(); } #endregion } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.Data.Cursors; using gView.Framework.Geometry; using gView.Framework.Network; using gView.Framework.system; using gView.Framework.UI; using gView.Framework.UI.Dialogs; using gView.Framework.UI.Events; using gView.Plugins.Network.Graphic; using System.Threading.Tasks; namespace gView.Plugins.Network { [RegisterPlugInAttribute("158C5F28-B987-4d16-8C9D-A1FC6E70EB56")] public class TraceNetwork : ITool { private IMapDocument _doc = null; private Module _module = null; #region ITool Member public string Name { get { return "Trace Network"; } } public bool Enabled { get { if (_module != null && _module.SelectedNetworkTracer != null) { return _module.SelectedNetworkTracer.CanTrace(TracerInput()); } return false; } } public string ToolTip { get { return "Trace Network"; } } public ToolType toolType { get { return ToolType.command; } } public object Image { get { return global::gView.Win.Plugins.Network.Properties.Resources.path3; } } public void OnCreate(object hook) { if (hook is IMapDocument) { _doc = (IMapDocument)hook; _module = Module.GetModule(_doc); } } async public Task<bool> OnEvent(object MapEvent) { if (_module != null && _module.SelectedNetworkTracer != null) { if (_module.SelectedNetworkTracer is INetworkTracerProperties && await ((INetworkTracerProperties)_module.SelectedNetworkTracer).NetworkTracerProperties(_module.SelectedNetworkFeatureClass, TracerInput()) != null) { FormTracerProperties dlg = new FormTracerProperties( await ((INetworkTracerProperties)_module.SelectedNetworkTracer).NetworkTracerProperties(_module.SelectedNetworkFeatureClass, TracerInput())); if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return false; } } if (_module.SelectedNetworkTracer is IProgressReporterEvent) { NetworkProgressReporter reporter = new NetworkProgressReporter(_doc); FormTaskProgress dlg = new FormTaskProgress(); dlg.ShowProgressDialog(reporter, this.Trace(reporter)); } else { await Trace(null); } ((MapEvent)MapEvent).drawPhase = DrawPhase.Graphics; ((MapEvent)MapEvent).refreshMap = true; } return true; } #endregion async private Task Trace(object arg) { NetworkProgressReporter reporter = arg as NetworkProgressReporter; if (_doc == null || _module == null) { return; } if (reporter != null && _module.SelectedNetworkTracer is IProgressReporterEvent) { ((IProgressReporterEvent)_module.SelectedNetworkTracer).ReportProgress += reporter.FireProgressReporter; } NetworkTracerOutputCollection outputCollection = await _module.SelectedNetworkTracer.Trace( _module.SelectedNetworkFeatureClass, TracerInput(), reporter != null ? reporter.CancelTracker : null); IDisplay display = (IDisplay)_doc.FocusMap; _module.RemoveAllNetworkGraphicElements(display); if (outputCollection != null) { foreach (INetworkTracerOutput output in outputCollection) { if (output is NetworkEdgeCollectionOutput) { IFeatureCursor cursor = await _module.NetworkPathEdges((NetworkEdgeCollectionOutput)output); if (cursor == null) { return; } IFeature feature; while ((feature = await cursor.NextFeature()) != null) { if (!(feature.Shape is IPolyline)) { continue; } display.GraphicsContainer.Elements.Add(new GraphicNetworkPathEdge((IPolyline)feature.Shape)); } } else if (output is NetworkPolylineOutput) { display.GraphicsContainer.Elements.Add(new GraphicNetworkPathEdge(((NetworkPolylineOutput)output).Polyline)); } else if (output is NetworkFlagOutput) { NetworkFlagOutput flag = (NetworkFlagOutput)output; string text = flag.UserData != null ? flag.UserData.ToString() : "Flag"; display.GraphicsContainer.Elements.Add(new GraphicFlagPoint(flag.Location, text)); } } } } private NetworkTracerInputCollection TracerInput() { if (_module == null) { return null; } NetworkTracerInputCollection input = new NetworkTracerInputCollection(); if (_module.StartNodeIndex >= 0) { input.Add(new NetworkSourceInput(_module.StartNodeIndex)); } if (_module.EndNodeIndex >= 0) { input.Add(new NetworkSinkInput(_module.EndNodeIndex)); } if (_module.GraphWeight != null) { input.Add(new NetworkWeighInput(_module.GraphWeight, _module.WeightApplying)); } if (_module.StartEdgeIndex >= 0) { input.Add(new NetworkSourceEdgeInput(_module.StartEdgeIndex, _module.StartPoint)); } return input; } } }
using System; using System.Web.UI; using System.Configuration; using System.Data.SqlClient; namespace OfoTest2 { public partial class Contact : Page { protected void Button1_Click(object sender, EventArgs e) { String strConnString = ConfigurationManager.ConnectionStrings["OFOConnectionString"].ConnectionString; SqlConnection con = new SqlConnection(strConnString); con.Open(); string Fname = String.Format("{0}", Request.Form["fname"]); string sname = String.Format("{0}", Request.Form["sname"]); string role = String.Format("{0}", Request.Form["role"]); string company = String.Format("{0}", Request.Form["company"]); string email = String.Format("{0}", Request.Form["email"]); string seta = String.Format("{0}", Request.Form["seta"]); SqlCommand cmd = new SqlCommand("insert into contact values(@FirstName,@Surname,@Role,@Sector,@EmailAddress,@Company)", con); cmd.Parameters.AddWithValue("FirstName", Fname); cmd.Parameters.AddWithValue("Surname", sname); cmd.Parameters.AddWithValue("Role", role); cmd.Parameters.AddWithValue("Company", company); cmd.Parameters.AddWithValue("Sector", seta); cmd.Parameters.AddWithValue("EmailAddress", email); cmd.ExecuteNonQuery(); Submit.Visible = false; returntohometext.Visible = true; returntohome.Visible = true; } protected void RetToHome(object sender, EventArgs e) { Response.Redirect("Default.aspx"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace ANAGRAMME { class Program { public static void lire(ref string ch1,ref string ch2) { do { Console.WriteLine("Tapez votre premier mot "); ch1 = Console.ReadLine(); Console.WriteLine("Tapez votre deuxième mot "); ch2 = Console.ReadLine(); } while (string.IsNullOrEmpty(ch1) || string.IsNullOrEmpty(ch2) || ch2 == ch1); } public static bool verifier(string ch1, string ch2) { return ch1.All(x => ch2.Contains(x)) && ch2.All(x => ch1.Contains(x)); } static void Main(string[] args) { string mot1 = "", mot2 = ""; lire(ref mot1, ref mot2); if (verifier(mot1, mot2)){ Console.WriteLine($"{mot2} est une anagramme de {mot1}"); } else { Console.WriteLine($"{mot2} n'est pas une anagramme de {mot1}"); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task7_Advertisement_Message { public class task7_Advertisement_Message { public static void Main() { var phrases = File.ReadAllLines("phrases.txt"); var events = File.ReadAllLines("events.txt"); var authors = File.ReadAllLines("authors.txt"); var cities = File.ReadAllLines("cities.txt"); var massege = new Random(); var n = int.Parse(Console.ReadLine()); var adds = new List<string>(); for (int i = 0; i < n; i++) { var phrase = PickRandomElementFromArray(phrases, massege); var @event = PickRandomElementFromArray(events, massege); var author = PickRandomElementFromArray(authors, massege); var city = PickRandomElementFromArray(cities, massege); adds.Add($"{phrase} {@event} {author} - {city}"); } File.WriteAllLines("output.txt", adds); } public static string PickRandomElementFromArray(string[] arr, Random massege) { var randomValidIndex = massege.Next(0, arr.Length - 1); var randomElement = arr[randomValidIndex]; return randomElement; } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pgh.Auth.Model.Migrations { public partial class V10092019 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "Applications", keyColumn: "AppId", keyValue: new Guid("65e582f2-e513-4164-ae8a-9f2aed435222")); migrationBuilder.DeleteData( table: "Applications", keyColumn: "AppId", keyValue: new Guid("ea445968-9398-4058-bd2c-23293428765e")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("0d0cda2c-826c-445f-b52b-4aacb438e1e8")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("380117cd-58c7-4a53-a290-87e5b431cfde")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("4f47cd97-e586-471a-b428-d43c84141573")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("5bdadf51-9c3d-4964-9733-7378e469cf44")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("ca33b4da-a217-43e5-aefc-22c9b73a0d89")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("48da03cd-03fc-42df-85d2-cdfb8aa3ac8f")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("e616fca0-d7f3-4288-85dc-7f30d55f36f2")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("0afb105d-5e9a-4306-934d-72f78f5d2768")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("2b6db602-4730-4c15-925a-8ca338a70e6b")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("48fa45ce-d66a-4e16-938c-87470f944363")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("6e9544e5-1b31-44f1-995f-aebe22b9c6dd")); migrationBuilder.InsertData( table: "Applications", columns: new[] { "AppId", "AppCode", "AppDescription", "AppDisplayName", "AppName", "AppState" }, values: new object[,] { { new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4"), "0000", "Cette application gérer l'authentification et des permissions des différents applications.", "Gestion de l'authentification des applications", "AuthApp", true }, { new Guid("f39a767f-fb5d-490a-b3a3-6903eeb21638"), "0001", "Cette application gérer le processus d'analyse des échantillons par le labo Dick.", "Gestion de laboratoire Dick", "LaboDickAgro", true }, { new Guid("0a70dd20-305c-4e2b-b84e-704d827d2bfb"), "0013", "Mise a jour de l'ancienne application Laboratoir Dick.", "Gestion de laboratoire Dick Elevage", "LaboDickElevage", true } }); migrationBuilder.InsertData( table: "Permissions", columns: new[] { "PermId", "PermDescription", "PermDisplayName", "PermName", "PermState" }, values: new object[,] { { new Guid("55246a69-70f1-484c-b454-057040cb408d"), "Users Will Have Permission to Manage personal views.", "Manage personal views", "ManagePersonalViews", true }, { new Guid("0c3fb9e5-9703-47ca-8290-e0ee0a6bf704"), "Users Will Have Permission to view pages.", "View Pages", "ViewPages", true }, { new Guid("b6cc17d7-8885-474d-8397-08dd594a43d9"), "Users Will Have Permission to create groups.", "Create Groups", "CreateGroups", true }, { new Guid("ddfea423-43ab-460f-aa82-75e9e56c6bd3"), "Users Will Have Permission to view application pages.", "View application pages", "ViewApplicationPages", true }, { new Guid("ea418322-d667-4742-8b47-79e0bcd9c43c"), "Users Will Have Permission to Delete versions.", "Delete Versions", "DeleteVersions", true }, { new Guid("d23cdb47-bc5f-4d55-b1a8-fbf033a11c16"), "Users Will Have Permission to edit users personal information.", "Edit user's personal information", "EditUserPersonalInformation", true }, { new Guid("81a7c86b-65de-4b7c-a608-b1d904f499b6"), "Users Will Have Permission to approve items.", "Approve Items", "ApproveItems", true }, { new Guid("e2855fd2-6713-420a-96c6-b31ba50a6f89"), "Users Will Have Permission to View Items.", "View Items", "ViewItems", true }, { new Guid("b781e222-af1d-4abf-af36-96c507815829"), "Users Will Have Permission to delete Elements.", "Delete Items", "DeleteItems", true }, { new Guid("c68d7a74-7e29-4b24-90a2-5f06f9e40048"), "Users Will Have Permission to edit Items.", "Edit Items", "EditItems", true }, { new Guid("13377610-d71b-4c3a-a7a1-feed4f21fb15"), "Users Will Have the permission to add items", "Add Items", "AddItems", true }, { new Guid("20ead205-14ac-4a14-adce-2d69df261801"), "Users Will Have Permission to show versions.", "Show Versions", "ShowVersions", true } }); migrationBuilder.InsertData( table: "Roles", columns: new[] { "RoleId", "RoleDescription", "RoleDisplayName", "RoleName", "RoleState" }, values: new object[,] { { new Guid("aad23d91-72f7-46da-a5b6-ea8a6d6fc526"), "Restricted reading Default Groupe", "Restricted reading Groupe", "Restricted reading", true }, { new Guid("378ddc6d-f019-4103-a072-1a2f0da53094"), "Approval Default Groupe", "Approval Groupe", "Approval", true }, { new Guid("319d93fe-47f0-49cf-a4c6-f358fe88354c"), "Display Only Default Groupe", "Display Only Groupe", "DisplayOnly", true }, { new Guid("5cb17690-b876-46d9-97a5-9d3ef9c6295f"), "Limited Access Default Groupe", "Limited Access", "LimitedAccess", true }, { new Guid("ef49422b-0246-464b-8bae-a6f5408a82b1"), "Collaboration Default Groupe", "Collaboration Groupe", "Collaboration", true }, { new Guid("a59d6f95-74a2-4525-ad61-f6ab6e626ea3"), "Editors Groupe Default Groupe", "Editors Groupe", "Editors", true }, { new Guid("870057fd-94b0-4b02-9749-d058ac5fdc03"), "Design Groupe Default Groupe", "Design Groupe", "Design", true }, { new Guid("5acd82a4-dd50-46ed-9a82-7a735663e0df"), "Total Control Default Groupe", "Total Control", "TotalControl", true }, { new Guid("663f67d9-599c-42c3-b818-0c939c5e14c1"), "Readers Groupe Default Groupe", "Readers Groupe", "Readers", true } }); migrationBuilder.InsertData( table: "User", columns: new[] { "UsersId", "FkUsersId", "UsersBirthDate", "UsersCode", "UsersDateLeave", "UsersFilialeCode", "UsersFilialeName", "UsersGenderCode", "UsersJoinDate", "UsersLastName", "UsersMail", "UsersMailIntern", "UsersName", "UsersPersonalNumber", "UsersPhoneNumber", "UsersPosteName", "UsersState" }, values: new object[,] { { new Guid("ac1f391b-da75-4d08-8222-26969a35ce58"), null, new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2170), "00000002", new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2171), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2171), "Test", "User1@poulina.com", "User1@poulina.com", "User1", "63524163", "63524141", "User1 Poste", false }, { new Guid("d360d9d1-540d-4915-8637-a58990c0eff2"), null, new DateTime(2019, 9, 10, 17, 56, 9, 134, DateTimeKind.Local).AddTicks(7439), "00000000", new DateTime(2019, 9, 10, 17, 56, 9, 136, DateTimeKind.Local).AddTicks(3466), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 10, 17, 56, 9, 136, DateTimeKind.Local).AddTicks(4362), "Admin", "Admin@poulina.com", "Admin@poulina.com", "Admin", "63524163", "63524141", "Admin Poste", false }, { new Guid("1eb21829-ebee-410a-a3b2-6237bf8c24c9"), null, new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2110), "00000001", new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2119), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2123), "SupAdmin", "SupAdmin@poulina.com", "SupAdmin@poulina.com", "SupAdmin", "63524163", "63524141", "SupAdmin Poste", false }, { new Guid("da4a9814-7c71-4104-8447-cb778317db6c"), null, new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2204), "00000003", new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2204), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 10, 17, 56, 9, 137, DateTimeKind.Local).AddTicks(2205), "Test", "User2@poulina.com", "User2@poulina.com", "User2", "63524163", "63524141", "User2 Poste", false } }); migrationBuilder.InsertData( table: "Menus", columns: new[] { "MenuId", "FkAppId", "FkMenuId", "MenuDescription", "MenuDisplayName", "MenuName", "MenuState", "MenuUrl" }, values: new object[,] { { new Guid("80795f57-7878-4ba4-9acb-ce0ee1a1e87e"), new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4"), null, "User setup menu.", "Users", "AuthUsers", true, "Http://srvapp/authusers" }, { new Guid("52010bc1-528f-4ea3-b978-dbb5956cd88c"), new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4"), null, "Permissions setup menu.", "Permissions", "AuthPermissions", true, "Http://srvapp/authpermissions" }, { new Guid("19b3c4d6-bd51-441f-8455-0b19d164a7dd"), new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4"), null, "Roles setup menu.", "Roles", "AuthRoles", true, "Http://srvapp/authroles" }, { new Guid("b01a7bf8-036a-4ff2-97f1-5a71f1eb35c8"), new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4"), null, "Applications setup menu.", "Applications", "AuthApplications", true, "Http://srvapp/authappications" }, { new Guid("300b625d-4be5-455e-bab8-b6c0dd29540c"), new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4"), null, "Menus setup menu.", "Menus", "AuthMenus", true, "Http://srvapp/authmenus" } }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "Applications", keyColumn: "AppId", keyValue: new Guid("0a70dd20-305c-4e2b-b84e-704d827d2bfb")); migrationBuilder.DeleteData( table: "Applications", keyColumn: "AppId", keyValue: new Guid("f39a767f-fb5d-490a-b3a3-6903eeb21638")); migrationBuilder.DeleteData( table: "Menus", keyColumn: "MenuId", keyValue: new Guid("19b3c4d6-bd51-441f-8455-0b19d164a7dd")); migrationBuilder.DeleteData( table: "Menus", keyColumn: "MenuId", keyValue: new Guid("300b625d-4be5-455e-bab8-b6c0dd29540c")); migrationBuilder.DeleteData( table: "Menus", keyColumn: "MenuId", keyValue: new Guid("52010bc1-528f-4ea3-b978-dbb5956cd88c")); migrationBuilder.DeleteData( table: "Menus", keyColumn: "MenuId", keyValue: new Guid("80795f57-7878-4ba4-9acb-ce0ee1a1e87e")); migrationBuilder.DeleteData( table: "Menus", keyColumn: "MenuId", keyValue: new Guid("b01a7bf8-036a-4ff2-97f1-5a71f1eb35c8")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("0c3fb9e5-9703-47ca-8290-e0ee0a6bf704")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("13377610-d71b-4c3a-a7a1-feed4f21fb15")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("20ead205-14ac-4a14-adce-2d69df261801")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("55246a69-70f1-484c-b454-057040cb408d")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("81a7c86b-65de-4b7c-a608-b1d904f499b6")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("b6cc17d7-8885-474d-8397-08dd594a43d9")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("b781e222-af1d-4abf-af36-96c507815829")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("c68d7a74-7e29-4b24-90a2-5f06f9e40048")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("d23cdb47-bc5f-4d55-b1a8-fbf033a11c16")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("ddfea423-43ab-460f-aa82-75e9e56c6bd3")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("e2855fd2-6713-420a-96c6-b31ba50a6f89")); migrationBuilder.DeleteData( table: "Permissions", keyColumn: "PermId", keyValue: new Guid("ea418322-d667-4742-8b47-79e0bcd9c43c")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("319d93fe-47f0-49cf-a4c6-f358fe88354c")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("378ddc6d-f019-4103-a072-1a2f0da53094")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("5acd82a4-dd50-46ed-9a82-7a735663e0df")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("5cb17690-b876-46d9-97a5-9d3ef9c6295f")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("663f67d9-599c-42c3-b818-0c939c5e14c1")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("870057fd-94b0-4b02-9749-d058ac5fdc03")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("a59d6f95-74a2-4525-ad61-f6ab6e626ea3")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("aad23d91-72f7-46da-a5b6-ea8a6d6fc526")); migrationBuilder.DeleteData( table: "Roles", keyColumn: "RoleId", keyValue: new Guid("ef49422b-0246-464b-8bae-a6f5408a82b1")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("1eb21829-ebee-410a-a3b2-6237bf8c24c9")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("ac1f391b-da75-4d08-8222-26969a35ce58")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("d360d9d1-540d-4915-8637-a58990c0eff2")); migrationBuilder.DeleteData( table: "User", keyColumn: "UsersId", keyValue: new Guid("da4a9814-7c71-4104-8447-cb778317db6c")); migrationBuilder.DeleteData( table: "Applications", keyColumn: "AppId", keyValue: new Guid("fc5dcfbb-7f24-479c-922c-e8663bf5cab4")); migrationBuilder.InsertData( table: "Applications", columns: new[] { "AppId", "AppCode", "AppDescription", "AppDisplayName", "AppName", "AppState" }, values: new object[,] { { new Guid("65e582f2-e513-4164-ae8a-9f2aed435222"), "0012", "Cette application gérer le processus d'analyse des échantillons par le labo Dick", "Gestion de laboratoire Dick", "LaboDick", false }, { new Guid("ea445968-9398-4058-bd2c-23293428765e"), "0013", "Mise a jour de l'ancienne application Laboratoir Dick", "Gestion de laboratoire Dick V2", "LaboDick V2", false } }); migrationBuilder.InsertData( table: "Permissions", columns: new[] { "PermId", "PermDescription", "PermDisplayName", "PermName", "PermState" }, values: new object[,] { { new Guid("ca33b4da-a217-43e5-aefc-22c9b73a0d89"), "Users Will Have Read Permission.", "Affichage", "Read", true }, { new Guid("5bdadf51-9c3d-4964-9733-7378e469cf44"), "Users Will Have Create Permission.", "Creation", "Create", true }, { new Guid("4f47cd97-e586-471a-b428-d43c84141573"), "Users Will Have Update Permission.", "Mise à jour", "Update", true }, { new Guid("0d0cda2c-826c-445f-b52b-4aacb438e1e8"), "Users Will Have Delete Permission.", "Suppression", "Delete", true }, { new Guid("380117cd-58c7-4a53-a290-87e5b431cfde"), "Users Will Have Permission To View Reporting Pages.", "View Reporting", "ViewReporting", true } }); migrationBuilder.InsertData( table: "Roles", columns: new[] { "RoleId", "RoleDescription", "RoleDisplayName", "RoleName", "RoleState" }, values: new object[,] { { new Guid("48da03cd-03fc-42df-85d2-cdfb8aa3ac8f"), "Ce rôle vous permet de lire les données spécifique de l'application.", "Readers LaboDick", "Readers", true }, { new Guid("e616fca0-d7f3-4288-85dc-7f30d55f36f2"), "Ce rôle vous permet de Modifier les données spécifique de l'application.", "Editors LaboDick", "Editors", true } }); migrationBuilder.InsertData( table: "User", columns: new[] { "UsersId", "FkUsersId", "UsersBirthDate", "UsersCode", "UsersDateLeave", "UsersFilialeCode", "UsersFilialeName", "UsersGenderCode", "UsersJoinDate", "UsersLastName", "UsersMail", "UsersMailIntern", "UsersName", "UsersPersonalNumber", "UsersPhoneNumber", "UsersPosteName", "UsersState" }, values: new object[,] { { new Guid("2b6db602-4730-4c15-925a-8ca338a70e6b"), null, new DateTime(2019, 9, 6, 11, 37, 11, 818, DateTimeKind.Local).AddTicks(4528), "00000000", new DateTime(2019, 9, 6, 11, 37, 11, 821, DateTimeKind.Local).AddTicks(3282), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 6, 11, 37, 11, 821, DateTimeKind.Local).AddTicks(4305), "Admin", "Admin@poulina.com", "Admin@poulina.com", "Admin", "63524163", "63524141", "Admin Poste", false }, { new Guid("0afb105d-5e9a-4306-934d-72f78f5d2768"), null, new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3230), "00000001", new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3242), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3251), "SupAdmin", "SupAdmin@poulina.com", "SupAdmin@poulina.com", "SupAdmin", "63524163", "63524141", "SupAdmin Poste", false }, { new Guid("6e9544e5-1b31-44f1-995f-aebe22b9c6dd"), null, new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3320), "00000002", new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3323), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3324), "Test", "User1@poulina.com", "User1@poulina.com", "User1", "63524163", "63524141", "User1 Poste", false }, { new Guid("48fa45ce-d66a-4e16-938c-87470f944363"), null, new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3329), "00000003", new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3330), "DD01", "PoulinaGroupeHolding", "M", new DateTime(2019, 9, 6, 11, 37, 11, 822, DateTimeKind.Local).AddTicks(3331), "Test", "User2@poulina.com", "User2@poulina.com", "User2", "63524163", "63524141", "User2 Poste", false } }); } } }
using System; namespace LogFile.Generator.Core.Generator { public class DateTimeGenerator : IGenerator<DateTime> { private DateTime _myDate = DateTime.Today; public DateTime Generate(Random myRandom) { _myDate = _myDate.AddSeconds(myRandom.Next(0, 59)); return _myDate; } } }
using System; namespace iSukces.Code { public class AutoCodeSettings { public StaticMethodInfo GetUrlStringEncodeOrThrow() { var tmp = UrlStringEncode; if (tmp.IsEmpty) throw new Exception(nameof(UrlStringEncode) + " is empty"); return tmp; } public static AutoCodeSettings Default => InstanceHolder.DefaultInstance; /// <summary> /// Initialize this with /// AutoCodeSettings.Default.UrlStringEncode = new StaticMethodInfo( /// typeof(System.Net.WebUtility), /// nameof(System.Net.WebUtility.UrlEncode)); /// </summary> public StaticMethodInfo UrlStringEncode { get; set; } private class InstanceHolder { public static readonly AutoCodeSettings DefaultInstance = new AutoCodeSettings(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Images.Data; namespace Homework_6_5.Models { public class LinkViewModel { public Image Image { get; set; } public string HostName { get; set; } } }
using Microsoft.SharePoint; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.Common.Util; using BELCORP.GestorDocumental.DA.Comun; using BELCORP.GestorDocumental.DA.Sharepoint; using BELCORP.GestorDocumental.BE.Contratos; namespace BELCORP.GestorDocumental.BL.Contratos { public class EmpresasBelcorpContrataBL { #region Singleton private static volatile EmpresasBelcorpContrataBL _instance = null; private static object lockAccessObject = new Object(); public static EmpresasBelcorpContrataBL Instance { get { if (_instance == null) { lock (lockAccessObject) { _instance = new EmpresasBelcorpContrataBL(); } } return _instance; } } /// <summary> /// Contructor por defecto /// </summary> private EmpresasBelcorpContrataBL() { } #endregion public List<EmpresasBelcorpContrataBE> ObtenerListaEmpresasContrata(string URL_Sitio) { List<EmpresasBelcorpContrataBE> lst = new List<EmpresasBelcorpContrataBE>(); EmpresasBelcorpContrataBE oItem = null; SPListItemCollection splic = SharePointHelper.ObtenerInformacionLista( URL_Sitio, ListasGestionContratos.EmpresasBelcorpContrata); if (splic != null) { foreach (SPListItem splitem in splic) { oItem = new EmpresasBelcorpContrataBE(); oItem.Id = splitem.ID; oItem.Title = splitem.Title; lst.Add(oItem); } } lst = lst.OrderBy(o => o.Title).ToList(); return lst; } public List<EmpresasBelcorpContrataBE> ObtenerListaEmpresasContrataXIdPais(string URL_Sitio, string idPais) { List<EmpresasBelcorpContrataBE> lst = new List<EmpresasBelcorpContrataBE>(); EmpresasBelcorpContrataBE oItem = null; using (SPSite site = new SPSite(URL_Sitio)) { SPWeb web = site.OpenWeb(); SPList lista = web.Lists[ListasGestionContratos.EmpresasBelcorpContrata]; SPQuery spQuery = new SPQuery(); spQuery.RowLimit = 100; spQuery.Query = "<Where>" + "<" + SharePointHelper.OperatorType.Equal + ">" + "<FieldRef Name='" + "CodPais" + "' LookupId='TRUE'/>" + "<Value Type='" + SharePointHelper.FieldTypeCAML.Lookup_ + "'>" + idPais + "</Value>" + "</" + SharePointHelper.OperatorType.Equal + ">" + "</Where>"; SPListItemCollection itemCollection = lista.GetItems(spQuery); if (itemCollection != null && itemCollection.Count > 0) { foreach (SPListItem itemEmpresaBelcorp in itemCollection) { oItem = new EmpresasBelcorpContrataBE(); oItem.Id = itemEmpresaBelcorp.ID; oItem.Title = itemEmpresaBelcorp.Title; //oItem.IdPais = Convert.ToInt32(itemEmpresaBelcorp["CodPais"]); lst.Add(oItem); } } } lst = lst.OrderBy(o => o.Title).ToList(); return lst; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Gap.NetFest.DataAccess.DTO { [Table("Customers")] public class Customers { [Key] [Column("id")] public string Id { get; set; } [Column("first_name")] public string Name { get; set; } [Column("last_name")] public string LastName { get; set; } public ICollection<Invoices> Invoices { get; set; } } }
using XH.Infrastructure.Command; namespace XH.Commands.Tenants { public abstract class CreateOrUpdateTenantCommand : CommandBase { public string TenantName { get; set; } public bool IsActive { get; set; } public string Host { get; set; } public string Name { get; set; } } }
namespace DChild.Gameplay.Player { public interface IPlayerSkillEnabler { void EnableSkill<T>(bool value) where T : IPlayerSkill; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerController : MonoBehaviour { /// <summary> /// This is the object that holds all the options the players share. /// </summary> public PlayerOptions po; /// <summary> /// This is the object that keeps the game Loop and score under control. /// </summary> public GameManager gm; /// <summary> /// colliders that detect if you successfully kicked the other player. /// </summary> public Collider2D leftKickCollider, rightKickController; /// <summary> /// your body. get kicked there and you go flying /// </summary> public Collider2D bodyCollider; /// <summary> /// a reference to the other players' controller. /// </summary> public Collider2D OpponentBodyCollider; /// <summary> /// a reference to your opponents script /// </summary> public PlayerController opponent; public Vector2 velocity; /// <summary> /// the current number of in-air jumps you have /// </summary> int currentAirJumps; /// <summary> /// reference to own rigidbody /// </summary> public Rigidbody2D rb; /// <summary> /// Which keys control your dude. /// </summary> public KeyCode left, right, action; /// <summary> /// status booleans /// </summary> public bool stunned, canKick; /// <summary> /// Indicator to where the player is kicking. /// </summary> public GameObject leftKickWind, rightKickWind; // Use this for initialization void Start () { po = GameObject.Find("GameOptions").GetComponent<PlayerOptions>(); currentAirJumps = po.airJumps; stunned = false; canKick = true; } public Text KickCoolDownText; /// <summary> /// This gets called once the other player manages to kick you. /// </summary> /// <param name="opponentPosition">Vector2 other players position</param> public void kickEvent(Vector2 opponentPosition){ Debug.Log("shit me, "+name+", got kicked"); Vector2 kickDirection = (Vector2)this.transform.position - opponentPosition; rb.AddForce(kickDirection * po.kickForce); stunned = true; StartCoroutine("Stunned"); } /// <summary> /// Start cooldown until you are not stunned anymore. /// </summary> /// <returns></returns> IEnumerator Stunned() { yield return new WaitForSeconds(po.stunDuration); stunned = false; } /// <summary> /// Start the cooldown to be able to kick again. /// </summary> /// <returns></returns> IEnumerator KickCoolDown(){ KickCoolDownText.gameObject.SetActive(true); canKick = false; yield return new WaitForSeconds(po.kickCoolDown); KickCoolDownText.gameObject.SetActive(false); canKick = true; } /// <summary> /// Reset the number of air-jumps this player has left. /// </summary> /// <param name="coll">Collision event.</param> void OnCollisionEnter2D(Collision2D coll){ if( po.groundColliders.Contains(coll.collider) ){ currentAirJumps = po.airJumps; } } /// <summary> /// JUMP! /// </summary> void jump(){ if(currentAirJumps > 0){ currentAirJumps --; rb.AddForce(new Vector2(0, po.jumpHeight)); } } /// <summary> /// notify the playerOptions that this player has scored. /// </summary> public void Score(){ gm.SendMessage("Score", this.name); } /// <summary> /// get this player off-screen for some time. /// </summary> /// <returns></returns> IEnumerator resetPlayer(){ Debug.Log("resetualizing player"); //place player away and don't simulate. this.transform.position = new Vector3(0, 100, 0); rb.bodyType = RigidbodyType2D.Static; //wait for the respawn timer to pass. yield return new WaitForSeconds(po.reviveTimer); //place player randomly on map and simulate. this.transform.position = po.playerRespawns[Random.Range(0, po.playerRespawns.Length-1)]; rb.bodyType = RigidbodyType2D.Dynamic; } /// <summary> /// how long a kick should be /// </summary> float kickWindDuration = 0.5f; IEnumerator rightKick(){ rightKickWind.SetActive(true); yield return new WaitForSeconds(kickWindDuration); rightKickWind.SetActive(false); } IEnumerator leftKick(){ leftKickWind.SetActive(true); yield return new WaitForSeconds(kickWindDuration); leftKickWind.SetActive(false); } // Update is called once per frame float currentKickCooldown; void Update () { velocity = rb.velocity; if(this.transform.position.y < po.waterLevel){ StartCoroutine("resetPlayer"); opponent.SendMessage("Score"); } currentKickCooldown -= Time.deltaTime; if(KickCoolDownText.IsActive()){ float x = currentKickCooldown-(currentKickCooldown%0.1f); KickCoolDownText.text = ""+x; } // inputs shouldn't register if the player is stunned if(!stunned && !gm.gameOver){ // the action key is the kick/jump key. if(Input.GetKeyDown(action)){ //prioritize kicks over jumping. if(leftKickCollider.IsTouching(OpponentBodyCollider) || rightKickController.IsTouching(OpponentBodyCollider)){ //TODO: decide that if you cant kick, you should jump instead. if(canKick){ canKick = false; StartCoroutine("KickCoolDown"); currentKickCooldown = po.kickCoolDown; if(opponent.transform.position.x < transform.position.x){ //start left kickWind StartCoroutine("leftKick"); } else { //start Right kickwind StartCoroutine("rightKick"); } opponent.SendMessage("kickEvent", (Vector2)this.transform.position); } else { Debug.Log("me, " + name + " Cant kick"); } } // the player can't kick. check if he can jump instead. else { jump(); } } // if(Input.GetKey(left)){ if(this.velocity.x < po.runSpeed){ rb.AddForce(new Vector2(-po.runSpeed, 0)); } } if(Input.GetKey(right)){ if(this.velocity.x < po.runSpeed){ rb.AddForce(new Vector2(po.runSpeed, 0)); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class cllBack : MonoBehaviour { // public GameObject cnvas; public GameObject link; public GameObject gob; public robotSynthesis cRS; public GameObject txtBox; public GameObject jCylinder; public bool addAxes = false; int numJoints = 1; public bool jointInformation = false; public string jointName; public void addJoint() { Debug.Log("adddddd Joiiiintttt"); addAxes = true; numJoints = numJoints + 1; //txtBox.GetComponent<Text>().text = "Number of Joints: " + numJoints.ToString(); // add an axes between the end-effector axis and the last joint axis var newJointAxis = Instantiate(gob, (cRS.jointAxes[cRS.jointAxes.Count-1].transform.position + cRS.jointAxes[cRS.jointAxes.Count - 2].transform.position) /2, Quaternion.identity); cRS.jointAxes.Insert(cRS.jointAxes.Count - 1, newJointAxis); // add two cylinders var newJointCylinder = Instantiate(jCylinder, newJointAxis.transform.position, Quaternion.identity); var newJointCylinderp = Instantiate(jCylinder, newJointAxis.transform.position, Quaternion.identity); GameObject[] newJointCylinderObjects = new GameObject[2]; newJointCylinderObjects[0] = newJointCylinder; newJointCylinderObjects[1] = newJointCylinderp; cRS.jointCylinders.Add(newJointCylinderObjects); var newLink = Instantiate(link, Vector3.up, Quaternion.identity); cRS.links.Add(newLink); /* var newJointText = Instantiate(cnvas.transform.GetChild(0).gameObject, new Vector3(cnvas.transform.GetChild(0).transform.position.x, cRS.jointTexts[numJoints-2].transform.position.y-35, cnvas.transform.GetChild(0).transform.position.z), Quaternion.identity); newJointText.transform.SetParent(cnvas.transform); newJointText.GetComponent<Text>().text = "Joint " + numJoints; newJointText.name = "Joint" + numJoints; cRS.jointTexts.Add(newJointText);*/ } public void jointInfo() { jointInformation = true; jointName = EventSystem.current.currentSelectedGameObject.name; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; namespace KartSystem { public class DocStatus:SimpleDbEntity { public override string FriendlyName { get { return "Статус документа"; } } public string Name { get; set; } } }
using System.ComponentModel; using System.IO; using System.Linq; using Spectre.Console; using Spectre.Console.Cli; namespace WitsmlExplorer.Console.QueryCommands { public class GetQuerySettings : CommandSettings { private readonly string[] validReturnElements = {"requested", "all", "id-only", "header-only", "data-only", "station-location-only", "latest-change-only"}; [CommandArgument(0, "<PATH_TO_QUERY_FILE>")] [Description("Path to query file in XML format")] public string QueryFile { get; init; } [CommandOption("--returnElements")] [Description("Indicates which elements and attributes are requested to be returned in addition to data-object selection items (requested(default)|all|id-only|header-only|data-only|station-location-only|latest-change-only)")] [DefaultValue("requested")] public string ReturnElements { get; init; } [CommandOption("--maxReturnNodes")] [Description("Max number of data nodes to return. Must be a whole number greater than zero, if provided")] [DefaultValue("")] public int? MaxReturnNodes { get; init; } public override ValidationResult Validate() { var queryPath = Path.Combine(Directory.GetCurrentDirectory(), QueryFile); if (!File.Exists(queryPath)) return ValidationResult.Error($"Could not find query file: {queryPath}"); if (!validReturnElements.Contains(ReturnElements)) return ValidationResult.Error($"Invalid value for returnElements ({ReturnElements})"); if (MaxReturnNodes is < 1) return ValidationResult.Error("MaxReturnNodes must be a whole number greater than zero"); return ValidationResult.Success(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using CapaEntidades; namespace CapaNegocio.Interfaces { interface iPais { DataSet Listar(); bool Agregar(PaisEntidad pais); bool Eliminar(string codPais); bool Actualizar(PaisEntidad pais); DataSet Buscar(string codPais); } }
using ArkSavegameToolkitNet.Property; using ArkSavegameToolkitNet.Types; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArkSavegameToolkitNet { [JsonObject(MemberSerialization.OptIn)] public class ArkTribe : IGameObjectContainer, IPropertyContainer { [JsonProperty] public IList<GameObject> Objects { get; private set; } public IDictionary<ArkName, IProperty> Properties { get { return Tribe.Properties; } set { Tribe.Properties = value; } } public GameObject Tribe { get; set; } public int TribeVersion { get; set; } public DateTime SaveTime { get; set; } private ArkNameCache _arkNameCache; private ArkNameTree _exclusivePropertyNameTree; private string _fileName; public ArkTribe() { Objects = new List<GameObject>(); _arkNameCache = new ArkNameCache(); } public ArkTribe(string fileName, ArkNameCache arkNameCache = null, ArkNameTree exclusivePropertyNameTree = null) : this() { _fileName = fileName; if (arkNameCache != null) _arkNameCache = arkNameCache; _exclusivePropertyNameTree = exclusivePropertyNameTree; var fi = new FileInfo(fileName); SaveTime = fi.LastWriteTimeUtc; var size = fi.Length; if (size == 0) return; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, null, 0L, MemoryMappedFileAccess.Read)) { using (MemoryMappedViewAccessor va = mmf.CreateViewAccessor(0L, 0L, MemoryMappedFileAccess.Read)) { ArkArchive archive = new ArkArchive(va, size, _arkNameCache, exclusivePropertyNameTree: _exclusivePropertyNameTree); readBinary(archive); } } } public virtual void readBinary(ArkArchive archive) { TribeVersion = archive.GetInt(); if (TribeVersion != 1) throw new System.NotSupportedException($@"Unknown Tribe Version {TribeVersion} in ""{_fileName}""" + (TribeVersion == 0 ? " (possibly corrupt)" : "")); var tribesCount = archive.GetInt(); for (int i = 0; i < tribesCount; i++) { Objects.Add(new GameObject(archive, _arkNameCache)); } for (int i = 0; i < tribesCount; i++) { GameObject obj = Objects[i]; if (obj.ClassName.Token.Equals("PrimalTribeData")) Tribe = obj; obj.loadProperties(archive, i < tribesCount - 1 ? Objects[i + 1] : null, 0); } } } }
using System; using System.Globalization; using System.Text.RegularExpressions; using EnsureThat; using EnsureThat.Internals; using Xunit; #pragma warning disable 618 namespace UnitTests { public class EnsureStringParamTests : UnitTestBase { private static void AssertIsNotNull(params Action[] actions) => ShouldThrow<ArgumentNullException>(ExceptionMessages.Common_IsNotNull_Failed, actions); private static void AssertIsNotEmpty(params Action[] actions) => ShouldThrow<ArgumentException>(ExceptionMessages.Strings_IsNotEmpty_Failed, actions); private static void AssertIsNotNullOrEmpty(params Action[] actions) => ShouldThrow<ArgumentException>(ExceptionMessages.Strings_IsNotNullOrEmpty_Failed, actions); private static void AssertIsNotNullOrWhiteSpace(params Action[] actions) => ShouldThrow<ArgumentException>(ExceptionMessages.Strings_IsNotNullOrWhiteSpace_Failed, actions); [Fact] public void IsNotNull_WhenStringIsNull_ThrowsArgumentNullException() { string value = null; AssertIsNotNull( () => Ensure.String.IsNotNull(value, ParamName), () => EnsureArg.IsNotNull(value, ParamName), () => Ensure.That(value, ParamName).IsNotNull()); } [Fact] public void IsNotNull_WhenStringIsNotNull_It_should_not_throw() { var value = string.Empty; ShouldNotThrow( () => Ensure.String.IsNotNull(value, ParamName), () => EnsureArg.IsNotNull(value, ParamName), () => Ensure.That(value, ParamName).IsNotNull()); } [Fact] public void IsNotNullOrEmpty_WhenStringIsNull_ThrowsArgumentNullException() { string value = null; AssertIsNotNull( () => Ensure.String.IsNotNullOrEmpty(value, ParamName), () => EnsureArg.IsNotNullOrEmpty(value, ParamName), () => Ensure.That(value, ParamName).IsNotNullOrEmpty()); } [Fact] public void IsNotNullOrEmpty_WhenStringIsEmpty_ThrowsArgumentException() { var value = string.Empty; AssertIsNotNullOrEmpty( () => Ensure.String.IsNotNullOrEmpty(value, ParamName), () => EnsureArg.IsNotNullOrEmpty(value, ParamName), () => Ensure.That(value, ParamName).IsNotNullOrEmpty()); } [Fact] public void IsNotNullOrEmpty_WhenStringIsNotNullOrEmpty_It_should_not_throw() { var value = " "; ShouldNotThrow( () => Ensure.String.IsNotNullOrEmpty(value, ParamName), () => EnsureArg.IsNotNullOrEmpty(value, ParamName), () => Ensure.That(value, ParamName).IsNotNullOrEmpty()); } [Fact] public void IsNotEmptyOrWhiteSpace_WhenNull_It_should_not_throw() { string value = null; ShouldNotThrow( () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace(), () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName)); } [Fact] public void IsNotEmptyOrWhiteSpace_WhenEmpty_ThrowsArgumentException() { string value = ""; ShouldThrow<ArgumentException>( ExceptionMessages.Strings_IsNotEmptyOrWhiteSpace_Failed, () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace(), () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName)); } [Fact] public void IsNotEmptyOrWhiteSpace_WhenWhiteSpace_ThrowsArgumentException() { string value = " "; ShouldThrow<ArgumentException>( ExceptionMessages.Strings_IsNotEmptyOrWhiteSpace_Failed, () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace(), () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName)); } [Fact] public void IsNotEmptyOrWhiteSpace_WhenPartialWhiteSpace_It_should_not_throw() { string value = " string with whitespace in it "; ShouldNotThrow( () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName), () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace()); } [Fact] public void IsNotNullOrWhiteSpace_WhenStringIsNull_ThrowsArgumentNullException() { string value = null; AssertIsNotNull( () => Ensure.String.IsNotNullOrWhiteSpace(value, ParamName), () => EnsureArg.IsNotNullOrWhiteSpace(value, ParamName)); } [Theory] [InlineData("")] [InlineData(" ")] public void IsNotNullOrWhiteSpace_WhenStringIsInvalid_ThrowsArgumentException(string value) { AssertIsNotNullOrWhiteSpace( () => Ensure.String.IsNotNullOrWhiteSpace(value, ParamName), () => EnsureArg.IsNotNullOrWhiteSpace(value, ParamName), () => Ensure.That(value, ParamName).IsNotNullOrWhiteSpace()); } [Fact] public void IsNotNullOrWhiteSpace_WhenStringHasValue_It_should_not_throw() { var value = "delta"; ShouldNotThrow( () => Ensure.String.IsNotNullOrWhiteSpace(value, ParamName), () => EnsureArg.IsNotNullOrWhiteSpace(value, ParamName), () => Ensure.That(value, ParamName).IsNotNullOrWhiteSpace()); } [Fact] public void IsNotEmpty_WhenStringIsEmpty_ThrowsArgumentException() { var value = string.Empty; AssertIsNotEmpty( () => Ensure.String.IsNotEmpty(value, ParamName), () => EnsureArg.IsNotEmpty(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmpty()); } [Fact] public void IsNotEmpty_WhenStringHasValue_It_should_not_throw() { var value = "delta"; ShouldNotThrow( () => Ensure.String.IsNotEmpty(value, ParamName), () => EnsureArg.IsNotEmpty(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmpty()); } [Fact] public void IsNotEmpty_WhenStringIsNull_It_should_not_throw() { string value = null; ShouldNotThrow( () => Ensure.String.IsNotEmpty(value, ParamName), () => EnsureArg.IsNotEmpty(value, ParamName), () => Ensure.That(value, ParamName).IsNotEmpty()); } [Fact] public void HasLength_When_null_It_throws_ArgumentNullException() { string value = null; var expected = 1; AssertIsNotNull( () => Ensure.String.HasLength(value, expected, ParamName), () => EnsureArg.HasLength(value, expected, ParamName), () => Ensure.That(value, ParamName).HasLength(expected)); } [Fact] public void HasLength_When_non_matching_length_of_string_It_throws_ArgumentException() { var value = "Some string"; var expected = value.Length + 1; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_SizeIs_Failed, expected, value.Length), () => Ensure.String.HasLength(value, expected, ParamName), () => EnsureArg.HasLength(value, expected, ParamName), () => Ensure.That(value, ParamName).HasLength(expected)); } [Fact] public void HasLength_When_matching_constraint_It_should_not_throw() { var value = "Some string"; ShouldNotThrow( () => Ensure.String.HasLength(value, value.Length, ParamName), () => EnsureArg.HasLength(value, value.Length, ParamName)); } [Fact] public void HasLengthBetween_WhenStringIsNull_ThrowsArgumentNullException() { string value = null; AssertIsNotNull( () => Ensure.String.HasLengthBetween(value, 1, 2, ParamName), () => EnsureArg.HasLengthBetween(value, 1, 2, ParamName), () => Ensure.That(value, ParamName).HasLengthBetween(1, 2)); } [Fact] public void HasLengthBetween_WhenStringIsToShort_ThrowsArgumentException() { const int low = 2; const int high = 4; var value = new string('a', low - 1); ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_HasLengthBetween_Failed_ToShort, low, high, value.Length), () => Ensure.String.HasLengthBetween(value, low, high, ParamName), () => EnsureArg.HasLengthBetween(value, low, high, ParamName), () => Ensure.That(value, ParamName).HasLengthBetween(low, high)); } [Fact] public void HasLengthBetween_WhenStringIsToLong_ThrowsArgumentException() { const int low = 2; const int high = 4; var value = new string('a', high + 1); ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_HasLengthBetween_Failed_ToLong, low, high, value.Length), () => Ensure.String.HasLengthBetween(value, low, high, ParamName), () => EnsureArg.HasLengthBetween(value, low, high, ParamName), () => Ensure.That(value, ParamName).HasLengthBetween(low, high)); } [Fact] public void HasLengthBetween_WhenStringIsLowLimit_It_should_not_throw() { const int low = 2; const int high = 4; var value = new string('a', low); ShouldNotThrow( () => Ensure.String.HasLengthBetween(value, low, high, ParamName), () => EnsureArg.HasLengthBetween(value, low, high, ParamName), () => Ensure.That(value, ParamName).HasLengthBetween(low, high)); } [Fact] public void HasLengthBetween_WhenStringIsHighLimit_It_should_not_throw() { const int low = 2; const int high = 4; var value = new string('a', high); ShouldNotThrow( () => Ensure.String.HasLengthBetween(value, low, high, ParamName), () => EnsureArg.HasLengthBetween(value, low, high, ParamName), () => Ensure.That(value, ParamName).HasLengthBetween(low, high)); } [Fact] public void Matches_WhenUrlStringDoesNotMatchStringPattern_ThrowsArgumentException() { const string value = @"incorrect"; const string match = @"(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*"; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_Matches_Failed, value, match), () => Ensure.String.Matches(value, match, ParamName), () => EnsureArg.Matches(value, match, ParamName), () => Ensure.That(value, ParamName).Matches(match)); } [Fact] public void Matches_WhenUrlStringDoesNotMatchRegex_ThrowsArgumentException() { const string value = @"incorrect"; var match = new Regex(@"(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*"); ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_Matches_Failed, value, match), () => Ensure.String.Matches(value, match, ParamName), () => EnsureArg.Matches(value, match, ParamName), () => Ensure.That(value, ParamName).Matches(match)); } [Fact] public void Matches_WhenUrlStringMatchesStringPattern_It_should_not_throw() { const string value = @"http://google.com:8080"; const string match = @"(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*"; ShouldNotThrow( () => Ensure.String.Matches(value, match, ParamName), () => EnsureArg.Matches(value, match, ParamName), () => Ensure.That(value, ParamName).Matches(match)); } [Fact] public void Matches_WhenUrlStringMatchesRegex_It_should_not_throw() { const string value = @"http://google.com:8080"; var match = new Regex(@"(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*"); ShouldNotThrow( () => Ensure.String.Matches(value, match, ParamName), () => EnsureArg.Matches(value, match, ParamName), () => Ensure.That(value, ParamName).Matches(match)); } [Fact] public void SizeIs_When_null_It_throws_ArgumentNullException() { string value = null; var expected = 1; AssertIsNotNull( () => Ensure.String.SizeIs(value, expected, ParamName), () => EnsureArg.SizeIs(value, expected, ParamName), () => Ensure.That(value, ParamName).SizeIs(expected)); } [Fact] public void SizeIs_When_non_matching_length_of_string_It_throws_ArgumentException() { var value = "Some string"; var expected = value.Length + 1; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_SizeIs_Failed, expected, value.Length), () => Ensure.String.SizeIs(value, expected, ParamName), () => EnsureArg.SizeIs(value, expected, ParamName), () => Ensure.That(value, ParamName).SizeIs(expected)); } [Fact] public void SizeIs_When_matching_constraint_It_should_not_throw() { var value = "Some string"; ShouldNotThrow( () => Ensure.String.SizeIs(value, value.Length, ParamName), () => EnsureArg.SizeIs(value, value.Length, ParamName)); } [Fact] public void IsEqualTo_When_different_values_It_throws_ArgumentException() { const string value = "The value"; const string expected = "Other value"; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsEqualTo_Failed, value, expected), () => Ensure.String.IsEqualTo(value, expected, ParamName), () => EnsureArg.IsEqualTo(value, expected, ParamName), () => Ensure.That(value, ParamName).IsEqualTo(expected)); } [Fact] public void IsEqualTo_When_same_value_It_should_not_throw() { const string value = "The value"; const string expected = value; ShouldNotThrow( () => Ensure.String.IsEqualTo(value, expected, ParamName), () => EnsureArg.IsEqualTo(value, expected, ParamName), () => Ensure.That(value, ParamName).IsEqualTo(expected), () => Ensure.String.Is(value, expected, ParamName), () => EnsureArg.Is(value, expected, ParamName), () => Ensure.That(value, ParamName).Is(expected)); } [Fact] public void IsEqualTo_When_same_value_by_specific_compare_It_should_not_throw() { const string value = "The value"; const string expected = "the value"; ShouldNotThrow( () => Ensure.String.IsEqualTo(value, expected, StringComparison.OrdinalIgnoreCase, ParamName), () => EnsureArg.IsEqualTo(value, expected, StringComparison.OrdinalIgnoreCase, ParamName), () => Ensure.That(value, ParamName).IsEqualTo(expected, StringComparison.OrdinalIgnoreCase), () => Ensure.String.Is(value, expected, StringComparison.OrdinalIgnoreCase, ParamName), () => EnsureArg.Is(value, expected, StringComparison.OrdinalIgnoreCase, ParamName), () => Ensure.That(value, ParamName).Is(expected, StringComparison.OrdinalIgnoreCase)); } [Fact] public void IsNotEqualTo_When_same_values_It_throws_ArgumentException() { const string value = "The value"; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNot_Failed, value, value), () => Ensure.String.IsNotEqualTo(value, value, ParamName), () => EnsureArg.IsNotEqualTo(value, value, ParamName), () => Ensure.That(value, ParamName).IsNotEqualTo(value), () => Ensure.String.IsNot(value, value, ParamName), () => EnsureArg.IsNot(value, value, ParamName), () => Ensure.That(value, ParamName).IsNot(value)); } [Fact] public void IsNotEqualTo_When_different_values_by_casing_using_non_case_sensitive_compare_It_throws_ArgumentException() { const string value = "The value"; var compareTo = value.ToLower(CultureInfo.CurrentCulture); ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Comp_IsNot_Failed, value, compareTo), () => Ensure.String.IsNotEqualTo(value, compareTo, StringComparison.OrdinalIgnoreCase, ParamName), () => EnsureArg.IsNotEqualTo(value, compareTo, StringComparison.OrdinalIgnoreCase, ParamName), () => Ensure.That(value, ParamName).IsNotEqualTo(compareTo, StringComparison.OrdinalIgnoreCase), () => Ensure.String.IsNot(value, compareTo, StringComparison.OrdinalIgnoreCase, ParamName), () => EnsureArg.IsNot(value, compareTo, StringComparison.OrdinalIgnoreCase, ParamName), () => Ensure.That(value, ParamName).IsNot(compareTo, StringComparison.OrdinalIgnoreCase)); } [Fact] public void IsNotEqualTo_When_different_values_It_should_not_throw() { var value = "The value"; ShouldNotThrow( () => Ensure.String.IsNotEqualTo(value, value + "a", ParamName), () => EnsureArg.IsNotEqualTo(value, value + "a", ParamName), () => Ensure.That(value, ParamName).IsNotEqualTo(value + "a"), () => Ensure.String.IsNot(value, value + "a", ParamName), () => EnsureArg.IsNot(value, value + "a", ParamName), () => Ensure.That(value, ParamName).IsNot(value + "a")); } [Fact] public void IsNotEqualTo_When_different_values_by_casing_using_case_sensitive_compare_It_should_not_throw() { var value = "The value"; var compareTo = value.ToLower(CultureInfo.CurrentCulture); ShouldNotThrow( () => Ensure.String.IsNotEqualTo(value, compareTo, StringComparison.Ordinal, ParamName), () => EnsureArg.IsNotEqualTo(value, compareTo, StringComparison.Ordinal, ParamName), () => Ensure.That(value, ParamName).IsNotEqualTo(compareTo, StringComparison.Ordinal), () => Ensure.String.IsNot(value, compareTo, StringComparison.Ordinal, ParamName), () => EnsureArg.IsNot(value, compareTo, StringComparison.Ordinal, ParamName), () => Ensure.That(value, ParamName).IsNot(compareTo, StringComparison.Ordinal)); } [Fact] public void IsGuid_When_null_It_should_not_throw_ArgumentNullException() { string value = null; ShouldThrowButNot<ArgumentNullException>( () => Ensure.String.IsGuid(value, ParamName), () => EnsureArg.IsGuid(value, ParamName), () => Ensure.That(value, ParamName).IsGuid()); } [Fact] public void IsGuid_When_null_It_should_throw_ArgumentException() { string value = null; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsGuid_Failed, value), () => Ensure.String.IsGuid(value, ParamName), () => EnsureArg.IsGuid(value, ParamName), () => Ensure.That(value, ParamName).IsGuid()); } [Fact] public void IsGuid_When_is_not_Guid_throws_ArgumentException() { const string value = "324-3243-123-23"; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsGuid_Failed, value), () => Ensure.String.IsGuid(value, ParamName), () => EnsureArg.IsGuid(value, ParamName), () => Ensure.That(value, ParamName).IsGuid()); } [Fact] public void IsGuid_When_valid_Guid_It_should_not_throw_and_should_return_Guid() { var value = Guid.NewGuid(); var valueAsString = value.ToString(); ShouldNotThrow( () => Ensure.String.IsGuid(valueAsString, ParamName), () => EnsureArg.IsGuid(valueAsString, ParamName), () => Ensure.That(valueAsString, ParamName).IsGuid()); ShouldReturn( value, () => Ensure.String.IsGuid(valueAsString), () => EnsureArg.IsGuid(valueAsString)); } [Fact] public void StartsWith_When_DoesStartWith_It_should_not_throw() { var value = "startsWith_foobar"; var startPart = "startsWith"; ShouldNotThrow( () => Ensure.String.StartsWith(value, startPart, ParamName), () => EnsureArg.StartsWith(value, startPart, ParamName), () => Ensure.That(value, ParamName).StartsWith(startPart)); } [Fact] public void StartsWith_When_DoesNotStartWith_It_should_throw() { var value = "startsWith_foobar"; var startPart = "otherString"; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_StartsWith_Failed, value, startPart), () => Ensure.String.StartsWith(value, startPart, ParamName), () => EnsureArg.StartsWith(value, startPart, ParamName), () => Ensure.That(value, ParamName).StartsWith(startPart)); } [Fact] public void IsAllLettersOrDigits_WhenStringIsAllLettersAndDigits_It_should_not_throw() { const string value = "aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789"; ShouldNotThrow( () => Ensure.String.IsAllLettersOrDigits(value, ParamName), () => EnsureArg.IsAllLettersOrDigits(value, ParamName), () => Ensure.That(value, ParamName).IsAllLettersOrDigits()); } [Fact] public void IsAllLettersOrDigits_WhenStringIsAllDigits_It_should_not_throw() { const string value = "0123456789"; ShouldNotThrow( () => Ensure.String.IsAllLettersOrDigits(value, ParamName), () => EnsureArg.IsAllLettersOrDigits(value, ParamName), () => Ensure.That(value, ParamName).IsAllLettersOrDigits()); } [Fact] public void IsAllLettersOrDigits_WhenStringIsAllLetters_It_should_not_throw() { const string value = "aBcDeFgHiJkLmNoPqRsTuVwXyZ"; ShouldNotThrow( () => Ensure.String.IsAllLettersOrDigits(value, ParamName), () => EnsureArg.IsAllLettersOrDigits(value, ParamName), () => Ensure.That(value, ParamName).IsAllLettersOrDigits()); } [Fact] public void IsAllLettersOrDigits_WhenStringDoesNotHaveLettersOrDigits_It_should_throw() { const string value = "<:)-+-<"; ShouldThrow<ArgumentException>( string.Format(DefaultFormatProvider.Strings, ExceptionMessages.Strings_IsAllLettersOrDigits_Failed, value), () => Ensure.String.IsAllLettersOrDigits(value, ParamName), () => EnsureArg.IsAllLettersOrDigits(value, ParamName), () => Ensure.That(value, ParamName).IsAllLettersOrDigits()); } } }
using UnityEngine; [CreateAssetMenu( fileName = "Requirement", menuName = "MS49/Milestone/Requirement/Worker Count", order = 1)] public class RequirementMethodWorkerCount : RequirementMethodBase { [SerializeField, Tooltip("If blank, all worker types will be counted.")] private WorkerType workerType = null; public override int getProgress(World world) { int count = 0; foreach(EntityBase e in world.entities.list) { if(e is EntityWorker) { if(this.workerType == null) { count++; } else { if(((EntityWorker)e).type == this.workerType) { count++; } } } } return count; } }
using Core; using DBCore; using ServiceCenter.Helpers; using ServiceCenter.View.Repair; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Input; namespace ServiceCenter.ViewModel.Repair { class PageAppearanceViewModel : BaseViewModel, ICallbackUpdate { //наша форма private FormOrderInfo window = Application.Current.Windows.OfType<FormOrderInfo>().FirstOrDefault(); //главный фрейм private PageOrderInfoViewModel context; #region поля и свойства для связи с формой //индикатор ожидания private bool _isAwait = false; public bool IsAwait { get => _isAwait; set => Set(ref _isAwait, value); } //сторка поиска private string _searchField = " "; public string SearchField { get => _searchField; set => Set(ref _searchField, value); } //список внешнего вида private ObservableCollection<Appearance> _appearanceList = new ObservableCollection<Appearance>(); public ObservableCollection<Appearance> AppearanceList { get => _appearanceList; set => Set(ref _appearanceList, value); } private IEnumerable<Appearance> _appearanceFiltred; public IEnumerable<Appearance> AppearanceFiltrerd { get => _appearanceFiltred; set => Set(ref _appearanceFiltred, value); } private Appearance _selectedAppearance = null; public Appearance SelectedAppearance { get => _selectedAppearance; set => Set(ref _selectedAppearance, value); } #endregion #region комманды public ICommand CancelSearchCommand { get; } public ICommand SendAppearanceCommand { get; } public ICommand AddAppearanceCommand { get; } #endregion //конструктор public PageAppearanceViewModel(PageOrderInfoViewModel context) { this.context = context; CancelSearchCommand = new Command(CancelSearchExecute, CancelSearchCanExecute); SendAppearanceCommand = new Command(SendAppearanceExecuted, SendAppearanceCanExecuted); AddAppearanceCommand = new Command(AddAppearanceExecute); PropertyChanged += PageAppearanceViewModel_PropertyChanged; GetAppearance(); } private void PageAppearanceViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { //обработка строки поиска if (e.PropertyName == nameof(SearchField)) { AppearanceFiltrerd = from i in _appearanceList where i.AppearanceName.ToLower().IndexOf(_searchField.ToLower()) >= 0 select i; } } #region обработка комманд private void AddAppearanceExecute(object obj) { PageAppearanceAdd page = new PageAppearanceAdd(); PageAppearanceAddViewModel model = new PageAppearanceAddViewModel(this); page.DataContext = model; window.frame_OrderInfo.Navigate(page); } private void SendAppearanceExecuted(object obj) { context.Appearance = SelectedAppearance; window.frame_OrderInfo.GoBack(); } private bool SendAppearanceCanExecuted(object arg) { if (SelectedAppearance == null) return false; else return true; } private async void GetAppearance() { IsAwait = true; _appearanceList.Clear(); var list = await AppearanceDB.GetAppearanceAsync(); IsAwait = false; if (list == null) Dialogs.DialogBox.Show("ServiceCenter", "Ошибка получения списка внешнего вида", "Вероятно проблемы с сервером или подключением", Dialogs.DialogIcons.Error); else { for (int i = 0; i < list.Count; i++) { _appearanceList.Add(list[i]); } SearchField = string.Empty;//дергаем свойство, чтобы сработал linq запрос } } private bool CancelSearchCanExecute(object arg) { if (String.IsNullOrEmpty(SearchField)) return false; else return true; } private void CancelSearchExecute(object obj) { SearchField = string.Empty; } #endregion #region реализация интерфейса public void AddToList(object o) { if (o is Appearance) { Appearance appearance = o as Appearance; context.Appearance = appearance; window.frame_OrderInfo.GoBack(); } } public void RemoveFromList(object o) { //not use } public void Update(int positionId, object o) { //not use } public void Refresh() { //not use } public void Select(object o) { if (o is Appearance) { Appearance appearance = o as Appearance; SearchField = appearance.AppearanceName; } } #endregion } }
namespace Uintra.Core.User.Models { public interface IIntranetUser { int Id { get; set; } string Email { get; set; } string DisplayName { get; set; } bool IsSuperUser { get; set; } bool IsApproved { get; set; } bool IsLockedOut { get; set; } bool IsValid { get; } } }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; await Host.CreateDefaultBuilder() .ConfigureHostConfiguration(c => { c.SetBasePath(Directory.GetCurrentDirectory()); c.AddJsonFile("appsettings.json", optional: false); }) .ConfigureServices((_, s) => s.AddHostedService<SampleHostedService>()) .ConfigureLogging((c, l) => { l.AddConfiguration(c.Configuration); l.AddConsole(); l.AddSentry(); }) .UseConsoleLifetime() .Build() .RunAsync();
using System; using System.Globalization; namespace Crystal.Plot2D.Charts { public abstract class NumericLabelProviderBase : LabelProviderBase<double> { bool shouldRound = true; private int rounding; protected void Init(double[] ticks) { if (ticks.Length == 0) { return; } double start = ticks[0]; double finish = ticks[ticks.Length - 1]; if (start == finish) { shouldRound = false; return; } double delta = finish - start; rounding = (int)Math.Round(Math.Log10(delta)); double newStart = RoundingHelper.Round(start, rounding); double newFinish = RoundingHelper.Round(finish, rounding); if (newStart == newFinish) { rounding--; } } protected override string GetStringCore(LabelTickInfo<double> tickInfo) { string res; if (!shouldRound) { res = tickInfo.Tick.ToString(CultureInfo.InvariantCulture); } else { int round = Math.Min(15, Math.Max(-15, rounding - 3)); // was rounding - 2 res = RoundingHelper.Round(tickInfo.Tick, round).ToString(CultureInfo.InvariantCulture); } return res; } } }
using Microsoft.Office.Interop.Excel; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace Pronto.Common { public class ExcelImport { public static void ExportToPdf(Route route,string pdfFile) { Excel.Workbook wbk = ExportToExcel(route); Excel.Application app = wbk.Application; app.Visible = false; app.DisplayAlerts = false; wbk.Worksheets["Search"].Delete(); wbk.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfFile, XlFixedFormatQuality.xlQualityMinimum, false); wbk.Close(false); app.Quit(); } public static void ExportToPdf(System.Data.DataTable dtTable, string pdfFile) { Excel.Workbook wbk = ExportToExcel(dtTable); Excel.Application app = wbk.Application; app.Visible = false; app.DisplayAlerts = false; wbk.Worksheets["Stops"].Delete(); wbk.Worksheets["Route"].Delete(); wbk.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, pdfFile, XlFixedFormatQuality.xlQualityMinimum, false); wbk.Close(false); app.Quit(); } public static void ExportExcel(Route route) { Excel.Workbook wk = ExportToExcel(route); wk.Application.Visible = true; wk.Application.WindowState = XlWindowState.xlMaximized; } public static void ExportExcel(System.Data.DataTable dtTable) { Excel.Workbook wk = ExportToExcel( dtTable); wk.Application.Visible = true; wk.Worksheets["Search"].Select(); wk.Application.WindowState = XlWindowState.xlMaximized; } private static Excel.Workbook ExportToExcel(System.Data.DataTable dtTable) { Excel.Workbook wbk = OpenExcel(); Excel.Worksheet wkSheet = wbk.Worksheets["Search"]; for (int i = 0; i < dtTable.Columns.Count; i++) { wkSheet.Cells[1, i+1].Value = dtTable.Columns[i].ColumnName; for (int j = 0; j < dtTable.Rows.Count; j++) { wkSheet.Cells[j+2, i+1].Value = dtTable.Rows[j][i].ToString(); } } wkSheet.Columns.AutoFit(); wkSheet.PageSetup.PrintArea = wkSheet.Range[wkSheet.Cells[1, 1], wkSheet.Cells[dtTable.Rows.Count + 1, dtTable.Columns.Count]].Address; return wbk; } private static Excel.Workbook ExportToExcel(Route route) { Excel.Workbook wbk = OpenExcel(); foreach (Excel.Worksheet item in wbk.Worksheets) { item.PageSetup.LeftHeader = "Route ID: -" + route.RootNo.ToString(); item.PageSetup.RightHeader = "Route Date:-" + route.RouteDate.ToString(); } WritToExcel("RootNo", route.RootNo.ToString(), wbk); WritToExcel("RouteDate", route.RouteDate.ToString(), wbk); WritToExcel("DriverName", route.driver.DriverName.ToString(), wbk); WritToExcel("VehicleId", route.truck.VehicleID, wbk); WritToExcel("LicencePlateId", route.truck.LicencePlateId, wbk); WritToExcel("TruckId", route.truck.TruckId.ToString(), wbk); if (route.helpers != null) { for (int i = 0; i < route.helpers.Count; i++) { WritToExcel("HelperName" + (i + 1).ToString(), route.helpers[i].HelperName.ToString(), wbk); } } WritToExcel("DepatureTime", route.DepatureTime.ToString(), wbk); WritToExcel("ArrivelTime", route.ArrivelTime.ToString(), wbk); WritToExcel("DepartureMilage", route.DepartureMilage.ToString(), wbk); WritToExcel("ArrivelMilage", route.ArrivelMilage.ToString(), wbk); WritToExcel("RouteMlg", route.RouteMlg.ToString(), wbk); WritToExcel("HotelInfo", route.HotelInfo.ToString(), wbk); WritToExcel("HotelReceipt", route.HotelReceipt.ToString(), wbk); WritToExcel("TotolCod", route.TotolCod.ToString(), wbk); WritToExcel("CodDecrepency", route.CodDecrepency.ToString(), wbk); WritToExcel("BreakAStart", route.BreakAStart.ToString(), wbk); WritToExcel("BreakAEnd", route.BreakAEnd.ToString(), wbk); WritToExcel("BreakBStart", route.BreakBStart.ToString(), wbk); WritToExcel("BreakBEnd", route.BreakBEnd.ToString(), wbk); WritToExcel("LunchStart", route.LunchStart.ToString(), wbk); WritToExcel("LunchEnd", route.LunchEnd.ToString(), wbk); WritToExcel("DinnerStart", route.DinnerStart.ToString(), wbk); WritToExcel("DinnerEnd", route.DinnerEnd.ToString(), wbk); WritToExcel("DriverComments", route.DriverComments.ToString(), wbk); WriteStopsToExcel(wbk, route.stops, route.RootNo, route.RouteDate); return wbk; } private static void WriteStopsToExcel(Excel.Workbook wk,List<Stop> stopList,int RootNo,DateTime routedate) { Excel.Worksheet wkSheet = wk.Worksheets["Stops"]; //wkSheet.UsedRange.PageBreak = (int)Excel.XlPageBreak.xlPageBreakManual; int Offset = 31; int lastRow = stopList.Count * Offset; //wkSheet.Application.ActiveWindow.View = XlWindowView.xlPageBreakPreview; wkSheet.PageSetup.PrintArea = wkSheet.Range[wkSheet.Cells[1, 1], wkSheet.Cells[lastRow, 6]].Address; //wkSheet.HPageBreaks.Add(wkSheet.Range["A7"]); //wkSheet.VPageBreaks.Add(wkSheet.Cells[4,3]); for (int i = stopList.Count; i > 0 ;i--) { WritToExcel("StopNo", "Stop-" + i.ToString(), wk); WritToExcel("ClientName", stopList[i-1].ClientName, wk); if (stopList[i - 1].customer != null) { WritToExcel("CustomerName", stopList[i - 1].customer.CustomerName, wk); } WritToExcel("ClientAddr", stopList[i - 1].ClientAddr, wk); WritToExcel("ClientCity", stopList[i - 1].ClientCity, wk); WritToExcel("ClientState", stopList[i - 1].ClientState, wk); WritToExcel("ClientZipCode", stopList[i - 1].ClientZipCode, wk); if (stopList[i - 1].service != null) { WritToExcel("ServiceType", stopList[i - 1].service.ServiceType, wk); } WritToExcel("ClientPh", stopList[i - 1].ClientPh, wk); WritToExcel("PTSID", stopList[i - 1].PtsId, wk); WritToExcel("QBDocNo", stopList[i - 1].QbDocNo, wk); WritToExcel("PhoneID", stopList[i - 1].PhoneId, wk); WritToExcel("PADID", stopList[i - 1].PadId, wk); WritToExcel("StopArrivalTime", stopList[i - 1].StopArrivalTime.ToString(), wk); WritToExcel("ETA", stopList[i - 1].Eta, wk); WritToExcel("StopMlgMeterRead", stopList[i - 1].StopMlgMeterRead.ToString(), wk); WritToExcel("StopDepartTime", stopList[i - 1].StopDepartTime.ToString(), wk); WritToExcel("StopCodAmount", stopList[i - 1].StopCodAmount.ToString(), wk); WritToExcel("StopTimeAllot", stopList[i - 1].StopTimeAllot.ToString(), wk); WritToExcel("StopNote", stopList[i - 1].StopNote, wk); if (i > 1) { wk.Names.Item("StopArea").RefersToRange.EntireRow.Copy(); wkSheet.Cells[Offset * (i - 1) + 1, 1].PasteSpecial(XlPasteType.xlPasteAll, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false); //wkSheet.Cells[Offset * (i - 1) + 1, 1].PasteSpecial(XlPasteType.xlPasteFormats, XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false); var tt = wkSheet.Cells[Offset * (i - 1) + 1, 1].Address; wkSheet.HPageBreaks.Add(wkSheet.Cells[Offset * (i - 1) + 1, 1]); } } //if (stopList.Count > 1) //{ // wkSheet.HPageBreaks[1].DragOff(XlDirection.xlDown, 1); //} Clipboard.Clear(); //wkSheet.Columns.AutoFit(); } private static void WritToExcel(string PropName,string value,Excel.Workbook wk) { try { wk.Names.Item(PropName).RefersToRange.Value = value; } catch (Exception ex) { throw new Exception("Cannot write value to excel " + PropName, ex); } } private static Excel.Workbook OpenExcel() { string TemplatePath = Path.Combine(Utility.ProjectPaths.InstallationPath, "Template.xltx"); Excel.Application xlApp = new Excel.Application(); Excel.Workbook wktmpl = xlApp.Workbooks.Open(TemplatePath); //xlApp.Visible = true; //xlApp.WindowState = Excel.XlWindowState.xlMaximized; return wktmpl; } } }
using Mirror; using System.Collections; using System.Collections.Generic; using UnityEngine; [DisallowMultipleComponent] public abstract class Entity : NetworkBehaviour { [SyncVar] public int storyLocation; protected SpriteRenderer spriteRenderer; string outlineShaderName = "_UseOutline"; int outlineShaderPropertyID; string isPrimaryShaderName = "_IsPrimaryTarget"; int isPrimaryShaderPropertyID; private Rigidbody2D rb2D; public virtual void Init(int storyLocation) { this.storyLocation = storyLocation; } protected virtual void Start() { spriteRenderer = GetComponent<SpriteRenderer>(); rb2D = GetComponent<Rigidbody2D>(); SortIntoParent(); UpdateLayering(); outlineShaderPropertyID = Shader.PropertyToID(outlineShaderName); isPrimaryShaderPropertyID = Shader.PropertyToID(isPrimaryShaderName); } public void NotifyInteractionRadiusChange(bool isInside) { if (IsInteractable() && isInside) { SetShaderOutlineEnabled(true); } else { SetShaderOutlineEnabled(false); } } public void NotifyIsPrimaryTarget(bool isPrimaryTarget) { if (IsInteractable()) { SetShaderIsPrimaryTarget(isPrimaryTarget); } } void SetShaderOutlineEnabled(bool enabled) { if (spriteRenderer) { spriteRenderer.material.SetFloat(outlineShaderPropertyID, (enabled ? 1 : 0)); } } void SetShaderIsPrimaryTarget(bool isPrimaryTarget) { if (spriteRenderer) { spriteRenderer.material.SetFloat(isPrimaryShaderPropertyID, (isPrimaryTarget ? 1 : 0)); } } public virtual bool IsInteractable() { return false; } public virtual void Interact(PlayerCharacter playerCharacter) { //To be overriden } protected virtual void UpdateLayering() { gameObject.layer = (int)Layering.StoryToPhysicsLayer(storyLocation); if (spriteRenderer) { spriteRenderer.sortingLayerID = Layering.StoryToSortingLayerID(storyLocation); spriteRenderer.sortingOrder = Constants.ENTITY_SORTING_ORDER; } } public virtual void ChangeStory(Verticality verticality) { print(verticality); if (verticality == Verticality.Up) storyLocation++; else storyLocation--; UpdateLayering(); SortIntoParent(); } public void JumpToPosition(Vector3 position) { if (rb2D != null) rb2D.MovePosition(position); else transform.position = position; } protected abstract void SortIntoParent(); }
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 MainWebApplication.Data; using MainWebApplication.Models; namespace MainWebApplication.Views { public class DigitalValuesController : Controller { private readonly MainWebApplicationContext _context; public DigitalValuesController(MainWebApplicationContext context) { _context = context; } // GET: DigitalValues public async Task<IActionResult> Index() { var mainWebApplicationContext = _context.DigitalValue.Include(d => d.BleCharacteristic); return View(await mainWebApplicationContext.ToListAsync()); } // GET: DigitalValues/Details/5 public async Task<IActionResult> Details(DateTime? id) { if (id == null) { return NotFound(); } var digitalValue = await _context.DigitalValue .Include(d => d.BleCharacteristic) .FirstOrDefaultAsync(m => m.Timestamp == id); if (digitalValue == null) { return NotFound(); } return View(digitalValue); } // GET: DigitalValues/Create public IActionResult Create() { ViewData["BleCharacteristicID"] = new SelectList(_context.Set<BleCharacteristic>(), "BleCharacteristicID", "Discriminator"); return View(); } // POST: DigitalValues/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("BleCharacteristicID,Timestamp,Value")] DigitalValue digitalValue) { if (ModelState.IsValid) { _context.Add(digitalValue); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["BleCharacteristicID"] = new SelectList(_context.Set<BleCharacteristic>(), "BleCharacteristicID", "Discriminator", digitalValue.BleCharacteristicID); return View(digitalValue); } // GET: DigitalValues/Edit/5 public async Task<IActionResult> Edit(DateTime? id) { if (id == null) { return NotFound(); } var digitalValue = await _context.DigitalValue.FindAsync(id); if (digitalValue == null) { return NotFound(); } ViewData["BleCharacteristicID"] = new SelectList(_context.Set<BleCharacteristic>(), "BleCharacteristicID", "Discriminator", digitalValue.BleCharacteristicID); return View(digitalValue); } // POST: DigitalValues/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(DateTime id, [Bind("BleCharacteristicID,Timestamp,Value")] DigitalValue digitalValue) { if (id != digitalValue.Timestamp) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(digitalValue); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DigitalValueExists(digitalValue.Timestamp)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["BleCharacteristicID"] = new SelectList(_context.Set<BleCharacteristic>(), "BleCharacteristicID", "Discriminator", digitalValue.BleCharacteristicID); return View(digitalValue); } // GET: DigitalValues/Delete/5 public async Task<IActionResult> Delete(DateTime? id) { if (id == null) { return NotFound(); } var digitalValue = await _context.DigitalValue .Include(d => d.BleCharacteristic) .FirstOrDefaultAsync(m => m.Timestamp == id); if (digitalValue == null) { return NotFound(); } return View(digitalValue); } // POST: DigitalValues/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(DateTime id) { var digitalValue = await _context.DigitalValue.FindAsync(id); _context.DigitalValue.Remove(digitalValue); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool DigitalValueExists(DateTime id) { return _context.DigitalValue.Any(e => e.Timestamp == id); } } }
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; namespace Library.API.Controllers { [Route("api/values")] [ApiController] public class ValuesController : ControllerBase { private List<Student> students = new List<Student>(); public ValuesController(IDataProtectionProvider dataProtectionProvider, ILogger<ValuesController> logger) { DataProtectionProvider = dataProtectionProvider; Logger = logger; students.Add(new Student { Id = "1", Name = "TestUser" }); } public IDataProtectionProvider DataProtectionProvider { get; } public ILogger Logger { get; } [HttpGet] public ActionResult<IEnumerable<Student>> Get() { //var protector = DataProtectionProvider.CreateProtector("ProtectResourceId"); var protectorA = DataProtectionProvider.CreateProtector("A"); var protectorB = DataProtectionProvider.CreateProtector("B"); var protector = DataProtectionProvider.CreateProtector("C"); var result = students.Select(s => new Student { Id = protector.Protect(s.Id), Name = s.Name }); return result.ToList(); } [HttpGet("{id}")] public ActionResult<Student> Get(string id) { //var protector = DataProtectionProvider.CreateProtector("ProtectResourceId"); var protector = DataProtectionProvider.CreateProtector("A", "B", "C"); var rawId = protector.Unprotect(id); var targetItem = students.FirstOrDefault(s => s.Id == rawId); return new Student { Id = id, Name = targetItem.Name }; } private void TimeLimitedDataProtectorTest() { //当使用Unprotect方法解密时,如果密文已经过期,则同样会抛出CryptographicException异常 var protector = DataProtectionProvider.CreateProtector("testing").ToTimeLimitedDataProtector(); var content = protector.Protect("Hello", DateTimeOffset.Now.AddMinutes(10)); try { var rawContent = protector.Unprotect(content, out DateTimeOffset expiration); } catch (CryptographicException ex) { Logger.LogError(ex.Message, ex); } /* Microsoft.AspNetCore.DataProtection包中还提供了EphemeralDataProtectionProvider类,作为IDataProtectionProvider接口的一个实现, 它的加密和解密功能具有“一次性”的特点,当密文不需要持久化时,可以使用这种方式。所有的键都存储在内存中,且每个EphemeralDataProtectionProvider实例都有自己的主键。 */ } } public class Student { public string Id { get; set; } public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace checkMusic { class UpdateAppConfig { string ApplicationPath=""; System.IO.FileInfo AppConfigfile; StreamWriter sw; public void init(){ ApplicationPath = Directory.GetCurrentDirectory().ToString(); AppConfigfile = new FileInfo(ApplicationPath + "\\App.config"); } public void removeAppConfig(){ init(); if (AppConfigfile.Exists) AppConfigfile.Delete(); } public void creatAppConfig() { init(); if (!AppConfigfile.Exists) AppConfigfile.Create(); } public void updateAppConfig(string key,string value) { init(); if (AppConfigfile.Exists) AppConfigfile.Delete(); sw= AppConfigfile.CreateText(); sw.WriteLine("<?xml version=\""+"1.0\"?>"); sw.WriteLine("<configuration>"); sw.WriteLine("<connectionStrings>"); sw.WriteLine("<add name=\"Default\" connectionString=\"Max Pool Size = 512;server="+"."+";uid=sa; pwd=esun5005;database=ESUNNET\" providerName=\"System.Data.SqlClient\" />"); sw.WriteLine("</connectionStrings>"); sw.WriteLine(" <appSettings>"); if (key == "LeavePath") { sw.WriteLine("<add key=\"LeavePath\" value=\"" + value + "\"/>"); sw.WriteLine("<add key=\"RecordPath\" value=\"" + value + "\"/>"); } // sw.WriteLine("<add key=\"LeavePath\" value=\"" + "D:\\work\\z中百集团\\VXML" + "\"/>"); if (key == "RecordPath") { sw.WriteLine("<add key=\"LeavePath\" value=\"" + value + "\"/>"); sw.WriteLine("<add key=\"RecordPath\" value=\"" + value + "\"/>"); } sw.WriteLine("</appSettings>"); sw.WriteLine("</configuration>"); sw.AutoFlush = true; AppConfigfile.Refresh(); sw.Flush(); if (sw != null) sw.Close(); sw.Dispose(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MaterialSkin.Controls; using AForge.Video; using AForge.Video.DirectShow; using FontAwesome.Sharp; using MaterialSkin; namespace Parking_Lot_Project { public partial class bossForm : MaterialForm { #region Data Admin ad = new Admin(); #endregion #region Camera #endregion public delegate void sendData(string id); public sendData sendTheData; public bossForm() { InitializeComponent(); } private void OpenForm(Form childForm, TabPage page) { //if (curentEmpForm != null) //{ // curentEmpForm.Close(); //} childForm.TopLevel = false; childForm.FormBorderStyle = FormBorderStyle.None; childForm.Dock = DockStyle.Fill; page.Controls.Add(childForm); childForm.BringToFront(); childForm.Show(); } private void OpenFormPanel(Form childForm, Panel page) { //if (curentEmpForm != null) //{ // curentEmpForm.Close(); //} childForm.TopLevel = false; childForm.FormBorderStyle = FormBorderStyle.None; childForm.Dock = DockStyle.Fill; page.Controls.Add(childForm); childForm.BringToFront(); childForm.Show(); } private void bossForm_Load(object sender, EventArgs e) { //loadDataEmp(); //cameras = new FilterInfoCollection(FilterCategory.VideoInputDevice); //foreach (FilterInfo camera in cameras) // comboBox_cameras.Items.Add(camera.Name); //comboBox_cameras.SelectedIndex = 1; //comboBox_manager.Enabled = false; mainForm frm = new mainForm(); frm.label_darkID.Text = "Boss"; frm.iconButton_exit.Visible = false; interfaceWorkerForm frmEmp = new interfaceWorkerForm(); frm.label_darkID.Text = "B"; OpenForm(frmEmp, tabPage_emp); OpenForm(new parkingAreaForm(), tabPage_transport); OpenFormPanel(new calenderForm(), panel_calender) ; OpenFormPanel(new interfaceForm(), panel_work); OpenForm(new customerListForm(), tabPage_customer); OpenForm(new contractForm(), tabPage_contract); OpenForm(new addSpecForm(), tabPage_addSpec); } #region Format #endregion private void iconButton_setting_Click(object sender, EventArgs e) { settingBossForm frm = new settingBossForm(); frm.ShowDialog(); } private void metroTile_emp_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_emp; } private void metroTile_addAccount_Click(object sender, EventArgs e) { RegisterForm frm = new RegisterForm(); frm.ShowDialog(); } private void metroTile_setting_Click(object sender, EventArgs e) { settingBossForm frm = new settingBossForm(); frm.ShowDialog(); } private void metroTile_exit_Click(object sender, EventArgs e) { Application.Exit(); } private void metroTile_parking_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_transport; } private void metroTile_security_Click(object sender, EventArgs e) { } private void groupBox_work_Enter(object sender, EventArgs e) { //addManagerForm frm = new addManagerForm(); //frm.Show(); } private void metroTile_bike_Click(object sender, EventArgs e) { bikeListForm frm = new bikeListForm(); frm.Show(); } private void metroTile_addCus_Click(object sender, EventArgs e) { addCustomerForm frm = new addCustomerForm(); frm.Show(); } private void metroTile_listCus_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_customer; } private void materialButton_settingSpec_Click(object sender, EventArgs e) { specSettingForm frm = new specSettingForm(); frm.Show(); } private void metroTile_rent_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedIndex = 6; OpenForm(new contractForm(), tabPage_contract); } private void metroTile_sendRent_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedIndex = 6; contractForm frm = new contractForm(); frm.tabControl_rent.SelectedIndex = 1; OpenForm(frm, tabPage_contract); } private void metroTile_listContract_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedIndex = 6; contractForm frm = new contractForm(); frm.tabControl_rent.SelectedIndex = 2; OpenForm(frm, tabPage_contract); } private void tabPage_Dashboard_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_interface; } private void comboBox_service_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox_service.SelectedIndex == 0) { OpenFormPanel(new interfaceFixForm(), panel_service); } else { OpenFormPanel(new interfaceWasherForm(), panel_service); } } private void metroTile_serviceFix_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_service; comboBox_service.SelectedIndex = 0; } private void metroTile_washService_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_service; comboBox_service.SelectedIndex = 1; } private void metroTile_spec_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_addSpec; } private void metroTile_shiftSe_Click(object sender, EventArgs e) { OpenForm(new shiftForm(), tabPage_shift); materialTabControl_boss.SelectedTab = tabPage_shift; } private void metroTile_shiftFix_Click(object sender, EventArgs e) { OpenForm(new shiftFixForm(), tabPage_shift); materialTabControl_boss.SelectedTab = tabPage_shift; } private void metroTile_shiftWash_Click(object sender, EventArgs e) { OpenForm(new shiftWashForm(), tabPage_shift); materialTabControl_boss.SelectedTab = tabPage_shift; } private void iconButton_home_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_interface; } private void metroTile_se_Click(object sender, EventArgs e) { addManagerForm frm = new addManagerForm(); frm.Show(); } private void metroTile_car_Click(object sender, EventArgs e) { carListForm frm = new carListForm(); frm.Show(); } private void metroTile_moto_Click(object sender, EventArgs e) { motorListForm frm = new motorListForm(); frm.Show(); } private void metroTile_fix_Click(object sender, EventArgs e) { removeManagerForm frm = new removeManagerForm(); frm.Show(); } private void metroTile_price_Click(object sender, EventArgs e) { materialTabControl_boss.SelectedTab = tabPage_work; } private void iconButton1_Click(object sender, EventArgs e) { bossForm_Load(null, null); } } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System; using UnityEngine; using UnityEditor; public class nearItemInfo { public int no; public iInfo info; public float dist; public bfsPos[] bfsPos; public Vector3[] bestWay; public nearItemInfo(int _no, iInfo _info, float _dist, bfsPos[] _bfsPos, Vector3[] _bestWay) { no = _no; info = _info; dist = _dist; bfsPos = _bfsPos; bestWay = _bestWay; } public void setBestWay(Vector3[] BestWay) { bestWay = BestWay; } } //public class bfsPos { // public Vector3 pos; // public Vector3[] ch; // public Vector3 pr; // public int no; // public float bfsDist = 0; // public bfsPos(Vector3 pos_, Vector3 pr_, Vector3[] ch_, int no_) { // pos = pos_; // pr = pr_; // ch = ch_; // no = no_; // } // public Vector3 getParent() { // return pr; // } // public void set_bfsDist(float _bfsDist) { // bfsDist = _bfsDist; // } //} public class bfsPos { public Vector3 pos; public int prNo; public int[] chNo; public int layNo; public float bfsDist = 0; public bfsPos(Vector3 _pos, int _layNo, int _prNo, int[] _chNo) { pos = _pos; layNo = _layNo; prNo = _prNo; chNo = _chNo; } public int getParent() { return prNo; } public void set_bfsDist(float _bfsDist) { bfsDist = _bfsDist; } } public class EnemyBehaviour : MonoBehaviour { private GameObject initObj; private InitBehaviour init; private Methods mt; public StreamWriter sw; private bool swFlg = false; Vector3[] BestWayToGoal = new Vector3[0]; /* 一時停止 */ [MenuItem ("Custom/Pause")] private static void Pause () { EditorApplication.isPaused = true; } // Use this for initialization void Start () { initObj = GameObject.Find( "Player" ); init = initObj.GetComponent<InitBehaviour>(); mt = initObj.GetComponent<Methods> (); } /* ************** * * Update * * **************/ /* プレイヤーの動きを定義 */ bool trackGoalFlg = false; int goalCnt; private void playerMove() { // nearItmがリセットされていて、かつ残りのItemがある場合 if (mt.checkRestItemExist ()) { if (!mt.checkNearItemExist (init.nearItm)) { mt.getNearItemInfo (); // 一番近いitem情報を出す // sw.WriteLine ("\nbfsPos"); // bfsPos[] bfsPos = init.nearItm.bfsPos; // for (int i = 0; i < bfsPos.Length; i++) { // sw.Write ("no: " + i.ToString() + " layNo: " + bfsPos [i].layNo.ToString() + " pr: " + bfsPos [i].prNo.ToString() + " pos: " + bfsPos [i].pos + " ch: "); // for (int j = 0; j < bfsPos [i].chNo.Length; j++) { // sw.Write (bfsPos [i].chNo [j].ToString() + " "); // } // sw.WriteLine (); // } // sw.WriteLine ("====="); // 最適経路を作成 //print(init.nearItm.dist); Vector3[] BestWay = mt.createBestWay (init.nearItm.info.pos, init.nearItm.bfsPos, (int)init.nearItm.dist); // 作成した最適経路はnearItmに格納する init.nearItm.setBestWay (BestWay); // sw.WriteLine ("BestWay len: " + BestWay.Length.ToString()); // for (int i = 0; i < BestWay.Length; i++) { // sw.WriteLine (BestWay [i]); // } // sw.WriteLine (); } // 格納されているBestWayに沿って動く Vector3 pNewPos = new Vector3(); if (mt.checkBestWayExist (init.nearItm.bestWay)) { pNewPos = init.nearItm.bestWay [(int)init.nearItm.dist - 1]; } else {// BestWayがなかった場合は、アイテムとの距離が2以上ならその方向に進んでみる、1なら停止 print("noBestWay"); pNewPos = mt.get_pPos_whenNoBestWay (init.nearItm, init.playerPos, init.eInfos, init.count); } init.updtMem.setUpdtPlayer( pNewPos, true); init.nearItm.dist--; // sw.WriteLine ("dist: " + init.nearItm.dist + " no: " + init.nearItm.no.ToString()); // itemとの距離が0の場合、該当するアイテムを消し、nearItmを初期化する if (init.nearItm.dist == 0) { // print ("dist0"); // sw.WriteLine (); mt.destroyItem (init.nearItm); init.iInfos [init.nearItm.no].pos = new Vector3 (); init.nearItm = mt.initNearItm (); } } else { // goalを追う if (!trackGoalFlg) { // 最短経路を作成 BestWayToGoal = mt.trackGoal (); // Flgを立てる trackGoalFlg = true; goalCnt = 1; } if (BestWayToGoal.Length > goalCnt) { init.updtMem.setUpdtPlayer (BestWayToGoal [BestWayToGoal.Length - 1 - goalCnt], true); } goalCnt = mt.checkGoal (goalCnt, BestWayToGoal); } } /* 敵の動きを定義 */ int iA, iB, iC, iD, iE; public Vector3 enemyMove(eInfo eInfo, int index, Vector3 pPos) { Vector3 rPos = pPos - eInfo.pos; if (eInfo.type == "A") { if (rPos.y != 0) { Vector3 eNextPos = eInfo.pos + new Vector3 (0, rPos.y / Mathf.Abs (rPos.y)); if (checkEnemyCollider (eNextPos, index)) { return eNextPos; } } if (rPos.x != 0) { Vector3 eNextPos = eInfo.pos + new Vector3 (rPos.x / Mathf.Abs(rPos.x), 0); if (checkEnemyCollider (eNextPos, index)) { return eNextPos; } } Vector3[] moveA= new Vector3[4] { new Vector3(0,-1), new Vector3(-1,0), new Vector3(0,+1), new Vector3(+1,0) }; for (iA = 0; iA < moveA.Length; iA++) { Vector3 eNextPos = eInfo.pos + moveA[iA]; if (checkEnemyCollider (eNextPos, index)) { return eNextPos; } } } else if (eInfo.type == "B") { if (rPos.x != 0) { Vector3 eNextPos = eInfo.pos + new Vector3 (rPos.x / Mathf.Abs (rPos.x), 0); if (checkEnemyCollider (eNextPos, index)) { return eNextPos; } } if (rPos.y != 0) { Vector3 eNextPos = eInfo.pos + new Vector3 (0, rPos.y / Mathf.Abs (rPos.y)); if (checkEnemyCollider (eNextPos, index)) { return eNextPos; } } Vector3[] moveB = new Vector3[4] { new Vector3(0,+1), new Vector3(-1,0), new Vector3(0,-1), new Vector3(+1,0) }; for (iB = 0; iB < moveB.Length; iB++) { Vector3 eNextPos = eInfo.pos + moveB [iB]; if (checkEnemyCollider (eNextPos, index)) { return eNextPos; } } } else if (eInfo.type == "C" || eInfo.type == "D" || eInfo.type == "E") { return mt.enemyMoveCDE (index, eInfo, pPos); } return new Vector3 (); } /* 敵の動きに対するCollider判定 新しい位置が衝突位置でないかどうか確認 */ public bool checkEnemyCollider(Vector3 NextPos, int eIndex) { int m; for (m = 0; m < init.wallPos.Length; m++) { // if (init.wallPos [m].x == NextPos.x) { // //print (" nextPos: " + NextPos + " " + mt.checkVecEqual (init.wallPos [m], NextPos)); // } if (mt.checkVecEqual(init.wallPos [m], NextPos)) { return false; } } for (m = 0; m < init.iInfos.Length; m++) { Vector3 iPos = init.iInfos [m].pos; if (iPos.x != 0 || iPos.y != 0) { if (mt.checkVecEqual (iPos, NextPos)) { return false; } } } if (eIndex >= 0) { for (int i = 0; i < init.eInfos.Length; i++) { if (i != eIndex) { Vector3 ePos_ = init.eInfos [i].pos; float dist = Mathf.Abs (NextPos.x - ePos_.x) + Mathf.Abs (NextPos.y - ePos_.y); // if (this.name == "Player") { // sw.WriteLine ("dist: " + dist.ToString()); // } // 距離が0になってしまうの場合 if (dist == 0) { return false; } // 距離が1の場合 else if (dist == 1) { // eIndex番号の小さい方が優先的に進めるという設定で。 if (mt.checkRankOfEnemy(eIndex, i)) { // 何もしない(番号iの方が遠慮して進むことにする) } else { // enemy_ の次の動きと被った場合false Vector3 e_NextPos = enemyMove (init.eInfos[i], i, init.playerPos); if (e_NextPos == NextPos) { return false; } } } } } } return true; } public Vector3 bfs_enemyMove(eInfo[] eInfos, int index, Vector3 pPos) { Vector3 rPos = pPos - eInfos[index].pos; if (eInfos[index].type == "A") { if (rPos.y != 0) { Vector3 eNextPos = eInfos[index].pos + new Vector3 (0, rPos.y / Mathf.Abs (rPos.y)); if (check_bfsEnemyCollider (eNextPos, index, eInfos)) { return eNextPos; } } if (rPos.x != 0) { Vector3 eNextPos = eInfos[index].pos + new Vector3 (rPos.x / Mathf.Abs(rPos.x), 0); if (check_bfsEnemyCollider (eNextPos, index, eInfos)) { return eNextPos; } } Vector3[] moveA= new Vector3[4] { new Vector3(0,-1), new Vector3(-1,0), new Vector3(0,+1), new Vector3(+1,0) }; for (iA = 0; iA < moveA.Length; iA++) { Vector3 eNextPos = eInfos[index].pos + moveA[iA]; if (check_bfsEnemyCollider (eNextPos, index, eInfos)) { return eNextPos; } } } else if (eInfos[index].type == "B") { if (rPos.x != 0) { Vector3 eNextPos = eInfos[index].pos + new Vector3 (rPos.x / Mathf.Abs (rPos.x), 0); if (check_bfsEnemyCollider (eNextPos, index, eInfos)) { return eNextPos; } } if (rPos.y != 0) { Vector3 eNextPos = eInfos[index].pos + new Vector3 (0, rPos.y / Mathf.Abs (rPos.y)); if (check_bfsEnemyCollider (eNextPos, index, eInfos)) { return eNextPos; } } Vector3[] moveB = new Vector3[4] { new Vector3(0,+1), new Vector3(-1,0), new Vector3(0,-1), new Vector3(+1,0) }; for (iB = 0; iB < moveB.Length; iB++) { Vector3 eNextPos = eInfos[index].pos + moveB [iB]; if (check_bfsEnemyCollider (eNextPos, index, eInfos)) { return eNextPos; } } } else if (eInfos[index].type == "C" || eInfos[index].type == "D" || eInfos[index].type == "E") { return mt.bfs_enemyMoveCDE (index, eInfos, pPos); } return new Vector3 (); } public bool check_bfsEnemyCollider(Vector3 NextPos, int eIndex, eInfo[] eInfos) { int m; for (m = 0; m < init.wallPos.Length; m++) { // if (init.wallPos [m].x == NextPos.x) { // //print (" nextPos: " + NextPos + " " + mt.checkVecEqual (init.wallPos [m], NextPos)); // } if (mt.checkVecEqual(init.wallPos [m], NextPos)) { return false; } } for (m = 0; m < init.iInfos.Length; m++) { Vector3 iPos = init.iInfos [m].pos; if (iPos.x != 0 || iPos.y != 0) { if (mt.checkVecEqual (iPos, NextPos)) { return false; } } } if (eIndex >= 0) { for (int i = 0; i < eInfos.Length; i++) { if (i != eIndex) { Vector3 ePos_ = eInfos [i].pos; float dist = Mathf.Abs (NextPos.x - ePos_.x) + Mathf.Abs (NextPos.y - ePos_.y); // if (this.name == "Player") { // sw.WriteLine ("dist: " + dist.ToString()); // } // 距離が0になってしまうの場合 if (dist == 0) { return false; } // 距離が1の場合 else if (dist == 1) { // eIndex番号の小さい方が優先的に進めるという設定で。 if (mt.checkRankOfEnemy(eIndex, i)) { // 何もしない(番号iの方が遠慮して進むことにする) } else { // enemy_ の次の動きと被った場合false Vector3 e_NextPos = bfs_enemyMove (eInfos, i, NextPos); // sw.WriteLine ("相手のenemyのpos" + ePos_ + " nextPos: " + e_NextPos); if (e_NextPos == NextPos) { return false; } } } } } } return true; } /* playerの動きに対するCollier判定 */ public bool checkPlayerCollider(Vector3 nowPos, Vector3 nextPos, eInfo[] dnme, eInfo[] dnmeNext, Vector3 target) { int m; for (m = 0; m < init.wallPos.Length; m++) { if (mt.checkVecEqual(init.wallPos [m], nextPos)) { return false; } } // if (nowPos == target) { // return false; // } int len = dnme.Length; if (dnme.Length > 0) { // 次移動した時の位置が現在のenemyの位置と一致していた場合、そこも避けなければならない for (int i = 0; i < len; i++) { if (dnmeNext [i].pos == nextPos) { //sw.WriteLine ("次の移動位置が現在のenemyと一致"); return false; } } for (int i = 0; i < len; i++) { if (dnmeNext [i].pos == nowPos && dnme [i].pos == nextPos) { //sw.WriteLine ("入れ替わり交差"); return false; } } // 次の位置がターゲットとも、敵の次の位置とも同じである場合 for (int i = 0; i < len; i++) { if (nextPos == target && nextPos == dnmeNext [i].pos) { //sw.WriteLine ("次の位置がターゲットとも、敵の次の位置とも同じ"); return false; } } } return true; } // Update is called once per frame void Update () { if (!init.KeyPlay) { if (mt.checkFlg ("time", this.name)) { // timeFlg==trueの検知を一瞬にしたいので、即座にfalseにする必要がある mt.makeFlgFalse ("time", this.name); if (this.tag == "player") { sw = new StreamWriter ("Assets/Log/LogData.txt", swFlg); //true=追記 false=上書き swFlg = true; } if (this.tag == "player") { /* プレイヤーの動きを決定 */ playerMove (); // /* 残り時間を更新 */ // mt.updateTime (); } else if (this.name.Substring (0, 5) == "Enemy") { /* 敵の動きを決定 */ int index = Int32.Parse (this.name.Substring (5)); Vector3 ePos = enemyMove (init.eInfos [index], index, init.playerPos); Vector3 e_rPos = ePos - init.eInfos [index].pos; eInfo eInfo = new eInfo (init.eInfos [index].type, ePos, e_rPos); init.updtMem.setUpdtEnemy (index, eInfo, true); } if (this.tag == "player") { sw.Flush (); sw.Close (); } } } else { if (mt.checkFlg("key", this.name)) { if (mt.checkFlg ("time", this.name)) { // timeFlg==trueの検知を一瞬にしたいので、即座にfalseにする必要がある mt.makeFlgFalse ("time", this.name); if (this.tag == "player") { Vector3 pNewPos = mt.get_pPosByKey (); for (int i = 0; i < init.iInfos.Length; i++) { if (mt.checkVecEqual (init.iInfos [i].pos, pNewPos)) { GameObject itemObj = GameObject.Find ("item" + i.ToString ()); Destroy (itemObj); init.iInfos [i].pos = new Vector3 (); break; } } init.updtMem.setUpdtPlayer (pNewPos, true); } else if (this.name.Substring (0, 5) == "Enemy") { int index = Int32.Parse (this.name.Substring (5)); Vector3 ePos = enemyMove (init.eInfos [index], index, init.playerPos); Vector3 e_rPos = ePos - init.eInfos [index].pos; eInfo eInfo = new eInfo (init.eInfos [index].type, ePos, e_rPos); init.updtMem.setUpdtEnemy (index, eInfo, true); } mt.makeFlgFalse ("key", this.name); } } } } }
using System; using System.Collections.Generic; using Microsoft.UnifiedRedisPlatform.Core.Services; using Microsoft.UnifiedRedisPlatform.Core.Services.Models; using Microsoft.UnifiedRedisPlatform.Core.Services.Interfaces; namespace Microsoft.UnifiedRedisPlatform.Core.Logging { internal class ServiceLogger : ILogger { private readonly LogConfiguration _configuration; private readonly IUnifiedRedisPlatformServiceClient _client; public ServiceLogger(string serviceEndpoint, string clusterName, string appName, string appSecret, LogConfiguration configuration) : this(configuration, new UnifiedRedisPlatformServiceClient(serviceEndpoint, clusterName, appName, appSecret)) { } public ServiceLogger(LogConfiguration configuration, IUnifiedRedisPlatformServiceClient client) { _configuration = configuration; _client = client; } public void LogEvent(string eventName, double timeTaken = 0, IDictionary<string, string> properties = null, IDictionary<string, string> metrics = null) { try { var genericLog = GenericLogProvider.CreateFromEvent(eventName, timeTaken, properties, metrics); _client.Log(new List<GenericLog>() { genericLog }, attempt: 1, maxAttempt: _configuration.MaxRetryAttempt).Wait(); } catch (Exception) { } } public void LogException(Exception exception, IDictionary<string, string> properties = null) { try { var genericLog = GenericLogProvider.CreateFromException(exception, properties); _client.Log(new List<GenericLog>() { genericLog }, attempt: 1, maxAttempt: _configuration.MaxRetryAttempt).Wait(); } catch (Exception) { } } public void LogMetric(string metricName, double duration, IDictionary<string, string> properties = null, IDictionary<string, string> metrics = null) { try { var genericLog = GenericLogProvider.CreateFromMetric(metricName, duration, properties, metrics); _client.Log(new List<GenericLog>() { genericLog }, attempt: 1, maxAttempt: _configuration.MaxRetryAttempt).Wait(); } catch (Exception) { } } public void Flush() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.SmtpApi; using System.Web.Helpers; using NewRimLiqourProject.Models; using NewRimLiqourProject.BusinessLogic; using RimLiqourProject.Models; using System.Net.Mail; namespace BnB.BusinessLogic { public class SendEmail { public string Title(RegisterViewModel model) { string title = "Mr"; if (model.Gender == "Female") { title = "Miss/Mrs"; } return title; } //public void SendMail(RegisterViewModel model) //{ // var boddy = new StringBuilder(); // boddy.Append("Dear : " + Title(model) + " " // + model.Name.Substring(0, 1) + " " + model.Surname + "<br>" + // "We're pleased to inform you that you have successfully registered as ...." + "<br>" + // "Please use this Crenditials to access on our websites " + "<br>" + // "UserName = " + model.UserName + "<br>" + // "Password = " + model.Password + "<br>" + // "Thank you :)" // ); // string body_for = boddy.ToString(); // string To_for = model.UserName; // string subject_for = "Registration"; // WebMail.SmtpServer = "pod51014.outlook.com"; // WebMail.SmtpPort = 587; // WebMail.UserName = "21508150@dut4life.ac.za"; // WebMail.Password = "Dut960320"; // WebMail.From = "21508150@dut4life.ac.za"; // WebMail.EnableSsl = true; // try // { // WebMail.Send(to: To_for, subject: subject_for, body: body_for); // } // catch (Exception e) // { // } //} public void mail(string email,OrderDetails order) { ApplicationDbContext db = new ApplicationDbContext(); // var myMessage = new SendGridMessage(); var myMessage = new SendGrid.SendGridMessage(); myMessage.From = new MailAddress("RimLiqourRetails@outlook.com", "Admin"); myMessage.AddTo(email); string subject = "Order Processed"; string html=""; ApplicationUser n = db.Users.ToList().Find(x => x.UserName == order.username); foreach (var c in db.Cart.ToList().FindAll(x=>x.UserId==order.username)) { html = "<h3>Hello " + order.username + ", </h3>" +"<table style=\"border: none; font-family: verdana, tahoma, sans-serif;\">" + "<tr> " + "<th>" + "Item Name " + "</th>" + "<th>" + "Quantity " + "</th>" + "<th>" + "SubTotal " + "</th>" + "<th>" + "DateCreated " + "</th>" + " </tr> </table>" + "<table>" + "<tr>" + "<td>" +c.Products.ProductName +"</td>" + "<td>" + c.Quantity + "</td>" + "<td>" + c.Products.Price * c.Quantity + "</td>" + "<td>" + c.DateCreate + "</td>" + "</tr></table>" +"Total Price :"+order.TotalPrice+"<br/>" + "<p>Regards,<br/> Rim Liquor Retials</p>"; } myMessage.Subject = subject; myMessage.Html = html; var transportWeb = new SendGrid.Web("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"); //credentials = New NetworkCredential("apikey", "<my api pw>"); // var transportWeb = new Web("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"); // var transportWeb = new Web("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"); // Send the email. transportWeb.DeliverAsync(myMessage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace WcfClient { class Program : IDisposable { //static ServiceHostBase asd = new ServiceHostBase() ; static InstanceContext context = new InstanceContext(new AsansörCallback()); static Wcf.AsansorClient server; static UserServiceReference.UserServiceClient User; static void Main(string[] args) { NetNamedPipeBinding binding = new NetNamedPipeBinding(); EndpointAddress address = new EndpointAddress("net.pipe://localhost/asansor"); server = new Wcf.AsansorClient(context,binding,address); server.ClientReg(); User = new UserServiceReference.UserServiceClient(binding,new EndpointAddress("net.pipe://localhost/user")); var asdg = User.Listele(); Console.ReadLine(); } public void Dispose() { server.Close(); } } }
using NUnit.Framework; using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; using System.Threading.Tasks; namespace AutoTest.webdriver { public class BaseTest { protected static Browser Browser = Browser.Instance; [SetUp] // вызывается перед началом запуска всех тестов public virtual void SetUp() { Browser = Browser.Instance; Browser.WindowMaximize(); } [TearDown] //вызывается после завершения всех тестов public virtual void TearDown() { Browser.Quite(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for cFiltro /// </summary> public class cFiltro { public cFiltro() { // // TODO: Add constructor logic here // } public }
using Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Models; using System.Collections.Generic; namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Comparer { public class TqRegistrationEqualityComparer : IEqualityComparer<TqRegistration> { private TqSpecialismRegistrationEqualityComparer _tqSpecialismRegistrationComprarer; public TqRegistrationEqualityComparer() { _tqSpecialismRegistrationComprarer = new TqSpecialismRegistrationEqualityComparer(); } public bool Equals(TqRegistration x, TqRegistration y) { if (x == null && x == null) return true; else if (x == null || x == null) return false; else if (x.GetType() != y.GetType()) return false; else return x.UniqueLearnerNumber == y.UniqueLearnerNumber && string.Equals(x.Firstname, y.Firstname) && string.Equals(x.Lastname, y.Lastname) && x.TqProviderId == y.TqProviderId && x.Status == y.Status; //&& Equals(x.TqSpecialismRegistrations, y.TqSpecialismRegistrations); //return x.UniqueLearnerNumber == y.UniqueLearnerNumber && string.Equals(x.Firstname, y.Firstname) // && string.Equals(x.Lastname, y.Lastname) && Equals(x.DateofBirth, y.DateofBirth) // && x.TqProviderId == y.TqProviderId && Equals(x.StartDate, y.StartDate) && x.Status == y.Status // && Equals(x.TqSpecialismRegistrations, y.TqSpecialismRegistrations); } public int GetHashCode(TqRegistration reg) { unchecked { var hashCode = reg.UniqueLearnerNumber.GetHashCode(); hashCode = (hashCode * 397) ^ (reg.Firstname != null ? reg.Firstname.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (reg.Lastname != null ? reg.Lastname.GetHashCode() : 0); //hashCode = (hashCode * 397) ^ (reg.DateofBirth != null ? reg.DateofBirth.GetHashCode() : 0); hashCode = (hashCode * 397) ^ reg.TqProviderId.GetHashCode(); //hashCode = (hashCode * 397) ^ (reg.StartDate != null ? reg.StartDate.GetHashCode() : 0); hashCode = (hashCode * 397) ^ reg.Status.GetHashCode(); //hashCode = (hashCode * 397) ^ (reg.TqSpecialismRegistrations != null ? reg.TqSpecialismRegistrations.GetHashCode() : 0); foreach(var specReg in reg.TqSpecialismRegistrations) { hashCode = (hashCode * 397) ^ _tqSpecialismRegistrationComprarer.GetHashCode(specReg); } return hashCode; } } } }
using UnityEngine; using UnityEngine.UI; public class ChangeCamera : MonoBehaviour { public Button changeCamBut; int currentCamera = 0; Camera[] allCameras; void Start() { allCameras = new Camera[Camera.allCamerasCount]; Camera.GetAllCameras(allCameras); changeCamBut.onClick.AddListener(ChangeActiveCamera); ChangeActiveCamera(); } void ChangeActiveCamera() { foreach(var cam in allCameras) { cam.enabled = false; } allCameras[currentCamera].enabled = true; currentCamera++; if (currentCamera > allCameras.Length - 1) currentCamera = 0; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace CRL { /// <summary> /// 基类,包含Id, AddTime字段 /// </summary> [Serializable] public abstract class IModelBase : IModel { /// <summary> /// 自增主键 /// </summary> [Attribute.Field(IsPrimaryKey = true)] public int Id { get; set; } [System.Xml.Serialization.XmlIgnore] [NonSerialized] private DateTime addTime = DateTime.Now; /// <summary> /// 添加时间 /// </summary> public DateTime AddTime { get; set; } } /// <summary> /// 基类,不包含任何字段 /// 如果有自定义主键名对象,请继承此类型 /// </summary> [Serializable] //[Attribute.ModelProxy] public abstract class IModel : ICloneable { protected static object lockObj = new object(); public string ToJson() { return CoreHelper.StringHelper.SerializerToJson(this); } //ContextBoundObject 要使用消息代理请继承此对象,使用AOP后,对象将不可调试 /// <summary> /// 数据校验方法 /// </summary> /// <returns></returns> public virtual string CheckData() { return ""; } [System.Xml.Serialization.XmlIgnore] [NonSerialized] Dictionary<string, object> Datas = new Dictionary<string, object>(); /// <summary> /// 获取关联查询的值 /// </summary> /// <param name="key"></param> /// <returns></returns> [Attribute.Field(MappingField = false)] public object this[string key] { get { object obj = null; var a = Datas.TryGetValue(key.ToLower(), out obj); if (!a) { throw new Exception(string.Format("对象:{0}不存在索引值:{1}", GetType(), key)); } return obj; } set { Datas[key.ToLower()] = value; } } #region 检查表 /// <summary> /// 检查索引 /// </summary> /// <param name="helper"></param> /// <returns></returns> public void CheckIndexExists(DBExtend helper) { var list = GetIndexScript(helper); foreach (var item in list) { try { helper.Execute(item); } catch (Exception ero)//出错, { CoreHelper.EventLog.Log(string.Format("创建索引失败:{0}\r\n{1}", ero.Message, item)); } } } internal static string CreateColumn(DBExtend helper, Attribute.FieldAttribute item) { var dbAdapter = helper._DBAdapter; string result = ""; if (string.IsNullOrEmpty(item.ColumnType)) { throw new Exception("ColumnType is null"); } string str = dbAdapter.GetCreateColumnScript(item); string indexScript = ""; if (item.FieldIndexType != Attribute.FieldIndexType.无) { indexScript = dbAdapter.GetColumnIndexScript(item); } try { helper.Execute(str); if (!string.IsNullOrEmpty(indexScript)) { helper.Execute(indexScript); } result += string.Format("创建字段:{0}\r\n", item.Name); } catch (Exception ero) { //CoreHelper.EventLog.Log("创建字段时发生错误:" + ero.Message); result += string.Format("创建字段:{0} 发生错误:{1}\r\n", item.Name, ero.Message); } return result; } /// <summary> /// 检查对应的字段是否存在,不存在则创建 /// </summary> /// <param name="helper"></param> public string CheckColumnExists(DBExtend helper) { string result = ""; var dbAdapter = helper._DBAdapter; List<Attribute.FieldAttribute> columns = GetColumns(dbAdapter); string tableName = TypeCache.GetTableName(this.GetType()); foreach (Attribute.FieldAttribute item in columns) { string sql = dbAdapter.GetSelectTop(item.KeyWordName, "from " + tableName, "", 1); try { helper.Execute(sql); } catch//出错,按没有字段算 { result += CreateColumn(helper, item); } } return result; } internal static void SetColumnDbType(DBAdapter.DBAdapterBase dbAdapter, Attribute.FieldAttribute info, Dictionary<Type, string> dic) { if (info.FieldType != Attribute.FieldType.数据库字段) { return ; } string defaultValue; Type propertyType = info.PropertyType; if (propertyType.FullName.IndexOf("System.") > -1 && !dic.ContainsKey(propertyType)) { throw new Exception(string.Format("找不到对应的字段类型映射 {0} 在 {1}", propertyType, dbAdapter)); } var columnType = dbAdapter.GetColumnType(info, out defaultValue); info.ColumnType = columnType; info.DefaultValue = defaultValue; if (info.ColumnType.Contains("{0}")) { throw new Exception(string.Format("属性:{0} 需要指定长度 ColumnType:{1}", info.Name, info.ColumnType)); } } /// <summary> /// 获取列 /// </summary> /// <returns></returns> List<Attribute.FieldAttribute> GetColumns(DBAdapter.DBAdapterBase dbAdapter) { //var dbAdapter = Base.CurrentDBAdapter; Dictionary<Type, string> dic = dbAdapter.GetFieldMapping(); Type type = this.GetType(); string tableName = TypeCache.GetTableName(type); var typeArry = TypeCache.GetProperties(type, true).Values; var columns = new List<CRL.Attribute.FieldAttribute>(); foreach (var info in typeArry) { if (info.FieldType == Attribute.FieldType.虚拟字段) continue; SetColumnDbType(dbAdapter, info, dic); columns.Add(info); } return columns; } internal List<string> GetIndexScript(DBExtend helper) { var dbAdapter = helper._DBAdapter; List<string> list2 = new List<string>(); List<Attribute.FieldAttribute> columns = GetColumns(dbAdapter); foreach (Attribute.FieldAttribute item in columns) { if (item.FieldIndexType != Attribute.FieldIndexType.无) { //string indexScript = string.Format("CREATE {2} NONCLUSTERED INDEX IX_INDEX_{0}_{1} ON dbo.[{0}]({1})", tableName, item.Name, item.FieldIndexType == Attribute.FieldIndexType.非聚集唯一 ? "UNIQUE" : ""); string indexScript = dbAdapter.GetColumnIndexScript(item); list2.Add(indexScript); } } return list2; } /// <summary> /// 创建表 /// </summary> /// <param name="helper"></param> /// <returns></returns> public string CreateTable(DBExtend helper) { string msg; CreateTable(helper, out msg); return msg; } /// <summary> /// 创建表 /// 会检查表是否存在,如果存在则检查字段 /// </summary> /// <param name="helper"></param> /// <param name="message"></param> /// <returns></returns> public bool CreateTable(DBExtend helper, out string message) { var dbAdapter = helper._DBAdapter; message = ""; TypeCache.SetDBAdapterCache(GetType(),dbAdapter); string tableName = TypeCache.GetTableName(GetType()); string sql = dbAdapter.GetSelectTop("0", "from " + tableName, "", 1); bool needCreate = false; try { //检查表是否存在 helper.Execute(sql); } catch { needCreate = true; } if (needCreate) { List<string> list = new List<string>(); try { List<Attribute.FieldAttribute> columns = GetColumns(dbAdapter); dbAdapter.CreateTable(helper, columns, tableName); message = string.Format("创建表:{0}\r\n", TypeCache.GetTableName(GetType())); CheckIndexExists(helper); return true; } catch (Exception ero) { message = "创建表时发生错误 类型{0} {1}\r\n"; message = string.Format(message, GetType(), ero.Message); throw new Exception(message); return false; } CoreHelper.EventLog.Log(message, "", false); } else { message = CheckColumnExists(helper); } return true; } #endregion #region 更新值判断 /// <summary> /// 存放原始克隆 /// </summary> [System.Xml.Serialization.XmlIgnore] [NonSerialized] private object _originClone = null; [System.Xml.Serialization.XmlIgnore] [Attribute.Field(MappingField = false)] internal object OriginClone { get { return _originClone; } set { _originClone = value; } } [System.Xml.Serialization.XmlIgnore] [NonSerialized] bool boundChange = true; [System.Xml.Serialization.XmlIgnore] internal bool BoundChange { get { return boundChange; } set { boundChange = value; } } [System.Xml.Serialization.XmlIgnore] [NonSerialized] ParameCollection changes = new ParameCollection(); [Attribute.Field(MappingField = false)] [System.Xml.Serialization.XmlIgnore] internal ParameCollection Changes { get { return changes; } set { changes = value; } } /// <summary> /// 表示值被更改了 /// </summary> /// <param name="name"></param> /// <param name="value"></param> internal protected void SetChanges(string name,object value) { if (!BoundChange) return; if (name.ToLower() == "boundchange") return; Changes[name] = value; } #endregion /// <summary> /// 创建当前对象的浅表副本 /// </summary> /// <returns></returns> public object Clone() { return MemberwiseClone(); } [System.Xml.Serialization.XmlIgnore] [NonSerialized] string modelKey = null; internal string GetModelKey() { if (modelKey == null) { var type = GetType(); var tab = TypeCache.GetTable(type); modelKey = string.Format("{0}_{1}", type, tab.PrimaryKey.GetValue(this)); } return modelKey; } internal int GetpPrimaryKeyValue() { var primaryKey = TypeCache.GetTable(GetType()).PrimaryKey; var keyValue = (int)primaryKey.GetValue(this); return keyValue; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Restaurant.Models { public class Menu2 { public int Menu2ID { get; set; } public string NameOfRest2 { get; set; } public string Type2 { get; set; } public string Name2 { get; set; } public int Stars2 { get; set; } [Required] [Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")] public decimal Price2 { get; set; } public string Description2 { get; set; } public int Ingredients2 { get; set; } public string Location { get; set; } public string TypeOfMeat { get; set; } } }
using Moq; using RocketLoopCoreApi.Models; using RocketLoopCoreApi.Repositories.Interfaces; using RocketLoopCoreApi.Services; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xunit; namespace RocketLoopXUnit.Services { public class UserServiceTest { protected UserService _service { get; } protected Mock<IUserRepository> _userRepositoryMock { get; } public UserServiceTest() { _userRepositoryMock = new Mock<IUserRepository>(); _service = new UserService(_userRepositoryMock.Object); } [Fact] public async Task Should_return_all_users() { // Arrange var expectedUsers = new ReadOnlyCollection<User>(new List<User> { new User { Id = 1, Name = "User 1" }, new User { Id = 2, Name = "User 2" }, new User { Id = 3, Name = "User 3" } }); _userRepositoryMock .Setup(x => x.GetAllUsersAsync()) .ReturnsAsync(expectedUsers); // Act var result = await _service.GetAllUsersAsync(); // Assert Assert.Same(expectedUsers, result); } } }
using Alabo.Cache; using Alabo.Dependency; using Alabo.Framework.Basic.Notifications.Domain.Services; using Alabo.Regexs; using Alabo.Schedules.Job; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Quartz; using System; using System.Collections.Generic; using System.Threading.Tasks; using ZKCloud.Open; using ZKCloud.Open.ApiBase.Configuration; using ZKCloud.Open.ApiBase.Models; using ZKCloud.Open.Message.Models; using ZKCloud.Open.Message.Services; using MessageQueue = Alabo.Framework.Basic.Notifications.Domain.Entities.MessageQueue; namespace Alabo.Framework.Basic.Notifications.Job { public class MessageQueueJob : JobBase { private IAdminMeesageApiClient _adminMessageApiClient; private IMessageApiClient _messageApiClient; private RestClientConfiguration _restClientConfiugration; public override TimeSpan? GetInterval() { return TimeSpan.FromSeconds(5); } protected override async Task Execute(IJobExecutionContext context, IScope scope) { FirstWaiter(context, scope, TimeSpan.FromMinutes(5)); var config = scope.Resolve<IConfiguration>(); _restClientConfiugration = new RestClientConfiguration(config); _messageApiClient = new MessageApiClient(_restClientConfiugration.OpenApiUrl); _adminMessageApiClient = new AdminMessageApiClient(_restClientConfiugration.OpenApiUrl); var objectCache = scope.Resolve<IObjectCache>(); objectCache.TryGet("MessageIsAllSend_Cache", out bool sendState); if (sendState == false) { scope.Resolve<IObjectCache>().Set("MessageIsAllSend_Cache", true); var messageQueueService = scope.Resolve<IMessageQueueService>(); var unHandledIdList = messageQueueService.GetUnHandledIdList(); if (unHandledIdList != null && unHandledIdList.Count > 0) { foreach (var id in unHandledIdList) { try { await HandleQueueAsync(messageQueueService, id); } catch (Exception ex) { scope.Resolve<IObjectCache>().Set("MessageIsAllSend_Cache", false); throw new ArgumentNullException(ex.Message); } } } } } private async Task HandleQueueAsync(IMessageQueueService messageQueueService, long queueId) { var queue = messageQueueService.GetSingle(queueId); // var result = await _adminMessageApiClient.GetAccount(_serverAuthenticationManager.Token.Token); if (queue == null) { throw new MessageQueueHandleException(queueId, $"message queue with id {queueId} not found."); } RegexHelper.CheckMobile(queue.Mobile); MessageResult messageResult = null; if (queue.TemplateCode > 0) { messageResult = await SendTemplateAsync(queue); } else { messageResult = await SendRawAsync(queue); } if (messageResult == null) { messageQueueService.ErrorQueue(queueId, "message send with no result!"); } else if (messageResult.Type == ResultType.Success) { messageQueueService.HandleQueueAndUpdateContent(queueId, "message send open service success!", messageResult.Message); } else { messageQueueService.ErrorQueue(queueId, $"message send {messageResult.Type}!", messageResult.Message); } } /// <summary> /// 发送单条 使用异步方法发送短信 /// </summary> /// <param name="queue"></param> private async Task<MessageResult> SendRawAsync(MessageQueue queue) { if (string.IsNullOrWhiteSpace(queue.Mobile)) { throw new ArgumentNullException(nameof(queue.Mobile)); } if (string.IsNullOrWhiteSpace(queue.Content)) { throw new ArgumentNullException(nameof(queue.Content)); } RegexHelper.CheckMobile(queue.Mobile); var result = await _messageApiClient.SendRawAsync(Token.Token, queue.Mobile, queue.Content, queue.IpAdress); if (result.Status != ResultStatus.Success) { throw new ServerApiException(result.Status, result.MessageCode, result.Message); } return ParseResult(result); } private async Task<MessageResult> SendTemplateAsync(MessageQueue queue) { if (string.IsNullOrWhiteSpace(queue.Mobile)) { throw new ArgumentNullException(nameof(queue.Mobile)); } if (queue.TemplateCode <= 0) { throw new ArgumentNullException(nameof(queue.TemplateCode)); } var template = GetTemplate(queue.TemplateCode); if (template == null) { throw new ArgumentNullException(nameof(template)); } if (template.Status != MessageTemplateStatus.Verified) { throw new ArgumentNullException(nameof(template)); } RegexHelper.CheckMobile(queue.Mobile); var parameters = JsonConvert.DeserializeObject<IDictionary<string, string>>(queue.Parameters); var result = await _messageApiClient.SendTemplateAsync(Token.Token, queue.Mobile, template.Id, queue.IpAdress, parameters); if (result.Status != ResultStatus.Success) { throw new ServerApiException(result.Status, result.MessageCode, result.Message); } return ParseResult(result); } /// <summary> /// 根据模板编号获取模板 /// </summary> /// <param name="code"></param> public MessageTemplate GetTemplate(long code) { if (code <= 0) { throw new ArgumentNullException(nameof(code)); } var result = _messageApiClient.GetTemplate(Token.Token, code); var entity = result.Result.Result; return entity; } private MessageResult ParseResult(ApiResult rawResult) { var messageResult = new MessageResult(); if (rawResult.Status == ResultStatus.Success) { messageResult.Message = "send to open success"; messageResult.Type = ResultType.Success; } else { messageResult.Message = "send to open faild"; messageResult.Type = ResultType.Faild; } return messageResult; } } }
using System.Collections.Generic; using Moq; using Otiport.API.Controllers; using Otiport.API.Services; using System.Threading.Tasks; using Xunit; using AutoFixture; using FluentAssertions; using Microsoft.AspNetCore.Mvc; using System.Net; using Otiport.API.Contract.Request.Common; using Otiport.API.Contract.Response.Common; using Otiport.API.Data.Entities.AddressInformations; namespace Otiport.Tests.UnitTests.Controllers { public class AddressInformationControllerTest : TestBase { private readonly AddressInformationsController addressInformationController; private readonly Mock<IAddressInformationService> addressServiceMock; public AddressInformationControllerTest() { addressServiceMock = MockFor<IAddressInformationService>(); addressInformationController = new AddressInformationsController(addressServiceMock.Object); } [Fact] public async Task GetCountries_Should_Return_Value() { //Arrange var getCountriesResponse = FixtureRepository.Create<GetCountriesResponse>(); addressServiceMock.Setup(x => x.GetCountriesAsync()).Returns(Task.FromResult<GetCountriesResponse>(getCountriesResponse)); //Act var result = await addressInformationController.GetCountries(); //Assert result.Should().NotBeNull(); result.Should().BeOfType<ObjectResult>(); var response = (ObjectResult)result; response.StatusCode.Should().Be((int)HttpStatusCode.OK); } [Fact] public async Task GetCities_Should_Return_Value() { //Arrange var getCitiesResponse = FixtureRepository.Create<GetCitiesResponse>(); var getCitiesRequest = FixtureRepository.Create<GetCitiesRequest>(); addressServiceMock.Setup(x => x.GetCitiesAsync(getCitiesRequest)).Returns(Task.FromResult<GetCitiesResponse>(getCitiesResponse)); //Act var result = await addressInformationController.GetCities(getCitiesRequest); //Assert result.Should().NotBeNull(); result.Should().BeOfType<ObjectResult>(); var response = (ObjectResult)result; response.StatusCode.Should().Be((int)HttpStatusCode.OK); } [Fact] public async Task GetDisctricts_Should_Return_Value() { //Arrange var getDistrictsRequest = FixtureRepository.Create<GetDistrictsRequest>(); var getDistrictsResponse = FixtureRepository.Create<GetDistrictsResponse>(); addressServiceMock.Setup(x => x.GetDistrictsAsync(getDistrictsRequest)).Returns(Task.FromResult<GetDistrictsResponse>(getDistrictsResponse)); //Act var result = await addressInformationController.GetDistricts(getDistrictsRequest); //Assert result.Should().NotBeNull(); result.Should().BeOfType<ObjectResult>(); var response = (ObjectResult)result; response.StatusCode.Should().Be((int)HttpStatusCode.OK); } } }
using UnityEngine; namespace AtomosZ.Cubeshots.WeaponSystems { public class BasicBullet : MonoBehaviour { public float speed; public int damage = 10; public float timeToLive = 3; [HideInInspector] public IShmupActor owner; [HideInInspector] public Vector3 direction; private float timeAlive; private float curve = 0; private Camera mainCamera; private Transform player; void Start() { mainCamera = Camera.main; gameObject.SetActive(false); enabled = false; player = GameObject.FindGameObjectWithTag(Tags.PLAYER).transform; } public void SetOwner(IShmupActor actor) { owner = actor; } public void Fire(Vector3 position, Vector3 direction, float curveAmount) { transform.localPosition = position; this.direction = direction; curve = curveAmount; timeAlive = 0; enabled = true; gameObject.SetActive(true); } void Update() { transform.localPosition = transform.localPosition + direction * speed * Time.deltaTime; direction = Quaternion.Euler(0, 0, curve * Time.deltaTime) * direction; timeAlive += Time.deltaTime; Debug.DrawLine(transform.localPosition, player.localPosition); Vector3 vpPos = mainCamera.WorldToViewportPoint(transform.localPosition); if (vpPos.x < -.5f || vpPos.y < -.5f || vpPos.x > 1.5f || vpPos.y > 1.5f) Disable(); } void OnTriggerEnter2D(Collider2D collision) { if ((collision.CompareTag(Tags.PLAYER) && CompareTag(Tags.ENEMY_BULLET)) || (collision.CompareTag(Tags.ENEMY) && CompareTag(Tags.PLAYER_BULLET))) { collision.GetComponent<IShmupActor>().TakeDamage(damage); Disable(); } } private void Disable() { gameObject.SetActive(false); enabled = false; owner.BulletBecameInactive(this); } } }
using System.Linq; using System.Threading.Tasks; using Lanches.Web.Context; using Lanches.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Lanches.Web.Areas.Admin.Controllers { [Area ("Admin")] [Authorize (Roles = "Admin")] public class AdminCategoriasController : Controller { private readonly AppDbContext _context; public AdminCategoriasController (AppDbContext context) { _context = context; } // GET: Admin/AdminCategorias public async Task<IActionResult> Index () { return View (await _context.Categorias.ToListAsync ()); } // GET: Admin/AdminCategorias/Details/5 public async Task<IActionResult> Details (int? id) { if (id == null) { return NotFound (); } var categoria = await _context.Categorias .SingleOrDefaultAsync (m => m.CategoriaId == id); if (categoria == null) { return NotFound (); } return View (categoria); } // GET: Admin/AdminCategorias/Create public IActionResult Create () { return View (); } // POST: Admin/AdminCategorias/Create // To protect from overposting attacks, please 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 ("CategoriaId,CategoriaNome,Descricao")] Categoria categoria) { if (ModelState.IsValid) { _context.Add (categoria); await _context.SaveChangesAsync (); return RedirectToAction (nameof (Index)); } return View (categoria); } // GET: Admin/AdminCategorias/Edit/5 public async Task<IActionResult> Edit (int? id) { if (id == null) { return NotFound (); } var categoria = await _context.Categorias.SingleOrDefaultAsync (m => m.CategoriaId == id); if (categoria == null) { return NotFound (); } return View (categoria); } // POST: Admin/AdminCategorias/Edit/5 // To protect from overposting attacks, please 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 ("CategoriaId,CategoriaNome,Descricao")] Categoria categoria) { if (id != categoria.CategoriaId) { return NotFound (); } if (ModelState.IsValid) { try { _context.Update (categoria); await _context.SaveChangesAsync (); } catch (DbUpdateConcurrencyException) { if (!CategoriaExists (categoria.CategoriaId)) { return NotFound (); } else { throw; } } return RedirectToAction (nameof (Index)); } return View (categoria); } // GET: Admin/AdminCategorias/Delete/5 public async Task<IActionResult> Delete (int? id) { if (id == null) { return NotFound (); } var categoria = await _context.Categorias .SingleOrDefaultAsync (m => m.CategoriaId == id); if (categoria == null) { return NotFound (); } return View (categoria); } // POST: Admin/AdminCategorias/Delete/5 [HttpPost, ActionName ("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed (int id) { var categoria = await _context.Categorias.SingleOrDefaultAsync (m => m.CategoriaId == id); _context.Categorias.Remove (categoria); await _context.SaveChangesAsync (); return RedirectToAction (nameof (Index)); } private bool CategoriaExists (int id) { return _context.Categorias.Any (e => e.CategoriaId == id); } } }
using System; using Xamarin.Forms; namespace PluginSample { public partial class PluginSamplePage : ContentPage { public PluginSamplePage() { InitializeComponent(); } private void OnClicked(object sender, EventArgs e) { this.label.Text = AssemblyTimeStamp.TimeStampUtil.GetAssemblyTimeStamp().ToString(); } } }
using AutoMapper; using Moq; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using WebApplication1; using WebApplication1.Profiles; namespace WebApplication1Test { [TestFixture] class AutoMapperTests { private Mock<IMapper> mapperMock; [SetUp] public void Setup() { mapperMock = new Mock<IMapper>(); } [Test] public void BuildingProfiles_ItShouldCorrectConfigured() { var config = new MapperConfiguration(cfg => cfg.AddProfile<BuildingProfiles>()); config.AssertConfigurationIsValid(); } [Test] public void PersonalAccountProfiles_ItShouldCorrectConfigured() { var config = new MapperConfiguration(cfg => cfg.AddProfile<PersonalAccountProfiles>()); config.AssertConfigurationIsValid(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class player : MonoBehaviour { public GameObject food; public SphereCollider FoodCollider; int hunger = 30; void Start() { } #if false void OnCollisionEnter(Collision Collision) { if (Collision.gameObject.tag == "Food") { Console.WriteLine("Press 'E' To Use"); if (Input.GetAxis("Submit")> 0) { Destroy(Collision.gameObject); } hunger = 30; } if (Collision.gameObject.tag == "Fire") { Console.WriteLine("Press 'E' To Light"); if (Input.GetAxis("Submit")>0) { RemoveItem.Inventory(Stick); AddItem.Inventory(Torch); } if (Collision.gameObject.tag == "tree") { Console.WriteLine("Press 'F' to Burn"); if (Input.GetAxis("axis")> 0) { Destroy(gameObject(Tree)); Create(gameObject(Fire)); } } } if (Collision.gameObject.tag == "Water") { Console.WriteLine("Press 'E' to collect"); if (Input.GetAxis("Submit")>0) { RemoveItem.Inventory(Bucket); AddItem.Inventory(Water); } } if (Collision.gameObject.tag == "Fire") { Console.WriteLine("Press 'Q' to Douse"); if (Input.GetAxis("axis")>0) { RemoveItem.Inventory(Water); AddItem.Inventory(Bucket); Destroy(gameObject(Fire)); } } } #endif private void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Recruit") { Instantiate(this, other.transform.position, other.transform.rotation); Destroy(other); } } void Hunger() { Debug.Log (hunger); hunger--; if (hunger == 0) { //void Destroy(Object Follower) } } /*void Rock() { if (OnCollisionEnter.gameObject.tag == "Rock") { Console.WriteLine("Press 'E' to Collect"); if (input.GetAxis("Submit")>0) { AddItem.Inventory(Rock); } } }*/ }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ContinueBtn : MonoBehaviour { private Menu menu; void Awake() { menu = FindObjectOfType<Menu>(); } public void ButtonOnClick() { menu.gameObject.SetActive(true); menu.SetShowFlag(); } }