text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class WriteLog : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["user"] == null) Response.Redirect("Login.aspx"); } protected void btnPublish_Click(object sender, EventArgs e) { string headline = txtHeadline.Text; string content = txtContent.Text; if (headline.Length == 0 || content.Length == 0) Response.Write("<script>alert('输入不能为空!')</script>"); else { Users user = (Users)Session["user"]; DateTime time = DateTime.Now; string sql = "insert into Log values('" + user.Userid + "',N'" + headline + "',N'" + content + "','" + time + "')"; DataClass.Save(sql); Response.Write("<script>alert('发表成功!');location='Log.aspx'</script>"); } } }
using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; namespace LeetCodeTests { public abstract class Problem_0021 { /* Merge two sorted linked lists and return it as a new list.The new list should be made by splicing together the nodes of the first two lists. */ public static void Test() { Solution sol = new Solution(); /* var input = new int[] { 2, 7, 11, 15 }; Console.WriteLine($"Input array: {string.Join(", ", input)}"); */ ListNode l1 = Utils.GenerateList(new int[] { 1, 3, 5, 7, 9 }); ListNode l2 = Utils.GenerateList(new int[] { 2, 4, 6, 8 }); Console.WriteLine($"Merge two list:\n\t{l1?.PrintList()}\n\t{l2?.PrintList()}\nResult: {sol.MergeTwoLists(l1, l2)?.PrintList()}"); } public class Solution { public ListNode MergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = null; ListNode tail = null; ListNode t1 = l1; ListNode t2 = l2; if (t1.val < t2.val) { head = t1; t1 = t1.next; } else { head = t2; t2 = t2.next; } tail = head; while ((t1 != null) || (t2 != null)) { if ((t1 != null) && (t1.val <= (t2?.val ?? int.MaxValue))) { tail.next = t1; t1 = t1.next; } else { tail.next = t2; t2 = t2?.next; } tail = tail.next; } return head; } } }//public abstract class Problem_ }
using System; namespace ApartmentApps.Api { public interface ITimeZone { DateTime Now { get; } DateTime Today { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IRAP.Global; using IRAPShared; namespace IRAP.Entity.MDM.Tables { /// <summary> /// T216 一般属性 /// </summary> [IRAPDB(TableName = "IRAPMDM..GenAttr_ProcessOperation")] public class GenAttr_ProcessOperation { private long partitioningKey = 0; private int entityID = 0; private byte[] operationSketch; [IRAPKey()] public long PartitioningKey { get { return partitioningKey; } set { partitioningKey = value; } } [IRAPKey()] public int EntityID { get { return entityID; } set { entityID = value; } } public byte[] OperationSketch { get { return operationSketch; } set { operationSketch = value; } } //[IRAPORMMap(ORMMap = false)] //public Image OperationImage //{ // get { return Tools.BytesToImage(operationSketch); } //} public GenAttr_ProcessOperation Clone() { return this.MemberwiseClone() as GenAttr_ProcessOperation; } } }
namespace Tsutsuji.Updater.Screens { public enum UpdaterType { /// <summary> Applies the updater and installer if used for the first time. </summary> First, /// <summary> Only applies the updater as if the user has used it more than once. </summary> Update } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class GlobalData { private static int timePoint = 0; private static int questionNumber; private static float startPosition = -3.48f; private static string lastScene = "HomeExt"; private static bool dreamDefeated = false; private static int dayCount = 0; private static int currentNumOfActions; private static int baseNumOfActions = 6; // Prevents setting to another value private static bool isTired; private static bool isVeryTired; private static bool isWellRested; private static bool isInMessage; private static bool TalkedToArtist = false; private static bool TalkedToPastor = false; private static bool TalkedToBreakUp = false; private static bool TalkedToDrunk = false; private static bool TalkedToFat = false; private static bool TalkedToPoor = false; private static bool day1TempFix = false; public static bool tempFix { get { return day1TempFix; } set { day1TempFix = value; } } public static int InAction { get { return baseNumOfActions; } set { baseNumOfActions = 6; } } public static bool GetSetVeryTired { get { return isVeryTired; } set { isVeryTired = value; } } public static bool InMessage { get { return isInMessage; } set { isInMessage = value; } } // Needed to prevent action ending scene auto to change scenes. public static int GetSetCurrentActions { get { return currentNumOfActions; } set { currentNumOfActions = value; } } public static bool GetSetTired { get { return isTired; } set { isTired = value; } } public static bool GetSetWellRested { get { return isWellRested; } set { isWellRested = value; } } public static int TimeOfDay { get { return timePoint; } set { timePoint = value; } } public static bool talkedToArtist { get { return TalkedToArtist; } set { TalkedToArtist = value; } } public static bool talkedToPoor { get { return TalkedToPoor; } set { TalkedToPoor = value; } } public static bool talkedToFat { get { return TalkedToFat; } set { TalkedToFat = value; } } public static bool talkedToDrunk { get { return TalkedToDrunk; } set { TalkedToDrunk = value; } } public static bool talkedToPastor { get { return TalkedToPastor; } set { TalkedToPastor = value; } } public static bool talkedToBreakUp { get { return TalkedToBreakUp; } set { TalkedToBreakUp = value; } } public static float StartPos { get { return startPosition; } set { startPosition = value; } } public static string LastScene { get { return lastScene; } set { lastScene = value; } } public static int Day { get { return dayCount; } set { dayCount = value; } } public static bool Victory { get { return dreamDefeated; } set { dreamDefeated = value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OcTur.DTO { /// <summary> /// O usuário DTO armazena as informações referentes ao usuário como Nome, /// Data de Nascimento, Senha de Usuário, Nome de Usuário e Foto de Usuário. /// Para transferir entre as Classes Model, Control e View /// </summary> class UsuarioDTO/* As classes são divididas em Dados, Metodos e as Propriedades * os atribudos são dados que são acessados por meios de metódos * já as propriedades são um hibridos entre Dados e Metodos que já possuem * seus proprios meios para acessa-las. Padrão de projeto sempre iniciar com letra Maiuscula*/ { public string Nome { get; set; } public string Senha { get; set; } public string Usuario { get; set; } public string DataNascimento { get; set;} public int Idioma { get; set; } public byte[] Foto { get; set; } public bool [] Id { get; set; } public int Papel { get; set; } } }
using System.Linq.Expressions; using ApartmentApps.Data; using ApartmentApps.Data.Repository; using Korzh.EasyQuery.Db; using Microsoft.AspNet.Identity; using Ninject; namespace ApartmentApps.Portal.Controllers { public class BuildingService : StandardCrudService<Building> { public BuildingService(IKernel kernel, IRepository<Building> repository) : base(kernel, repository) { } public override string DefaultOrderBy => "Name"; public DbQuery All() { return CreateQuery("All"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChatApp { //now can be serialized [Serializable] //avoid referencing & instead copy to avoid struct Packet //problems with color changing when sending a colored msg { public string nickname; public string message; public ConsoleColor textColor; } }
using Microsoft.EntityFrameworkCore; namespace DataLibrary { public partial class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { } public DbSet<Product> Products { get; set; } public DbSet<ProductType> ProductTypes { get; set; } } }
// Copyright (c) 2020, mParticle, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using MP.Json; using MP.Json.Validation; using Xunit; namespace JsonSchemaTestSuite.Draft4 { public class RefRemote { /// <summary> /// 1 - remote ref /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "remote ref valid", "1", true )] [InlineData( "remote ref invalid", "'a'", false )] public void RemoteRef(string desc, string data, bool expected) { // remote ref Console.Error.WriteLine(desc); string schemaData = "{ '$ref':'http://localhost:1234/integer.json' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 2 - fragment within remote ref /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "remote fragment valid", "1", true )] [InlineData( "remote fragment invalid", "'a'", false )] public void FragmentWithinRemoteRef(string desc, string data, bool expected) { // fragment within remote ref Console.Error.WriteLine(desc); string schemaData = "{ '$ref':'http://localhost:1234/subSchemas.json#/integer' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 3 - ref within remote ref /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "ref within ref valid", "1", true )] [InlineData( "ref within ref invalid", "'a'", false )] public void RefWithinRemoteRef(string desc, string data, bool expected) { // ref within remote ref Console.Error.WriteLine(desc); string schemaData = "{ '$ref':'http://localhost:1234/subSchemas.json#/refToInteger' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 4 - base URI change /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "base URI change ref valid", "[ [ 1 ] ]", true )] [InlineData( "base URI change ref invalid", "[ [ 'a' ] ]", false )] public void BaseURIChange(string desc, string data, bool expected) { // base URI change Console.Error.WriteLine(desc); string schemaData = "{ 'id':'http://localhost:1234/', 'items':{ 'id':'folder/', 'items':{ '$ref':'folderInteger.json' } } }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 5 - base URI change - change folder /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "number is valid", "{ 'list':[ 1 ] }", true )] [InlineData( "string is invalid", "{ 'list':[ 'a' ] }", false )] public void BaseURIChangeChangeFolder(string desc, string data, bool expected) { // base URI change - change folder Console.Error.WriteLine(desc); string schemaData = "{ 'definitions':{ 'baz':{ 'id':'folder/', 'items':{ '$ref':'folderInteger.json' }, 'type':'array' } }, 'id':'http://localhost:1234/scope_change_defs1.json', 'properties':{ 'list':{ '$ref':'#/definitions/baz' } }, 'type':'object' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 6 - base URI change - change folder in subschema /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "number is valid", "{ 'list':[ 1 ] }", true )] [InlineData( "string is invalid", "{ 'list':[ 'a' ] }", false )] public void BaseURIChangeChangeFolderInSubschema(string desc, string data, bool expected) { // base URI change - change folder in subschema Console.Error.WriteLine(desc); string schemaData = "{ 'definitions':{ 'baz':{ 'definitions':{ 'bar':{ 'items':{ '$ref':'folderInteger.json' }, 'type':'array' } }, 'id':'folder/' } }, 'id':'http://localhost:1234/scope_change_defs2.json', 'properties':{ 'list':{ '$ref':'#/definitions/baz/definitions/bar' } }, 'type':'object' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 7 - root ref in remote ref /// </summary> [Theory(Skip = "Work in Progress")] [InlineData( "string is valid", "{ 'name':'foo' }", true )] [InlineData( "null is valid", "{ 'name':null }", true )] [InlineData( "object is invalid", "{ 'name':{ 'name':null } }", false )] public void RootRefInRemoteRef(string desc, string data, bool expected) { // root ref in remote ref Console.Error.WriteLine(desc); string schemaData = "{ 'id':'http://localhost:1234/object', 'properties':{ 'name':{ '$ref':'name.json#/definitions/orNull' } }, 'type':'object' }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } } }
using System.Collections; using System.Threading; using UnityEngine; public class TimerEventArgs { public Timer timer; public TimerEventArgs(Timer timer) { this.timer = timer; } } public class Timer : MonoBehaviour { public LifeTime lifeTime; public int Day { get { return lifeTime.Day; } set { lifeTime.Day = value; } } public int Month { get { return lifeTime.Month; } set { lifeTime.Month = value; } } public int Year { get { return lifeTime.Year; } set { lifeTime.Year = value; } } public int Hour { get { return lifeTime.Hour; } set { lifeTime.Hour = value; } } public int Minute { get { return lifeTime.Minute; } set { lifeTime.Minute = value; } } public int Speed = 1; public float Second { get { return lifeTime.Second; } set { lifeTime.Second = (int)value; } } public static readonly int DayPerMonth = 7; public static readonly int MonthPerYear = 12; public int SecondPerReal = 16; public static readonly int MinuteSize = 60; public static readonly int HourSize = 60; public static readonly int DaySize = 3; public bool Running; public delegate void TimerHandler(object sender, TimerEventArgs time); public event TimerHandler DayEvent; public event TimerHandler HourEvent; public event TimerHandler MinuteEvent; public event TimerHandler MonthEvent; private Thread timer; private void Start() { lifeTime = new LifeTime(1, 1, 1, 0, 0, 0); Running = true; } public override string ToString() { return lifeTime.ToString(); } public void Update() { if (Running) { //Thread.Sleep(1000 / (SecondPerReal * Speed)); StartCoroutine("Ticking"); } } IEnumerator Ticking() { Running = false; yield return new WaitForSecondsRealtime(1f); CalculateTime(); Running = true; } public void CalculateTime() { Day++; OnDayPassed(); if (Day > DayPerMonth * Month) { Month++; OnMonthPassed(); } /*Second++; if (Second >= MinuteSize) { Minute++; Second = Second - MinuteSize; OnMinutePassed(); } if (Minute >= HourSize) { Hour++; Minute = Minute - HourSize; OnHourPassed(); } if (Day > DayPerMonth) { Month++; Day = 1; } if (Month >= MonthPerYear) { Year++; Month = 1; }*/ } public void OnMinutePassed() { MinuteEvent?.Invoke(this, new TimerEventArgs(this)); } public void OnHourPassed() { HourEvent?.Invoke(this, new TimerEventArgs(this)); } public void OnDayPassed() { Debug.Log("Day passed"); DayEvent?.Invoke(this, new TimerEventArgs(this)); } public void OnMonthPassed() { Debug.Log("Week passed"); MonthEvent?.Invoke(this, new TimerEventArgs(this)); } }
using System; using System.Collections.Generic; using System.Text; namespace NetCore.Service { public class Query { public string FieldName { get; set; } public string Value { get; set; } } }
using Alabo.Cloud.Shop.Favorites.Domain.Entities; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Cloud.Shop.Favorites.Domain.Repositories { public interface IFavoriteRepository : IRepository<Favorite, ObjectId> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TestWebApp.Database; namespace TestWebApp.Controllers { public class HomeController : Controller { protected readonly BloggingContext _dbContext; public HomeController(BloggingContext dbContext) { _dbContext = dbContext; } // GET: /<controller>/ public IActionResult Index() { var res = _dbContext.Blogs.ToList(); return View(); } } }
namespace WinAppDriver.Handlers { using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; [Route("GET", "/session/:sessionId/screenshot")] internal class ScreenshotHandler : IHandler { public object Handle(Dictionary<string, string> urlParams, string body, ref ISession session) { return Convert.ToBase64String(this.TakeScreenshotAsPng()); } private byte[] TakeScreenshotAsPng() { var bounds = Screen.PrimaryScreen.Bounds; using (var bmp = new Bitmap(bounds.Width, bounds.Height)) { using (var g = Graphics.FromImage(bmp)) { g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); var stream = new MemoryStream(); bmp.Save(stream, ImageFormat.Png); return stream.ToArray(); } } } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace MergeSort { public class FrogJumpService { public void ConsoleRun() { //Int var line = string.Empty; while (line.ToLower() != "exit") { Console.WriteLine("Enter start destination and jump distance: "); line = Console.ReadLine(); if (line == "exit") break; else { var start = Convert.ToInt32(line.Split(" ")[0]); var destination = Convert.ToInt32(line.Split(" ")[1]); var jumpDistance =Convert.ToInt32(line.Split(" ")[2]); Console.WriteLine($"Answer: {GetNumberOfJumps(start, destination, jumpDistance)}"); } } } public int GetNumberOfJumps(int start, int destination, int jumpDistance) { //Subtract start from destination for required distance //Divide required distance by jump distance //Return ceiling return (int)Math.Ceiling((destination - start) / (decimal) jumpDistance ); } } [TestFixture] public class FrogJumpServiceTests { public FrogJumpService service = new FrogJumpService(); [Test] public void Test1() { var x = 10; var y = 85; var d = 30; var expected = 3; Assert.AreEqual(expected, service.GetNumberOfJumps(x, y, d)); } [Test] public void Test2() { var x = 101; var y = 100000085; var d = 39; var expected = 2564103; Assert.AreEqual(expected, service.GetNumberOfJumps(x, y, d)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TP.Entities { public class User { [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } [DisplayName("Ad"),Required,StringLength(25, ErrorMessage="{0} alanı max. {1} karakter olmalıdır..")] public string user_name { get; set; } [DisplayName("Soyad"), Required, StringLength(25 ,ErrorMessage = "{0} alanı max. {1} karakter olmalıdır..")] public string user_surname { get; set; } [DisplayName("E-Posta"), Required, StringLength(70 ,ErrorMessage = "{0} alanı max. {1} karakter olmalıdır..")] public string mail { get; set; } [DisplayName("Parola"), Required,StringLength(15,MinimumLength =5, ErrorMessage = "{0} alanı max. {1} - min. {2} karakter olmalıdır..")] public string password { get; set; } public string user_picturepath { get; set; } public bool IsActive { get; set; } [Required] public Guid ActivateGuid { get; set; } public DateTime user_regdate { get; set; } public virtual List<Notification> notifications { get; set; } } }
using UnityEngine; namespace AudioVisualizer { public class SpectrumDataVisualator : MonoBehaviour { [SerializeField] private SpectrumDataProvider m_Provider; [SerializeField] private GameObject m_CubePrefab; [SerializeField] private float m_MaxScale; private void Awake() { if (m_Provider != null) m_SmpleCubes = new GameObject[m_Provider.SampleSize]; } private void Start() { if (m_Provider == null || m_CubePrefab == null) return; for (int i = 0; i < m_Provider.SampleSize; ++i) { var inst = Instantiate(m_CubePrefab, this.transform, false); inst.name = "Sample_" + i; Quaternion angle = Quaternion.Euler(0f, 360f / 512f * i, 0f); inst.transform.position = this.transform.position + angle * Vector3.forward * 100; inst.transform.rotation = angle; m_SmpleCubes[i] = inst; } } private void Update() { if (m_Provider == null) return; for (int i = 0; i < m_Provider.SampleSize; ++i) { if (m_SmpleCubes[i] == null) continue; m_SmpleCubes[i].transform.localScale = new Vector3(1, (m_Provider.SpectrumData[i] * m_MaxScale) + 1, 1); } } private GameObject[] m_SmpleCubes; } }
using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; namespace dotLua { public class Lua : DynamicObject, IDisposable { private readonly ILuaState _luaState; public Lua() : this(new LuaState()) { } internal Lua(ILuaState luaState) { _luaState = luaState; _luaState.OpenLibs(); } public void Do(string filename) { LuaError error = _luaState.Do(filename); if (error != LuaError.Ok) throw new FileLoadException(error.ToString()); } public override bool TryGetMember(GetMemberBinder binder, out object result) { Tuple<LuaType, object> field = _luaState.GetField(binder.Name); switch (field.Item1) { case LuaType.String: case LuaType.Number: case LuaType.Boolean: case LuaType.Table: result = field.Item2; break; default: throw new NotImplementedException(string.Format("Lua object {0} of type {1} is not supported.", binder.Name, field.Item1)); } return true; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (_luaState.TypeOf(binder.Name) != LuaType.Function) { result = null; return false; } result = Call(binder.Name, args); return true; } private IList<dynamic> Call(string functionName, dynamic[] args) { int bottom = _luaState.GetTop(); try { RawCall(functionName, args); int nArgs = _luaState.GetTop() - bottom; return _luaState.GetStackRange(bottom, nArgs); } finally { _luaState.SetTop(bottom); } } private void RawCall(string functionName, dynamic[] args) { _luaState.GetGlobal(functionName); args.ForEach(arg => _luaState.Push(arg)); LuaError error = _luaState.PCall(args.Length, LuaConstant.MultiReturn, 0); if (error != LuaError.Ok) { throw new InvocationException(error, functionName); } } private List<dynamic> GetStackRange(int index, int n) { var results = new List<dynamic>(n); Enumerable.Range(index + 1, n).ForEach(i => results.Add(_luaState.StackAt(i))); return results; } #region IDisposable public void Dispose() { Dispose(true); } private void Dispose(bool isDisposing) { if (isDisposing) { _luaState.Dispose(); } GC.SuppressFinalize(this); } ~Lua() { Dispose(false); } #endregion } }
using Tomelt.Environment.Extensions.Models; namespace Tomelt.Data.Migration { public interface IDataMigration : IDependency { Feature Feature { get; } } }
using System.ComponentModel; using PropertyChanged; namespace MyStore.Models { public class LoginModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public bool closeWindow { get; set; } public string appVersion { get; set; } public string username { get; set; } public bool rememberMe { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.Entity { public class SaleOrderItem:BaseEntity { public int SaleOrderId { get; set; } /// <summary> /// SKU编码 /// </summary> public int ProductId { get; set; } /// <summary> /// SKU编码 /// </summary> public string ProductName { get; set; } /// <summary> /// SKU编码 /// </summary> public string ProductCode { get; set; } /// <summary> /// 销项税率 /// </summary> // public decimal OutRate { get; set; } /// <summary> /// 平均成本 /// </summary> public decimal AvgCostPrice { get; set; } /// <summary> /// 销售价 /// </summary> public decimal SalePrice { get; set; } /// <summary> /// 实际折后价 /// </summary> public decimal RealPrice { get; set; } /// <summary> /// 数量 /// </summary> public int Quantity { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using DevExpress.XtraBars; using System.Threading; using System.Data.SqlClient; using System.Collections; using System.Xml; using System.Data.Linq; using System.Diagnostics; using DevExpress.XtraSplashScreen; namespace AsimcoBatchMNGMT { public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm { public static DataTable stockdt; //4班库存表 public static DataTable materialdt; //材料库存表 public static DataTable maindt; //主表 public static DataView maindv; //主视图 public static DataTable checkdt; //确认表 public static DataTable checkdv; //确认视图 public static string strRowFilter; //过滤字符串 public static string mainsql; WaitForm1 wf = new WaitForm1(); public MainForm() { InitializeComponent(); } //数据库配置后,从数据库加载数据 private void bbi_config_ItemClick(object sender, ItemClickEventArgs e) { ValidateForm.Instance.ShowDialog(); if (ValidateForm.Instance.DialogResult == DialogResult.OK) { RefreshData(); bbi_refresh.Enabled = true; //可用一级筛选控件 cboOperType.Enabled = true; cboOperType.Properties.Appearance.BackColor = Color.Gray; cboOperType.Properties.Appearance.ForeColor = Color.White; checkEdit1.Enabled = true; checkEdit1.Properties.Appearance.ForeColor = Color.White; checkEdit1.Properties.Appearance.BackColor = Color.Gray; bbi_log.Enabled = true; labelControl1.Visible = true; labelControl2.Visible = true; labelControl3.Visible = true; labelControl4.Visible = true; labelControl5.Visible = true; labelControl6.Visible = true; labelControl7.Visible = true; textEdit2.Visible = true; textEdit3.Visible = true; textEdit4.Visible = true; textEdit5.Visible = true; textEdit1.Visible = true; textEdit6.Visible = true; textEdit7.Visible = true; } } //卡片显示 private void ShowCard() { if (gridView1.DataRowCount > 0) { string xml = gridView1.GetDataRow(gridView1.FocusedRowHandle)["ExChangeXML"].ToString(); gridControl2.DataSource = DBhelp.XML2Table(xml); gridControl2.MainView.PopulateColumns(); //隐藏cardView1无用属性 for (int i = 0; i < 9; i++) { cardView1.Columns[i].Visible = false; } if (gridView1.GetDataRow(gridView1.FocusedRowHandle)["Properties"].ToString() != "") { string xml2 = gridView1.GetDataRow(gridView1.FocusedRowHandle)["Properties"].ToString(); DataTable tempstoredt = DBhelp.XML2Table(xml2); tempstoredt.Columns.Add("LotNumber"); tempstoredt.Columns.Add("RecvBatchNo"); tempstoredt.Columns.Add("MaterialTrackID"); tempstoredt.Columns.Add("QtyInStore"); string selectsql3 = null; if (tempstoredt.Columns.Contains("SKUID")) { selectsql3 = string.Format("SKUID = '{0}'", tempstoredt.Rows[0]["SKUID"].ToString()); } DataTable tempdt = materialdt.Clone(); if (selectsql3 != null) { DataRow[] drArr = materialdt.Select(selectsql3); if (drArr.Length > 0) { tempdt.ImportRow(drArr[0]); } } if (tempdt.Rows.Count > 0) { tempstoredt.Rows[0]["LotNumber"] = tempdt.Rows[0]["LotNumber"]; tempstoredt.Rows[0]["RecvBatchNo"] = tempdt.Rows[0]["RecvBatchNo"]; tempstoredt.Rows[0]["MaterialTrackID"] = tempdt.Rows[0]["MaterialTrackID"]; tempstoredt.Rows[0]["QtyInStore"] = tempdt.Rows[0]["QtyInStore"]; } else { tempstoredt.Rows[0]["LotNumber"] = "无记录"; tempstoredt.Rows[0]["RecvBatchNo"] = "无记录"; tempstoredt.Rows[0]["MaterialTrackID"] = "无记录"; tempstoredt.Rows[0]["QtyInStore"] = "无记录"; } gridControl3.DataSource = tempstoredt; gridControl3.MainView.PopulateColumns(); //隐藏cardView2无用属性 if (tempstoredt != null) { for (int i = 0; i < 5; i++) { cardView2.Columns[i].Visible = false; } } } //错误信息显示 textBox1.Multiline = true;//多行显示 textBox1.WordWrap = true; //文字断行显示 textBox1.Width = 15;//这里设置显示10个文字的宽度像素 if (gridView1.GetDataRow(gridView1.FocusedRowHandle)["ErrCode"].ToString() != "0"&&gridView1.GetDataRow(gridView1.FocusedRowHandle)["ErrCode"]!= null) { this.panelControl2.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(253)))), ((int)(((byte)(244)))), ((int)(((byte)(191))))); this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(253)))), ((int)(((byte)(244)))), ((int)(((byte)(191))))); this.textBox1.Text = gridView1.GetDataRow(gridView1.FocusedRowHandle)["ErrCode"].ToString() + ":" + gridView1.GetDataRow(gridView1.FocusedRowHandle)["ErrText"].ToString(); } else { this.panelControl2.Appearance.BackColor = System.Drawing.Color.White; this.textBox1.BackColor = System.Drawing.Color.White; this.textBox1.Text = ""; } } else { this.gridControl2.DataSource = null; this.gridControl3.DataSource = null; this.panelControl2.Appearance.BackColor = System.Drawing.Color.White; this.textBox1.BackColor = System.Drawing.Color.White; this.textBox1.Text = ""; } cardView1.OptionsBehavior.Editable = false; cardView1.Appearance.FieldValue.BackColor = Color.Transparent; cardView1.Appearance.FieldValue.ForeColor = Color.Black; } //操作类型变更事件 private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e) { filter(); } //未成功检查框变更事件 private void checkEdit1_CheckedChanged(object sender, EventArgs e) { filter(); } //gridView1焦点变更 private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { ShowCard(); } //自定义cardview标题 private void cardView1_CustomDrawCardCaption(object sender, DevExpress.XtraGrid.Views.Card.CardCaptionCustomDrawEventArgs e) { DevExpress.XtraGrid.Views.Card.CardView view = sender as DevExpress.XtraGrid.Views.Card.CardView; (e.CardInfo as DevExpress.XtraGrid.Views.Card.ViewInfo.CardInfo).CaptionInfo.CardCaption = "ExChangeXML"; } private void cardView2_CustomDrawCardCaption(object sender, DevExpress.XtraGrid.Views.Card.CardCaptionCustomDrawEventArgs e) { DevExpress.XtraGrid.Views.Card.CardView view = sender as DevExpress.XtraGrid.Views.Card.CardView; (e.CardInfo as DevExpress.XtraGrid.Views.Card.ViewInfo.CardInfo).CaptionInfo.CardCaption = "MaterialStore"; } //查询 private void filter() { maindv.Sort = "LinkedLogID asc,LogID asc"; gridControl1.DataSource = maindv; if (maindv != null) { if (checkEdit1.Checked) { if (cboOperType.Text != "所有" && cboOperType.Text != "操作类型") strRowFilter = "ExCode ='" + cboOperType.Text + "'and ErrCode <> 0 and Retried = 0"; else strRowFilter = "ErrCode <> 0 and Retried = 0"; } else { if (cboOperType.Text != "所有" && cboOperType.Text != "操作类型") strRowFilter = "ExCode ='" + cboOperType.Text + "'"; else strRowFilter = ""; } string _strRowFilter = ""; if (textEdit2.Text.Trim() != "") _strRowFilter += "ItemNumber like '%" + textEdit2.Text.Trim() + "%' and "; if (textEdit3.Text.Trim() != "") _strRowFilter += "LotNumber like '%" + textEdit3.Text.Trim() + "%' and "; if (textEdit4.Text.Trim() != "") _strRowFilter += "(BinFrom like '%" + textEdit4.Text.Trim() + "%' or BinTo like '%" + textEdit4.Text.Trim() + "%') and "; if (textEdit5.Text.Trim() != "") _strRowFilter += labelControl4.Text + " like '%" + textEdit5.Text.Trim() + "%' and "; if (textEdit1.Text.Trim() != "") _strRowFilter += labelControl5.Text + " = " + textEdit1.Text.Trim() + " and "; if (textEdit6.Text.Trim() != "") _strRowFilter += "OrderNumber like '%" + textEdit6.Text.Trim() + "%' and "; if (textEdit7.Text.Trim() != "") _strRowFilter += "OLineNo like '%" + textEdit7.Text.Trim() + "%' and "; if (_strRowFilter != "") { _strRowFilter = _strRowFilter.Substring(0, _strRowFilter.Length - 5); //删除多余字符 if (strRowFilter != "") { strRowFilter = string.Format("{0} and {1}", strRowFilter, _strRowFilter); } else strRowFilter = _strRowFilter; try { maindv.RowFilter = strRowFilter; } catch (Exception err) { MessageBox.Show(err.Message); } ShowCard(); } else { maindv.RowFilter = strRowFilter; ShowCard(); } if (gridView1.RowCount!=0) { if (gridView1.IsGroupRow(-1) == true) { if (gridView1.GetDataRow(0)["SKUID"].ToString() == "" || gridView1.GetDataRow(0) == null) { gridView1.SetRowExpanded(-1, false); } } gridView1.FocusedRowHandle = -1; } } else { gridView1.FocusedRowHandle = -1; ShowCard(); } } //判断窗口最大化 private void MainForm_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Maximized) { this.cardView1.CardWidth = 550; this.cardView2.CardWidth = 550; } if (this.WindowState == FormWindowState.Normal) { this.cardView1.CardWidth = 353; this.cardView2.CardWidth = 353; } } private void bbi_log_ItemClick(object sender, ItemClickEventArgs e) { string logPath = string.Format(@"{0}Log\IRAP_{1}.log", AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyy-MM-dd")); if (!System.IO.Directory.Exists(logPath)) { try { System.Diagnostics.Process.Start(logPath); //打开此文件。 } catch { MessageBox.Show("今天还没有日志生成!"); } } } //获取并显示数据 private void LoadTask() { Task task1 = Task.Factory.StartNew(() => { string sql3 = "Select * from IRAPRIMCS..utb_MaterialStore"; if (materialdt != null) { materialdt.Clear(); } try { materialdt = DBhelp.Query(sql3).Tables["ds"]; } catch (Exception e) { MessageBox.Show(e.Message); WriteLog.Instance.Write(e.Message, "加载材料库存数据失败"); } }); splashScreenManager1.SetWaitFormDescription("获取数据中..."); if (maindt != null) { maindt.Clear(); } try { maindt = DBhelp.Query(mainsql).Tables["ds"]; } catch (Exception e) { MessageBox.Show(e.Message); WriteLog.Instance.Write(e.Message, "加载主数据失败!"); } splashScreenManager1.SetWaitFormDescription("显示数据中..."); maindt.PrimaryKey = new DataColumn[] { maindt.Columns["LogID"] }; maindt.Columns.Add("ItemNumber").SetOrdinal(4); maindt.Columns.Add("LotNumber").SetOrdinal(5); maindt.Columns.Add("BinFrom").SetOrdinal(6); maindt.Columns.Add("BinTo").SetOrdinal(7); maindt.Columns.Add("OrderNumber").SetOrdinal(8); maindt.Columns.Add("OLineNo"); maindt.Columns.Add("Quantity").SetOrdinal(8); maindt.Columns.Add("SKUID").SetOrdinal(9); //更改ExCode并为列赋值 for (int i = 0; i < maindt.Rows.Count; i++) { SetDTRow((long)maindt.Rows[i]["LogID"], 1); } gridControl1.UseEmbeddedNavigator = true; gridControl1.EmbeddedNavigator.Enabled = false; maindv = maindt.DefaultView; maindv.Sort = "LinkedLogID asc,LogID asc"; gridControl1.DataSource = maindv; gridControl1.MainView.PopulateColumns(); //隐藏gridView1无用属性 gridView1.Columns["ErrCode"].Visible = false; gridView1.Columns["Retried"].Visible = false; gridView1.Columns["LinkedLogID"].Visible = false; gridView1.Columns["ExChangeXML"].Visible = false; gridView1.Columns["ErrText"].Visible = false; gridView1.Columns["Properties"].Visible = false; gridView1.Columns["SKUID"].GroupIndex = 0; gridView1.BestFitColumns(); Task.WaitAll(task1); } //刷新数据 private void RefreshData() { this.splashScreenManager1.ShowWaitForm(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); LoadTask(); if (gridView1.RowCount != 0) { filter(); } stopwatch.Stop(); WriteLog.Instance.Write(maindt.Rows.Count.ToString() + "条,"+string.Format("{0}ms",stopwatch.ElapsedMilliseconds.ToString()), "数据获取成功"); splashScreenManager1.CloseWaitForm(); } //获取解析的XML数据 private void SetDTRow(long LogID,int mode) { DataRow dr = maindt.Rows.Find(LogID); DataTable tempdt = DBhelp.XML2Table(dr["ExChangeXML"].ToString()); if (dr["Properties"].ToString() != "") { DataTable tempdt2 = DBhelp.XML2Table(dr["Properties"].ToString()); if (tempdt2.Columns.Contains("SKUID")) { dr["SKUID"] = tempdt2.Rows[0]["SKUID"]; } } if (dr["ExCode"].ToString() == "PICK08"|| dr["ExCode"].ToString() == "提料") { dr["ExCode"] = "PICK08"; dr["ItemNumber"] = tempdt.Rows[0]["ItemNumber"]; dr["LotNumber"] = tempdt.Rows[0]["LotNumber"]; dr["BinFrom"] = tempdt.Rows[0]["Bin"]; dr["Quantity"] = tempdt.Rows[0]["IssuedQuantity"]; dr["OrderNumber"] = tempdt.Rows[0]["OrderNumber"]; dr["OLineNO"] = tempdt.Rows[0]["LineNumber"]; if(mode ==2) { gridView1.SetFocusedRowCellValue("ItemNumber", tempdt.Rows[0]["ItemNumber"]); gridView1.SetFocusedRowCellValue("LotNumber", tempdt.Rows[0]["LotNumber"]); gridView1.SetFocusedRowCellValue("BinFrom", tempdt.Rows[0]["Bin"]); gridView1.SetFocusedRowCellValue("Quantity", tempdt.Rows[0]["IssuedQuantity"]); } } else if (dr["ExCode"].ToString() == "IMTR01" || dr["ExCode"].ToString() == "移库") { dr["ExCode"] = "IMTR01"; dr["ItemNumber"] = tempdt.Rows[0]["ItemNumber"]; dr["LotNumber"] = tempdt.Rows[0]["LotNumberFrom"]; dr["BinFrom"] = tempdt.Rows[0]["BinFrom"]; dr["BinTo"] = tempdt.Rows[0]["BinTo"]; dr["Quantity"] = tempdt.Rows[0]["InventoryQuantity"]; if(mode ==2) { gridView1.SetFocusedRowCellValue("ItemNumber", tempdt.Rows[0]["ItemNumber"]); gridView1.SetFocusedRowCellValue("LotNumber", tempdt.Rows[0]["LotNumberFrom"]); gridView1.SetFocusedRowCellValue("BinFrom", tempdt.Rows[0]["BinFrom"]); gridView1.SetFocusedRowCellValue("BinTo", tempdt.Rows[0]["BinTo"]); gridView1.SetFocusedRowCellValue("Quantity", tempdt.Rows[0]["InventoryQuantity"]); } } else if (dr["ExCode"].ToString() == "PORV01" || dr["ExCode"].ToString() == "入库") { dr["ExCode"] = "PORV01"; dr["ItemNumber"] = tempdt.Rows[0]["ItemNumber"]; dr["LotNumber"] = tempdt.Rows[0]["LotNumberDefault"]; dr["BinTo"] = tempdt.Rows[0]["Bin1"]; dr["Quantity"] = tempdt.Rows[0]["ReceiptQuantityMove1"]; dr["OrderNumber"] = tempdt.Rows[0]["PONumber"]; dr["OLineNO"] = tempdt.Rows[0]["POLineNumber"]; if (mode == 2) { gridView1.SetFocusedRowCellValue("ItemNumber", tempdt.Rows[0]["ItemNumber"]); gridView1.SetFocusedRowCellValue("LotNumber", tempdt.Rows[0]["LotNumberDefault"]); gridView1.SetFocusedRowCellValue("BinTo", tempdt.Rows[0]["Bin1"]); gridView1.SetFocusedRowCellValue("Quantity", tempdt.Rows[0]["ReceiptQuantityMove1"]); } } else if (dr["ExCode"].ToString() == "MORV00") { dr["ExCode"] = "MORV00"; dr["ItemNumber"] = tempdt.Rows[0]["ItemNumber"]; dr["LotNumber"] = tempdt.Rows[0]["LotNumber"]; dr["BinFrom"] = tempdt.Rows[0]["Bin1"]; dr["Quantity"] = tempdt.Rows[0]["ReceiptQuantity"]; dr["OrderNumber"] = tempdt.Rows[0]["MONumber"]; dr["OLineNO"] = tempdt.Rows[0]["MOLineNumber"]; } else if (dr["ExCode"].ToString() == "INVA01") { dr["ExCode"] = "INVA01"; dr["ItemNumber"] = tempdt.Rows[0]["ItemNumber"]; dr["LotNumber"] = tempdt.Rows[0]["LotNumber"]; dr["BinTo"] = tempdt.Rows[0]["Bin"]; dr["Quantity"] = tempdt.Rows[0]["AdjustQuantity"]; } tempdt.Clear(); } private void bbi_refresh_ItemClick(object sender, ItemClickEventArgs e) { RefreshData(); } //取数据库中最新的LogID private object GetLastLogID(long LinkedLogID) { string sql = string.Format("select LogID from IRAP..stb_Log_WebServiceShuttling where LinkedLogID ={0} and Retried = 0",LinkedLogID); object rlt = null; try { rlt =DBhelp.getSingle(sql); } catch(SqlException e) { MessageBox.Show("获取最新logID失败:" + e.Message); WriteLog.Instance.Write(e.Message, "获取最新logID失败"); } return rlt; } //显示编辑窗口 public void ShowEditForm() { string[][] check = new string[3][]; check[0] = new string[] { "False", "False", "False" }; //是否提交 check[1] = new string[] { "", "", "" }; //返回 RecvBatchNo,QtyInStore,QtyLoaded的值 check[2] = new string[] { "", "", "" }; //默认值 string selectsql3 = null; long LogID = long.Parse(gridView1.GetDataRow(gridView1.FocusedRowHandle)["LogID"].ToString()); long LinkedLogID = long.Parse(gridView1.GetDataRow(gridView1.FocusedRowHandle)["LinkedLogID"].ToString()); string skuid = ""; string[] retried = { gridView1.GetDataRow(gridView1.FocusedRowHandle)["Retried"].ToString(), gridView1.GetDataRow(gridView1.FocusedRowHandle)["Retried"].ToString() }; string[] xml = { gridView1.GetDataRow(gridView1.FocusedRowHandle)["ExChangeXML"].ToString(), gridView1.GetDataRow(gridView1.FocusedRowHandle)["ExChangeXML"].ToString() }; DataTable tempdt = DBhelp.XML2Table(xml[0]); if (xml[0] != "") { XmlDocument xdoc = new XmlDocument(); if (gridView1.GetDataRow(gridView1.FocusedRowHandle)["Properties"].ToString().Trim() != "") { xdoc.LoadXml(gridView1.GetDataRow(gridView1.FocusedRowHandle)["Properties"].ToString()); if (xdoc.FirstChild.SelectSingleNode("SKUID") != null) { skuid = xdoc.FirstChild.SelectSingleNode("SKUID").InnerText; selectsql3 = string.Format("SKUID = '{0}'", skuid); } } DialogResult dia = new DialogResult(); DataTable dtNew3 = materialdt.Clone(); string errinfo = gridView1.GetDataRow(gridView1.FocusedRowHandle)["ErrCode"].ToString() + ":" + gridView1.GetDataRow(gridView1.FocusedRowHandle)["ErrText"].ToString(); if (selectsql3 != null) { DataRow[] drArr3 = materialdt.Select(selectsql3); if (drArr3.Length > 0) { dtNew3.ImportRow(drArr3[0]); } if (dtNew3.Rows.Count <= 0) { dtNew3 = null; } } if (gridView1.GetDataRow(gridView1.FocusedRowHandle)["ExCode"].ToString() == "IMTR01") { IMTRForm im = null; im = new IMTRForm(xml, skuid, errinfo, retried, dtNew3, check); dia = im.ShowDialog(); } else if (gridView1.GetDataRow(gridView1.FocusedRowHandle)["ExCode"].ToString() == "PORV01") { PORVForm po = null; po = new PORVForm(xml, skuid, errinfo, retried, dtNew3, check); dia = po.ShowDialog(); } else if (gridView1.GetDataRow(gridView1.FocusedRowHandle)["ExCode"].ToString() == "PICK08") { PICKForm pi = null; pi = new PICKForm(xml, skuid, errinfo, retried, dtNew3, check); dia = pi.ShowDialog(); } if (dia == DialogResult.OK) { string sql = "update IRAP..stb_Log_WebServiceShuttling set ExChangeXML = @ExChangeXML where LogID = @LogID and PartitioningKey ='600100000'"; SqlParameter[] paras = new SqlParameter[2]; if (GetLastLogID(LinkedLogID) != null) { long LastLogID = (long)GetLastLogID(LinkedLogID); WriteLog.Instance.WriteBeginSplitter("开始编辑记录LogID =" + LastLogID.ToString() + string.Format(";Retried = {0}", retried[0])); paras[0] = new SqlParameter("@ExChangeXML", xml[0]); paras[1] = new SqlParameter("@LogID", LastLogID); int i = 2; try { i = DBhelp.ExecuteSQL(sql, paras); } catch (SqlException err) { WriteLog.Instance.Write(err.Message, "更改ExChangeXml失败"); WriteLog.Instance.Write(xml[1], "更改前的ExChangeXml"); WriteLog.Instance.Write(xml[0], "更改后的ExChangeXml"); MessageBox.Show(err.Message); } if (i == 0) { WriteLog.Instance.Write("未找到记录:", "更改ExChangeXml失败"); WriteLog.Instance.Write(xml[1], "更改前的ExChangeXml"); WriteLog.Instance.Write(xml[0], "更改后的ExChangeXml"); MessageBox.Show("保存失败"); } else if (i == 1) { WriteLog.Instance.Write("成功", "更改ExChangeXml成功"); WriteLog.Instance.Write(xml[1], "更改前的ExChangeXml"); WriteLog.Instance.Write(xml[0], "更改后的ExChangeXml"); string name = "IRAP..ssp_BackgroundJob_WSRetry"; SqlParameter[] paras3 = new SqlParameter[5]; paras3[0] = new SqlParameter("@SysLogID", 1); paras3[1] = new SqlParameter("@CommunityID", 60010); paras3[2] = new SqlParameter("@WSSLogID", LastLogID); paras3[3] = new SqlParameter("@ErrCode", SqlDbType.Int, 4); paras3[3].Direction = ParameterDirection.Output; paras3[4] = new SqlParameter("@ErrText", SqlDbType.NVarChar, 400); paras3[4].Direction = ParameterDirection.Output; int j = 2; try { j = DBhelp.ExecuteProc(name, paras3); } catch (SqlException err) { MessageBox.Show(err.Message); WriteLog.Instance.Write(err.Message, "WSRrtry执行失败"); } if (j == -1) { WriteLog.Instance.Write(string.Format("ErrCode = {0},{1}", paras3[3].Value.ToString(), paras3[4].Value.ToString()), "WSRetry执行成功"); MessageBox.Show(string.Format("ErrCode = {0},{1}", paras3[3].Value.ToString(), paras3[4].Value.ToString())); // 如果是 PORV01 交易成功,则需要将 utb_MaterialStore 表中的 RecvBatchNo 更新为四班中生成的 RecvBatchNo // 代码待定 if (check[0][0] == "True") { int flag = 2; string sql2 = "update IRAPRIMCS..utb_MaterialStore set RecvBatchNo = @RecvBatchNo where SKUID =@SKUID"; SqlParameter[] paras2 = new SqlParameter[2]; paras2[0] = new SqlParameter("@RecvBatchNo", check[0][1]); paras2[1] = new SqlParameter("@SKUID", skuid); try { flag = DBhelp.ExecuteSQL(sql2, paras2); if (flag == 0) { WriteLog.Instance.Write(string.Format("更改RecvbatcNo = {0}为RecvBatchNo = {1}", check[0][2], check[0][1]), "更改RecvBatchNo失败,未找到记录"); } else if (flag == 1) { WriteLog.Instance.Write(string.Format("更改RecvbatcNo = {0}为RecvBatchNo = {1}", check[0][2], check[0][1]), "更改RecvBatchNo成功"); } } catch (SqlException err) { MessageBox.Show(err.Message); WriteLog.Instance.Write(string.Format("更改RecvbatcNo = {0}更改RecvbatcNo = {1}", check[0][2], check[0][1]), "更改更改RecvbatcNo失败" + err.Message); } } if (check[1][0] == "True") { int flag = 2; string sql2 = "update IRAPRIMCS..utb_MaterialStore set QtyInStore = @QtyInStore where SKUID =@SKUID"; SqlParameter[] paras2 = new SqlParameter[2]; paras2[0] = new SqlParameter("@QtyInStore", check[1][1]); paras2[1] = new SqlParameter("@SKUID", skuid); try { flag = DBhelp.ExecuteSQL(sql2, paras2); if (flag == 0) { WriteLog.Instance.Write(string.Format("更改QtyInStore = {0}为QtyInStore = {1}", check[1][2], check[1][1]), "更改QtyInStore失败,未找到记录"); } else if (flag == 1) { WriteLog.Instance.Write(string.Format("更改QtyInStore = {0}为QtyInStore = {1}", check[1][2], check[1][1]), "更改QtyInStore成功"); } } catch (SqlException err) { MessageBox.Show(err.Message); WriteLog.Instance.Write(string.Format("更改QtyInStore = {0}更改QtyInStore = {1}", check[1][2], check[1][1]), "更改更改QtyInStore失败" + err.Message); } } if (check[2][1] != check[2][2] && check[2][0] == "True") { int flag = 2; string sql2 = "update IRAPMES..RSFact_PWOMaterialTrack set QtyLoaded = @QtyLoaded where WFInstanceID in (SELECT WFInstanceID from IRAPMES..AuxFact_PWOIssuing where MONumber =@MONumber and MOLineNo =@MOLineNo) and SKUID =@SKUID"; SqlParameter[] paras2 = new SqlParameter[4]; paras2[0] = new SqlParameter("@QtyLoaded", check[2][1]); paras2[1] = new SqlParameter("@MONumber", tempdt.Rows[0]["OrderNumber"].ToString()); paras2[2] = new SqlParameter("@MOLineNo", tempdt.Rows[0]["LineNumber"].ToString()); paras2[3] = new SqlParameter("@SKUID", skuid); try { flag = DBhelp.ExecuteSQL(sql2, paras2); if (flag == 0) { WriteLog.Instance.Write(string.Format("更改QtyLoaded = {0}为QtyLoaded = {1}", check[2][2], check[2][1]), "更改QtyLoaded失败,未找到记录"); } else if (flag == 1) { WriteLog.Instance.Write(string.Format("更改QtyLoaded = {0}为QtyLoaded = {1}", check[2][2], check[2][1]), "更改QtyLoaded成功"); } } catch (Exception err) { MessageBox.Show(err.Message); WriteLog.Instance.Write(string.Format("更改QtyLoaded = {0}为QtyLoaded = {1}", check[2][2], check[2][1]), "更改QtyLoaded失败" + err.Message); } } WriteLog.Instance.WriteEndSplitter("结束编辑记录"); RefreshData(); } } } else { MessageBox.Show("该LinkedLogID下无Retried=0的记录,请刷新数据"); } } else if (dia == DialogResult.Abort) { string sql = "update IRAP..stb_Log_WebServiceShuttling set Retried = @Retried where LogID = @LogID"; SqlParameter[] paras = new SqlParameter[2]; if (GetLastLogID(LinkedLogID) != null) { long LastLogID = (long)(LogID); paras[0] = new SqlParameter("@Retried", 1); paras[1] = new SqlParameter("@LogID", LastLogID); try { if (DBhelp.ExecuteSQL(sql, paras) == 1) { MessageBox.Show("删除成功"); WriteLog.Instance.WriteBeginSplitter("开始删除记录LogID =" + LastLogID.ToString() + string.Format(";Retried = {0}", retried[0])); WriteLog.Instance.Write(xml[1], "删除记录成功"); WriteLog.Instance.WriteEndSplitter("结束删除记录"); RefreshData(); } } catch (SqlException err) { MessageBox.Show("删除失败:" + err.Message); WriteLog.Instance.WriteBeginSplitter("开始删除记录LogID =" + LastLogID.ToString() + string.Format(";Retried = {0}", retried[0])); WriteLog.Instance.Write(err.Message, "删除记录失败"); WriteLog.Instance.Write(xml[1], "删除记录失败"); WriteLog.Instance.WriteEndSplitter("结束删除记录"); } } else { MessageBox.Show("该LinkedLogID下无Retried=0的记录,请刷新数据"); } } } } private void gridControl1_MouseDown(object sender, MouseEventArgs e) { DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y)); if (e.Button == MouseButtons.Left && e.Clicks == 2) { //判断光标是否在行范围内 if (hInfo.InRow) { if (!gridView1.IsGroupRow(gridView1.FocusedRowHandle)) //不是分组行 { ShowEditForm(); } } } } private void textEdit1_EditValueChanged(object sender, EventArgs e) { if (textEdit1.Text.Length > 6 || textEdit1.Text.Length == 0) { filter(); } } private void textEdit2_EditValueChanged(object sender, EventArgs e) { filter(); } private void gridControl1_KeyUp(object sender, KeyEventArgs e) { if (gridView1.RowCount != 0) { if (e.KeyCode == Keys.Enter) { int rowHandle = gridView1.FocusedRowHandle; if (gridView1.IsGroupRow(rowHandle) == true) { gridView1.SetRowExpanded(rowHandle, !gridView1.GetRowExpanded(rowHandle)); } else { ShowEditForm(); } } } } private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e) { Reports rts = new Reports(); rts.ShowDialog(); } private void MainForm_Shown(object sender, EventArgs e) { Application.DoEvents(); //RefreshData(); } } }
using System; using Grasshopper.Kernel; using Pterodactyl; using Xunit; namespace UnitTestsGH { public class TestPieChartToolGhHelper { public static PieChartToolGH TestObject { get { PieChartToolGH testObject = new PieChartToolGH(); return testObject; } } } public class TestPieChartToolGh { [Theory] [InlineData("Pie Chart", "Pie Chart", "Add simple pie chart", "Pterodactyl", "Tools")] public void TestName(string name, string nickname, string description, string category, string subCategory) { Assert.Equal(name, TestPieChartToolGhHelper.TestObject.Name); Assert.Equal(nickname, TestPieChartToolGhHelper.TestObject.NickName); Assert.Equal(description, TestPieChartToolGhHelper.TestObject.Description); Assert.Equal(category, TestPieChartToolGhHelper.TestObject.Category); Assert.Equal(subCategory, TestPieChartToolGhHelper.TestObject.SubCategory); } [Theory] [InlineData(0, "Title", "Title", "Title of your pie chart", GH_ParamAccess.item)] [InlineData(1, "Categories", "Categories", "Categories as text list", GH_ParamAccess.list)] [InlineData(2, "Values", "Values", "Values for each category as number list", GH_ParamAccess.list)] public void TestRegisterInputParams(int id, string name, string nickname, string description, GH_ParamAccess access) { Assert.Equal(name, TestPieChartToolGhHelper.TestObject.Params.Input[id].Name); Assert.Equal(nickname, TestPieChartToolGhHelper.TestObject.Params.Input[id].NickName); Assert.Equal(description, TestPieChartToolGhHelper.TestObject.Params.Input[id].Description); Assert.Equal(access, TestPieChartToolGhHelper.TestObject.Params.Input[id].Access); } [Theory] [InlineData(0, "Report Part", "Report Part", "Created part of the report", GH_ParamAccess.item)] public void TestRegisterOutputParams(int id, string name, string nickname, string description, GH_ParamAccess access) { Assert.Equal(name, TestPieChartToolGhHelper.TestObject.Params.Output[id].Name); Assert.Equal(nickname, TestPieChartToolGhHelper.TestObject.Params.Output[id].NickName); Assert.Equal(description, TestPieChartToolGhHelper.TestObject.Params.Output[id].Description); Assert.Equal(access, TestPieChartToolGhHelper.TestObject.Params.Output[id].Access); } [Fact] public void TestGuid() { Guid expected = new Guid("26a43f20-9ede-4f7c-b5dd-95ab3e2a9ad1"); Guid actual = TestPieChartToolGhHelper.TestObject.ComponentGuid; Assert.Equal(expected, actual); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Word = DocumentFormat.OpenXml.Wordprocessing; using DocGen.ObjectModel; using DocumentFormat.OpenXml; namespace DocGen.OOXML { class ElementFactory { /// <summary> /// Returns formatted OOXML elements according to the given Element object. /// </summary> /// <param name="element">Subclass of Element representing the document feature</param> /// <returns></returns> public static IEnumerable<OpenXmlElement> GetElement(Element element) { switch (element.GetElementType()) { case ElementType.Text: return GetElement(element as Text); case ElementType.Paragraph: return GetElement(element as Paragraph); case ElementType.Table: return TableFormatter.GetFormattedElement(element as Table); case ElementType.Image: return GetElement(element as Image); case ElementType.Heading: return GetElement(element as Heading); case ElementType.Section: return SectionFormatter.GetFormattedSection(element as Section); case ElementType.MultiColumnSection: return MultiColumnSectionFormatter.GetFormattedSection(element as MultiColumnSection); case ElementType.Chapter: return ChapterFormatter.GetFormattedChapter(element as Chapter); case ElementType.List: return GetElement(element as List); default: throw new InvalidInputException(element.GetElementType() + " "); } } private static IEnumerable<OpenXmlElement> GetElement(Text text) { Paragraph para = new Paragraph(text); var formattedPara = ParagraphFormatter.GetFormattedElement(para); OpenXmlElement[] result = new OpenXmlElement[1]; result[0] = formattedPara; return result; } private static IEnumerable<OpenXmlElement> GetElement(Paragraph paragraph) { var paragraphContent = ParagraphFormatter.GetFormattedElement(paragraph); OpenXmlElement[] result = new OpenXmlElement[1]; result[0] = paragraphContent; return result; } private static IEnumerable<OpenXmlElement> GetElement(Image image) { var imageContent = ImageFormatter.GetFormattedElement(image); OpenXmlElement[] result = new OpenXmlElement[1]; result[0] = imageContent; return result; } private static IEnumerable<OpenXmlElement> GetElement(List list) { List<OpenXmlElement> FormattedList = new List<OpenXmlElement>(); foreach (var listItem in ListFormatter.GetFormattedElement((List)list)) { FormattedList.Add(listItem); } return FormattedList.ToArray(); } private static IEnumerable<OpenXmlElement> GetElement(Heading heading) { var formattedHeading = HeadingFormatter.GetFormattedElement(heading); OpenXmlElement[] result = new OpenXmlElement[1]; result[0] = formattedHeading; return result; } } }
using FluentNHibernate.Mapping; using Infrastructure.Translations; namespace Data.Mappings { public class TranslationMap : ClassMap<Translation> { public TranslationMap() { Table("Translations"); Id(x => x.Id); Map(x => x.Culture) .Access.CamelCaseField(Prefix.Underscore) .Not.Nullable(); Map(x => x.Code) .Access.CamelCaseField(Prefix.Underscore) .Not.Nullable(); Map(x => x.Text) .Length(9999) .Access.CamelCaseField(Prefix.Underscore) .Not.Nullable(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using VirusTotalNET; using VirusTotalNET.Objects; using VirusTotalNET.ResponseCodes; using VirusTotalNET.Results; namespace VirusTotalGUI { public partial class Form1 : Form { private Byte[] fileBytes = null; List<ScanResult> resultList = new List<ScanResult>(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { AllocConsole(); Debug.WriteLine("Application Started"); } [DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] [return: MarshalAs(UnmanagedType.Bool)] static extern bool AllocConsole(); private static void PrintScan(FileReport fileReport) { Console.WriteLine("Scan ID: " + fileReport.ScanId); Console.WriteLine("Message: " + fileReport.VerboseMsg); if (fileReport.ResponseCode == FileReportResponseCode.Present) { foreach (KeyValuePair<string, ScanEngine> scan in fileReport.Scans) { Console.WriteLine("{0,-25} Detected: {1}", scan.Key, scan.Value.Detected); } } Console.ReadLine(); } private void BrowseButton_Click(object sender, EventArgs e) { this.openFileDialog1.InitialDirectory = "c:\\"; this.openFileDialog1.RestoreDirectory = true; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { fileLocator.Text = openFileDialog1.FileName; } } private async void ScanButton_Click(object sender, EventArgs e) { try { if (!(fileLocator.Text.EndsWith("png") || fileLocator.Text.EndsWith("jpg") || fileLocator.Text.EndsWith("gif")||fileLocator.Text.EndsWith("svg") || fileLocator.Text.EndsWith("txt"))) { fileBytes = File.ReadAllBytes(fileLocator.Text); if (fileBytes != null) { string API_KEY = System.Environment.GetEnvironmentVariable("API_KEY", EnvironmentVariableTarget.Machine); VirusTotal virusTotal = new VirusTotal(API_KEY); //Use HTTPS instead of HTTP virusTotal.UseTLS = true; if (fileBytes.Length > 0) { //Check if the file has been scanned before. FileReport report = await virusTotal.GetFileReportAsync(fileBytes); if (report.ResponseCode == FileReportResponseCode.Present) { foreach (KeyValuePair<string, ScanEngine> scan in report.Scans) { Console.WriteLine("{0,-25} Detected: {1}", scan.Key, scan.Value.Detected); } Console.WriteLine("Scan ID: " + report.ScanId); Console.WriteLine("Message: " + report.VerboseMsg); Console.WriteLine("Seen before: " + (report.ResponseCode == FileReportResponseCode.Present ? "Yes" : "No")); } addResultRecord(fileLocator.Text, report); } else { MessageBox.Show("Please Select a file having valid size"); } } } else { MessageBox.Show("Sorry We Currently Don't Support This Format, Next Release Will incorporat These Features"); fileLocator.Text = ""; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void updateListView() { scannedFileListView.Items.Clear(); foreach (var res in resultList) { var row = new string[] { res.FileName, res.DateOfScan.ToString("MM/dd/yyyy HH:mm:ss"), res.GetChecksum(), res.VerifyMalicious() }; var lvi = new ListViewItem(row); lvi.Tag = res; scannedFileListView.Items.Add(lvi); } } public void addResultRecord(string filepath, FileReport report) { var resultDict = new Dictionary<string, bool>(); if (report.Scans != null) { bool isMalicious = false; foreach (KeyValuePair<string, ScanEngine> scan in report.Scans) { resultDict.Add(scan.Key, scan.Value.Detected); //res += string.Format("{0,-25} Detected: {1} \n", scan.Key, scan.Value.Detected); } } ScanResult scr = new ScanResult(filepath); scr.Result = resultDict; resultList.Add(scr); fileLocator.Text = ""; fileBytes = null; updateListView(); } private void FileLocator_DoubleClick(object sender, EventArgs e) { this.openFileDialog1.InitialDirectory = "c:\\"; this.openFileDialog1.FilterIndex = 1; this.openFileDialog1.RestoreDirectory = true; if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { fileLocator.Text = this.openFileDialog1.FileName; } } private void FileLocator_Leave(object sender, EventArgs e) { if (fileLocator.Text.Length > 0) { if (!File.Exists(fileLocator.Text)) { MessageBox.Show("Invalid Path"); } } } private void FileLocator_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (fileLocator.Text.Length > 0) { if (File.Exists(fileLocator.Text)) { if (fileBytes.Length > 0) { fileBytes = null; } if (!(fileLocator.Text.EndsWith("png") || fileLocator.Text.EndsWith("txt") || fileLocator.Text.EndsWith("jpg") || fileLocator.Text.EndsWith("gif") || fileLocator.Text.EndsWith("svg"))) { fileBytes = File.ReadAllBytes(fileLocator.Text); } else { MessageBox.Show("Sorry We Currently Don't Support This Format, Next Release Will incorporat These Features"); fileLocator.Text = ""; } } else { MessageBox.Show("Invalid Path"); } } } } private void ScannedFileListView_SelectedIndexChanged(object sender, EventArgs e) { var selectedItem = (ScanResult)scannedFileListView.SelectedItems[0].Tag; if (selectedItem != null) { MessageBox.Show(selectedItem.ToString()); } } } }
using System; using UnityEngine; public class Window : MonoBehaviour { public Action onEndShowAnimation; public Action onEndHideAnimation; public Action onClickCloseButton; [SerializeField] private Animator _animator; private int _showHash = Animator.StringToHash("ShowAnimation"); private int _hideHash = Animator.StringToHash("HideAnimation"); public virtual bool IsShow() { if (gameObject.activeSelf) return true; return false; } public virtual void Show(bool animation = true) { gameObject.SetActive(true); if (_animator != null) _animator.enabled = false; else animation = false; if (animation) { _animator.enabled = true; _animator.Play(_showHash, -1, 0.0f); _animator.Update(0.0f); } else OnEndShowAnimation(); } public virtual void Hide(bool animation = true) { if (_animator == null) animation = false; if (animation) { _animator.enabled = true; _animator.Play(_hideHash, -1, 0.0f); _animator.Update(0.0f); } else OnEndHideAnimation(); onEndShowAnimation = null; } public virtual void OnEndShowAnimation() { if (_animator != null) _animator.enabled = false; WindowManager.Instance.AddWindow(this); onEndShowAnimation?.Invoke(); } public virtual void OnEndHideAnimation() { if (_animator != null) _animator.enabled = false; gameObject.SetActive(false); onEndHideAnimation?.Invoke(); onEndHideAnimation = null; WindowManager.Instance.RemoveWindow(this); Destroy(gameObject); } public virtual void OnClickCloseButton() { onClickCloseButton?.Invoke(); } }
using UnityEngine; using UI; using System.Collections; using System.Collections.Generic; public class WorkspaceDockAttachment : BaseAttachment { public float m_carouselRadius = 1.0f; public float m_arcSize = Mathf.PI / 2; public float m_minAngle = Mathf.PI * 0.1f; public float m_volumetricYOffset = 0.0f; protected BaseAttachment m_activeAttachment; protected Dictionary<BaseAttachment, GameObject> m_volumetrics; // Use this for initialization public override void Awake () { base.Awake(); SetAsDock(true); AddAcceptedDocktype(typeof(InstrumentAttachment)); m_volumetrics = new Dictionary<BaseAttachment, GameObject>(); } public override bool AddDockableAttachment (BaseAttachment attach) { if (base.AddDockableAttachment(attach)) { //attach.rigidbody.velocity = Vector3.zero; attach.rigidbody.isKinematic = true; InstrumentAttachment instrument = attach as InstrumentAttachment; attach.SetToolmodeResponse(new BaseTool.ToolMode[]{ BaseTool.ToolMode.PRIMARY, BaseTool.ToolMode.GRABBING }); instrument.EnableControls(); instrument.SetCloneable(false); GameObject volumetric = UIFactory.CreateVolumetricCylinder(); volumetric.transform.position = new Vector3(attach.transform.position.x, m_volumetricYOffset, attach.transform.position.z); volumetric.transform.parent = transform; iTween.ColorTo(volumetric, iTween.Hash("color", new Color(1.0f, 1.0f, 1.0f, 0.2f), "time", 0.8f)); m_volumetrics[instrument] = volumetric; PlaceObjects(); //iTween.MoveTo(attach.gameObject, iTween.Hash("position", transform.localPosition, "uselocal", true )); return true; } return false; } public override void RemoveDockableAttachment (BaseAttachment attach) { base.RemoveDockableAttachment (attach); attach.SetToolmodeResponse(new BaseTool.ToolMode[]{ BaseTool.ToolMode.GRABBING }); Destroy(m_volumetrics[attach]); attach.DisableControls(); attach.rigidbody.isKinematic = false; PlaceObjects(); } public void PlaceObjects(){ Vector3[] points = Utils.BuildArcPositions(m_carouselRadius, m_arcSize, m_childDockables.Count, m_minAngle, true); for(int i = 0; i < points.Length; i++){ points[i].z = points[i].y; points[i].y = 0.0f; } for (int i = 0; i < m_childDockables.Count; i++) { iTween.MoveTo(m_childDockables[i].gameObject, iTween.Hash("position", points[i], "time", 0.5f, "islocal", true)); iTween.MoveTo(m_volumetrics[m_childDockables[i]], iTween.Hash("position", points[i] + new Vector3(0.0f, m_volumetricYOffset, 0.0f), "time", 0.5f, "islocal", true)); } } public void InstrumentControlsAreVisible(BaseAttachment attach) { if (m_activeAttachment != null && attach != m_activeAttachment) m_activeAttachment.HideControls(); m_activeAttachment = attach; } // Update is called once per frame public override void Update () { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Engine.Interfaces; using Engine.Items; using Engine.Quests; namespace Engine.Characters { public class Player : LivingCreature, IHeal { public int Gold { get; set; } public int ExperiencePoints { get; set; } public int Level { get; set; } public List<InventoryItem> Inventory { get; set; } public List<PlayerQuest> Quests { get; set; } public int CurrentHitPoints { get; set; } public int MaximumHitPoints { get; set; } public Player(int id, string name, int currentHitPoints, int maximumHitPoints, int gold, int experiencePoints, int level) : base( id, name) { Gold = gold; ExperiencePoints = experiencePoints; Level = level; CurrentHitPoints = currentHitPoints; MaximumHitPoints = maximumHitPoints; Inventory = new List<InventoryItem>(); Quests = new List<PlayerQuest>(); } public void Heal(HealingPotion Potion) { this.ExperiencePoints += Potion.AmountToHeal; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Thingy.WebServerLite.Api; namespace Thingy.WebServerLite { public class WebServerResponse : IWebServerResponse { private readonly IMimeTypeProvider mimeTypeProvider; private Mutex fileIoMutex = new Mutex(false, "04f0fd63-10a5-4c01-a4be-50d10021d6d5"); public WebServerResponse(IMimeTypeProvider mimeTypeProvider, HttpListenerResponse response) { this.mimeTypeProvider = mimeTypeProvider; this.HttpListenerResponse = response; } public void FromFile(string filePath) { HttpListenerResponse.ContentType = mimeTypeProvider.GetMimeType(filePath); HttpListenerResponse.StatusCode = 200; try { using (Stream outputStream = HttpListenerResponse.OutputStream) { fileIoMutex.WaitOne(); try { using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { fileStream.CopyTo(HttpListenerResponse.OutputStream); fileStream.Close(); } } finally { fileIoMutex.ReleaseMutex(); } outputStream.Close(); } } catch(Exception exception) { InternalError(null, exception); } } public void FromString(string content, string contentType, int statusCode) { HttpListenerResponse.ContentType = contentType; HttpListenerResponse.StatusCode = statusCode; using (Stream outputStream = HttpListenerResponse.OutputStream) { byte[] buffer = Encoding.UTF8.GetBytes(content); HttpListenerResponse.ContentLength64 = buffer.Length; outputStream.Write(buffer, 0, buffer.Length); outputStream.Close(); } } public void InternalError(IWebServerRequest request, Exception e) { FromString( AddRequestDetails(new MarkUpBuilder() .Append("<!DOCTYPE html>", "<html>", "<head>", "<title>500 Error</title>", "</head>") .Append("<body style=\"font-family: calibri, ariel;\">", "<h1 style=\"background-color: #ffffcf; border : 1px solid black; padding : 8px\">500 - Internal Server Error</h1>") , request) .Append("<div style=\"font-family: consolas, courier; border : 1px solid black; padding : 8px\">") .Append(e.ToString().Replace("\n", "<br/>")) .Append("</div></body>", "</html>") .ToString(), "text/html", 500); } public void NotAllowed(IWebServerRequest request) { FromString( AddRequestDetails(new MarkUpBuilder() .Append("<!DOCTYPE html>", "<html>", "<head>", "<title>403 Forbidden</title>", "</head>") .Append("<body style=\"font-family: calibri, ariel;\">", "<h1 style=\"background-color: #ffffcf; border : 1px solid black; padding : 8px\">500 - Forbidden</h1>") , request) .Append("<div style=\"font-family: consolas, courier; border : 1px solid black; padding : 8px\">") .Append("The request was valid, but the server is refusing action.<br/>The user might not have the necessary permissions for a resource, or may need an account of some sort.") .Append("</div></body>", "</html>") .ToString(), "text/html", 403); } public void NotFound(IWebServerRequest request) { FromString( AddRequestDetails(new MarkUpBuilder() .Append("<!DOCTYPE html>", "<html>", "<head>", "<title>404 Not Found</title>", "</head>") .Append("<body style=\"font-family: calibri, ariel;\">", "<h1 style=\"background-color: #ffffcf; border : 1px solid black; padding : 8px\">404 - Not Found</h1>") , request) .Append("<div style=\"font-family: consolas, courier; border : 1px solid black; padding : 8px\">") .Append("The requested resource could not be found but may be available in the future.<br/>Subsequent requests by the client are permissible.") .Append("</div></body>", "</html>") .ToString(), "text/html", 404); } private MarkUpBuilder AddRequestDetails(MarkUpBuilder builder, IWebServerRequest request) { return request == null ? builder : builder .Append("<div style=\"font-family: consolas, courier; border : 1px solid black; padding : 8px; margin-bottom : 4px;\">") .Append("<table><tbody>") .Append("<tr><th style=\"padding-right : 4px; text-align : right\">HTTP Method</th><td>", request.HttpMethod, "</td></tr>") .Append("<tr><th style=\"padding-right : 4px; text-align : right\">Url</th><td>", request.HttpListenerRequest.Url, "</td></tr>") .Append("</tbody></table>") .Append("</div>"); } public HttpListenerResponse HttpListenerResponse { get; private set; } } }
using System; using System.IO; using Avalonia; using Avalonia.Platform; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Gui.Tabs { public class LegalIssuesViewModel : TextResourceViewModelBase { public LegalIssuesViewModel(Global global) : base(global, "Legal Issues", new Uri("resm:WalletWasabi.Gui.Assets.LegalIssues.txt")) { } } }
// The MIT License (MIT) // Copyright (c) 2015 Intis Telecom // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Collections.Specialized; using System.Net; using System.Text; using System.Web; namespace Intis.SDK { /// <summary> /// Class HttpApiConnector /// HTTP API data connector implementation API data connector /// </summary> public class HttpApiConnector : IApiConnector { /// <summary> /// Getting data from API /// </summary> /// <param name="url">API address</param> /// <param name="allParameters">parameters</param> /// <returns>data as an string</returns> public string GetContentFromApi(string url, NameValueCollection allParameters) { var encodeParameters = new NameValueCollection(); for (var i = 0; i <= allParameters.Count - 1; i++) { var param = HttpUtility.UrlEncode(allParameters.Get(i)); if (param != null) encodeParameters.Add(allParameters.GetKey(i), param); } var client = new WebClient { QueryString = encodeParameters, Encoding = Encoding.UTF8 }; var result = client.DownloadString(url); return result; } /// <summary> /// Getting timestamp from API /// </summary> /// <param name="url">API address</param> /// <returns>timestamp as an string</returns> public string GetTimestampFromApi(string url) { var client = new WebClient { Encoding = Encoding.UTF8 }; var result = client.DownloadString(url); return result; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Collections.Generic; using System.Linq; using ApartmentApps.Client.Models; using Microsoft.Rest; using Newtonsoft.Json.Linq; namespace ApartmentApps.Client.Models { public partial class AddBankAccountBindingModel { private string _accountHolderName; /// <summary> /// Required. /// </summary> public string AccountHolderName { get { return this._accountHolderName; } set { this._accountHolderName = value; } } private string _accountNumber; /// <summary> /// Required. /// </summary> public string AccountNumber { get { return this._accountNumber; } set { this._accountNumber = value; } } private string _friendlyName; /// <summary> /// Required. /// </summary> public string FriendlyName { get { return this._friendlyName; } set { this._friendlyName = value; } } private bool _isSavings; /// <summary> /// Required. /// </summary> public bool IsSavings { get { return this._isSavings; } set { this._isSavings = value; } } private string _routingNumber; /// <summary> /// Required. /// </summary> public string RoutingNumber { get { return this._routingNumber; } set { this._routingNumber = value; } } private string _userId; /// <summary> /// Optional. /// </summary> public string UserId { get { return this._userId; } set { this._userId = value; } } private IList<UserLookupBindingModel> _users; /// <summary> /// Optional. /// </summary> public IList<UserLookupBindingModel> Users { get { return this._users; } set { this._users = value; } } /// <summary> /// Initializes a new instance of the AddBankAccountBindingModel class. /// </summary> public AddBankAccountBindingModel() { this.Users = new LazyList<UserLookupBindingModel>(); } /// <summary> /// Serialize the object /// </summary> /// <returns> /// Returns the json model for the type AddBankAccountBindingModel /// </returns> public virtual JToken SerializeJson(JToken outputObject) { if (outputObject == null) { outputObject = new JObject(); } if (this.AccountHolderName == null) { throw new ArgumentNullException("AccountHolderName"); } if (this.AccountNumber == null) { throw new ArgumentNullException("AccountNumber"); } if (this.FriendlyName == null) { throw new ArgumentNullException("FriendlyName"); } if (this.RoutingNumber == null) { throw new ArgumentNullException("RoutingNumber"); } if (this.AccountHolderName != null) { outputObject["AccountHolderName"] = this.AccountHolderName; } if (this.AccountNumber != null) { outputObject["AccountNumber"] = this.AccountNumber; } if (this.FriendlyName != null) { outputObject["FriendlyName"] = this.FriendlyName; } outputObject["IsSavings"] = this.IsSavings; if (this.RoutingNumber != null) { outputObject["RoutingNumber"] = this.RoutingNumber; } if (this.UserId != null) { outputObject["UserId"] = this.UserId; } JArray usersSequence = null; if (this.Users != null) { if (this.Users is ILazyCollection<UserLookupBindingModel> == false || ((ILazyCollection<UserLookupBindingModel>)this.Users).IsInitialized) { usersSequence = new JArray(); outputObject["Users"] = usersSequence; foreach (UserLookupBindingModel usersItem in this.Users) { if (usersItem != null) { usersSequence.Add(usersItem.SerializeJson(null)); } } } } return outputObject; } } }
using System; namespace Vlc.DotNet.Core { /// <summary> /// The event that is emited on a libvlc <c>AudioDevice</c> event /// </summary> public class VlcMediaPlayerAudioDeviceEventArgs : EventArgs { /// <summary> /// The constructor /// </summary> /// <param name="audioDevice">The audio device</param> public VlcMediaPlayerAudioDeviceEventArgs(string audioDevice) { this.Device = audioDevice; } /// <summary> /// The device /// </summary> public string Device { get; } } }
using kindergarden.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace kindergarden.Controllers { [LoginCheck] [RoleCheck(RoleName ="teacher")] public class TeacherUserController : Controller { private readonly KinderModelContext db = new KinderModelContext(); public ActionResult ListCalendarActivities() { return View(); } public ActionResult ListCalendarAktivitet() { int SchoolId = Convert.ToInt32(Session["schoolId"]); var model = db.CalendarActivities.Where(z => z.SchoolId == SchoolId).ToList(); var secenek = new object(); secenek = model.Select(k => new { id = k.Id, title = k.Text, start = k.StartDate.AddHours(2), end = k.FinishDate.AddHours(2), }); return Json(secenek, JsonRequestBehavior.AllowGet); } public ActionResult AllActivities() { int SchoolId = Convert.ToInt32(Session["schoolId"]); var model = db.activities.Where(p => p.isActive == true && p.SchoolId == SchoolId).ToList(); return View(model); } public ActionResult DetailActivity(int Id) { var model = db.activities.Where(p => p.Id == Id).FirstOrDefault(); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult CommentActivities(activitiesMessage activitiesMessage) { string owner = Convert.ToString(Session["name"]); activitiesMessage.isActive = true; activitiesMessage.messageDate = DateTime.Now; activitiesMessage.messageOwner = owner; db.activitiesMessage.Add(activitiesMessage); db.SaveChanges(); return RedirectToAction("DetailActivity", new { Id = activitiesMessage.activitiesId }); } public ActionResult AllNews() { int SchoolId = Convert.ToInt32(Session["schoolId"]); var model = db.news.Where(p => p.SchoolId == SchoolId).ToList(); return View(model); } public ActionResult NewsDetail(int Id) { var model = db.news.Find(Id); if (model != null) { return View(model); } return RedirectToAction("AllNews"); } public ActionResult ListGallery() { int SchoolId = Convert.ToInt32(Session["schoolId"]); var model = db.gallery.Where(p => p.SchoolId == SchoolId).ToList(); return View(model); } public ActionResult ShowGallery(int galleryId) { var model = db.galleryimage.Where(p => p.galleryId == galleryId).ToList(); ViewBag.GalleryName = db.gallery.Find(galleryId).name; return View(model); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using Fbtc.Domain.Entities; using System.Collections.Generic; namespace Fbtc.Application.Interfaces { public interface IUnidadeFederacaoApplication { IEnumerable<UnidadeFederacao> GetAll(); IEnumerable<UnidadeFederacao> GetDisponiveis(int atcId); IEnumerable<UnidadeFederacao> GetUtilizadas(); } }
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 Hackathon_5_Advance { public partial class Form1 : Form { Dictionary<int, string> myConstellation; Dictionary<string, Constellation> data; string constellation; public Form1() { InitializeComponent(); } private void analysisButton_Click(object sender, EventArgs e) { int sum = 0; string yourBirthDay = dateTimePicker1.Value.ToShortDateString(); string[] cut = yourBirthDay.Split('/'); for(int i=0;i<cut.Length;i++) { char[] firstTemp = cut[i].ToCharArray(); for(int j=0;j<firstTemp.Length;j++) { sum += int.Parse(firstTemp[j].ToString()); } } while(sum > 9) { char[] secondTemp = sum.ToString().ToCharArray(); sum = 0; for (int i = 0; i < secondTemp.Length; i++) { sum += int.Parse(secondTemp[i].ToString()); } } /* string constellation = GetAtomFromBirthday(dateTimePicker1.Value);*/ data = findConstellation(); int yourYear = int.Parse(cut[0]); int yourMonth = int.Parse(cut[1]); int yourDay = int.Parse(cut[2]); DateTime yourDt = new DateTime(yourYear,yourMonth,yourDay); foreach(var dt in data) { if(dt.Value.startDate <= yourDt && yourDt <= dt.Value.endDate) { constellation = dt.Key.ToString(); } } switch (constellation) { case "牡羊座": myConstellation = CreateAries(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "金牛座": myConstellation = CreateTaurus(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "雙子座": myConstellation = CreateGemini(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "巨蟹座": myConstellation = CreateCancer(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "獅子座": myConstellation = CreateLeo(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "處女座": myConstellation = CreateVirgo(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "天秤座": myConstellation = CreateLibra(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "天蠍座": myConstellation = CreateScorpio(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "射手座": myConstellation = CreateSagittarius(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "摩羯座": myConstellation = CreateCapricorn(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "水瓶座": myConstellation = CreateAquarius(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; case "雙魚座": myConstellation = CreatePieces(); label2.Text = "你的星座是" + constellation + Environment.NewLine + "你的生命靈數" + sum + Environment.NewLine + myConstellation[sum]; break; default: break; } } public string GetAtomFromBirthday(DateTime dtBirthDay) { float fBirthDay = Convert.ToSingle(dtBirthDay.ToString("M.dd")); float[] atomBound = { 1.20F, 2.20F, 3.21F, 4.21F, 5.21F, 6.22F, 7.23F, 8.23F, 9.23F, 10.23F, 11.21F, 12.22F, 13.20F }; string[] atoms = { "水瓶座", "雙魚座", "牡羊座", "金牛座", "雙子座", "巨蟹座", "獅子座", "處女座", "天秤座", "天蠍座", "射手座", "魔羯座" }; string ret = string.Empty; for (int i = 0; i < atomBound.Length - 1; i++) { if (atomBound[i] <= fBirthDay && atomBound[i + 1] > fBirthDay) { ret = atoms[i]; break; } } return ret; } private Dictionary<string,Constellation> findConstellation() { var result = new Dictionary<string, Constellation>(); result.Add("白羊座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 3, 21), endDate = new DateTime(dateTimePicker1.Value.Year, 4, 19) }); result.Add("金牛座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 4, 20), endDate = new DateTime(dateTimePicker1.Value.Year, 5, 20) }); result.Add("雙子座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 5, 21), endDate = new DateTime(dateTimePicker1.Value.Year, 6, 21) }); result.Add("巨蠍座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 6, 22), endDate = new DateTime(dateTimePicker1.Value.Year, 7, 22) }); result.Add("獅子座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 7, 23), endDate = new DateTime(dateTimePicker1.Value.Year, 8, 22) }); result.Add("處女座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 8, 23), endDate = new DateTime(dateTimePicker1.Value.Year, 9, 22) }); result.Add("天秤座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 9, 23), endDate = new DateTime(dateTimePicker1.Value.Year, 10, 23) }); result.Add("天蠍座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 10, 24), endDate = new DateTime(dateTimePicker1.Value.Year, 11, 21) }); result.Add("射手座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 11, 22), endDate = new DateTime(dateTimePicker1.Value.Year, 12, 20) }); result.Add("魔蠍座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 12, 21), endDate = new DateTime(dateTimePicker1.Value.Year, 1, 20) }); result.Add("水瓶座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 1, 21), endDate = new DateTime(dateTimePicker1.Value.Year, 2, 19) }); result.Add("雙魚座", new Constellation { startDate = new DateTime(dateTimePicker1.Value.Year, 2, 20), endDate = new DateTime(dateTimePicker1.Value.Year, 3, 20) }); return result; } /// <summary> /// 牡羊座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateAries() { var result = new Dictionary<int, string>(); result.Add(1, "你是個主觀很強的人,只想著自己想做的事。"); result.Add(2, "你會在意別人看你的眼光,個性比較害羞一點。"); result.Add(3, "喜歡錶達自己的想法,但也要多聽聽別人的意見哦!"); result.Add(4, "你對未來很關心,很少胡思亂想,會腳踏實地的努力。"); result.Add(5, "最愛玩的Aries牧羊非你莫屬,尤其喜歡到處去湊熱鬧。"); result.Add(6, "你很固執哦!尤其是感情層面,而且非常的主觀。"); result.Add(7, "對於自己覺得有理的地方非常的堅持,不聽別人的意見。"); result.Add(8, "很重視實際層面的成就,會很努力在學習和工作上。"); result.Add(9, "你是較不切實際的人,不過你的熱情可將不可能變可能。"); return result; } /// <summary> /// 金牛座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateTaurus() { var result = new Dictionary<int, string>(); result.Add(1, "你的行動力很強,對事自有一套,做法也不喜歡受干涉。"); result.Add(2, "你會重視人際關係,在與別人相處時也比較容易受影響。"); result.Add(3, "你是牛座中比較靈活的,喜歡發表自己所研究出來的事物。"); result.Add(4, "你是牛座中最固執的哦!你的想法常常和別人不太一樣。"); result.Add(5, "你是一隻多才多藝的牛,如果能夠定下來會更有成就。"); result.Add(6, "你是最念舊的牛座,對於自己重視的東西會非常呵護。"); result.Add(7, "你是有叛逆性格的牛牛,不易被別人說服,自有一套想法。"); result.Add(8, "你很重視實際層面的成就,會努力讓自己更加的優秀或成功。"); result.Add(9, "你是牛座中最有夢想的,但是要多學習如何落實在現實中。"); return result; } /// <summary> /// 雙子座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateGemini() { var result = new Dictionary<int, string>(); result.Add(1, "喜歡自由自在的你,對於自己有興趣的事情都會去鑽研哦!"); result.Add(2, "你是最喜歡與別人溝通的Gemini雙子座,不過很容易受外來的影響。"); result.Add(3, "你真的是Gemini雙子座中最為多才多藝的,什麼東西都是一學就會。"); result.Add(4, "你是比較重視生活規律的人,看來隨和但自有一套規則。"); result.Add(5, "喜歡到處亂跑的你真是交友滿天下,心性上也比較不穩定。"); result.Add(6, "你是Gemini雙子中最重視人情味的,尤其重視老朋友之間的感情。"); result.Add(7, "你是Gemini雙子中最刁鑽古怪的,常想些別人都不會想到的問題。"); result.Add(8, "你喜歡享受生活,會特別的注重自己的生活品質。"); result.Add(9, "你是Gemini雙子中最會胡思亂想的,同時也是比較熱情的。"); return result; } /// <summary> /// 巨蟹座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateCancer() { var result = new Dictionary<int, string>(); result.Add(1, "你個性上有點自閉哦!不容易真正和別人有好的交流。"); result.Add(2, "會很看重別人的意見,要小心因此喪失自己的意見。"); result.Add(3, "喜歡感情上的表達與溝通,在藝術上會有不錯的天份哩!"); result.Add(4, "你是蟹子中比較龜毛的,尤其重視自己生活上的規律。"); result.Add(5, "你不一定喜歡亂跑,但不能受到太多拘束,想自由自在。"); result.Add(6, "你是蟹座中最重感情的,尤其在感情世界里很要求完美。"); result.Add(7, "你是蟹子中想得最多的,表現出來的模樣也頗為固執己見。"); result.Add(8, "你很重視現實上的成就與穩定,會努力讓自己的生活更好。"); result.Add(9, "你是蟹子中相當熱情的,但剛到新的環境會比較害羞。"); return result; } /// <summary> /// 獅子座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateLeo() { var result = new Dictionary<int, string>(); result.Add(1, "你是Leo獅子座中最為自我的,但可能因此造成人際問題。"); result.Add(2, "別人的肯定對你來說非常重要,可能因此而失去自我。"); result.Add(3, "你是Leo獅子座中最愛表現自己的,通常是人際關係中的佼佼者。"); result.Add(4, "你是只固執的Leo獅子,而且在行動上比較缺乏冒險犯難的精神。"); result.Add(5, "Leo獅子中最熱愛自由的就是你啦!一般來說你們是相當大方的。"); result.Add(6, "你是Leo獅子座中比較龜毛的,尤其是感情的表達上會顯得害羞。"); result.Add(7, "你是很會想的Leo獅子座哦!雖然比較主觀,但還可以溝通。"); result.Add(8, "你是一個講究生活品味的人哦!喜歡從容優渥的過日子。"); result.Add(9, "你的熱情很容易感動別人,在人群中常是人氣很旺的明星哩!"); return result; } /// <summary> /// 處女座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateVirgo() { var result = new Dictionary<int, string>(); result.Add(1, "你有點孤僻,常常覺得別人不了解你,要多與別人互動才好。"); result.Add(2, "你會很注重每個人的意見,與別人來往時也是非常誠懇的。"); result.Add(3, "能力頗佳的你,適合擔任發言或主持的任務,會勝任愉快哦!"); result.Add(4, "你是Virgo處女座中最為 ? t毛的,尤其容易劃地自限,要特別注意。"); result.Add(5, "你是屬於比較外向的,容易交到許多朋友,但知心的並不多。"); result.Add(6, "你是非常非常念舊的人哦!尤其是感情上,常常很難割捨。"); result.Add(7, "你的個性比較剛直,不過在與人交往上還是要多體諒別人哦!"); result.Add(8, "你是比較圓滑的人,很了解人際上的交流要如何互動。"); result.Add(9, "對你投入的事情非常的狂熱,有時甚至因此而廢寢忘食。"); return result; } /// <summary> /// 天秤座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateLibra() { var result = new Dictionary<int, string>(); result.Add(1, "你是秤子中比較獨立的,在決定事情時也比較不會猶豫不決。"); result.Add(2, "在秤子中你是最需要別人陪伴的,如果沒有伴會感到不安。"); result.Add(3, "你是秤子中最有才華的,在各項藝術領域都有不錯的天份。"); result.Add(4, "你是秤子中最為重視實際層面的,也是比較有責任感的哦!"); result.Add(5, "你是一隻喜愛交遊的Libra天秤,對感到好玩的事情都不會放過。"); result.Add(6, "感情的順利與否對你來說非常重要哦!要小心的經營才好。"); result.Add(7, "你是秤子中最喜歡思考的,對許多事都會找出合理的方法。"); result.Add(8, "很重視生活的感覺,不能忍受太差的生活環境,有雅癖傾向。"); result.Add(9, "你許多想法都有些不切實際,而且熱情常常無法持久哦!"); return result; } /// <summary> /// 天蠍座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateScorpio() { var result = new Dictionary<int, string>(); result.Add(1, "你很重視自己的目標,不太理睬身邊其他人在做些什麼。"); result.Add(2, "你很在乎兩人關係上的忠誠,會全心全意的對待另一半。"); result.Add(3, "對於溝通與人際關係是你的專長,總能夠得到大家幫助。"); result.Add(4, "你是非常非常固執的,一旦你決定的事就難以改變。"); result.Add(5, "你是蠍子中最開朗的,也是最容易與大家打成一片的。"); result.Add(6, "你是個完美主義者,尤其是非常重視感情方面的經營。"); result.Add(7, "你想的很多,常想到一些別人找不到的問題,非常聰明。"); result.Add(8, "你很重視自己的地社會地位,認為應該得到的就會去爭取。"); result.Add(9, "對於你喜歡或相信的事是非常狂熱的,但表面上看不出來。"); return result; } /// <summary> /// 射手座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateSagittarius() { var result = new Dictionary<int, string>(); result.Add(1, "你常常我行我素,一有目標就會很快去執行,行動力很強。"); result.Add(2, "喜歡與別人溝通相處的你,在人際上會得到大家的幫忙。"); result.Add(3, "你是相當有才華的人哦!很能夠表現自己在藝術上的才華。"); result.Add(4, "你是Sagittarius射手座中最重視生活規律的,而且也很有自己的想法。"); result.Add(5, "哇!你真是超愛亂跑,一直待在同一個地方會讓你很難過。"); result.Add(6, "你是很重視親情的人哦!在人際交流上也是很有一套的。"); result.Add(7, "你真是想得太多,又有點固執的人,懷疑的心態很強哦!"); result.Add(8, "你很重視自己的成就和外在的表現,喜歡富裕的生活環境。"); result.Add(9, "你是很有理想的人,也是舉辦活動的高手,受到大家歡迎!"); return result; } /// <summary> /// 摩羯座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateCapricorn() { var result = new Dictionary<int, string>(); result.Add(1, "你的自尊心很強哦!會默默的努力讓自己有所成就。"); result.Add(2, "你覺得與人交遊是件重要的事,另外感情也是生活重心。"); result.Add(3, "只要你多加努力就能展現出自己的才華,會很有成就哦!"); result.Add(4, "你很重視腳踏實地的生活,會努力讓自己生活穩定下來。"); result.Add(5, "你是Capricorn摩羯座中比較開朗的,對一些事比較不會那麼憂慮。"); result.Add(6, "感情是你生活平穩的重點,希望經營有未來的感情生活。"); result.Add(7, "你是一個非常聰明的人,但有時會因情緒化而下錯判斷。"); result.Add(8, "對你來說功成名就吸引力大,會努力成為重要的人物。"); result.Add(9, "你對自己想做的事非常投入,不過有時會忘了實際狀況。"); return result; } /// <summary> /// 水瓶座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreateAquarius() { var result = new Dictionary<int, string>(); result.Add(1, "你是瓶子座中最自閉的,有時候會顯得太過我行我素了些。"); result.Add(2, "你會比較受到別人的影響,但還不會失去自己原本的主張。"); result.Add(3, "你是一隻多才多藝的瓶子哩!尤其擅長於表達與溝通哦!"); result.Add(4, "你是瓶子中比較穩定的,會習慣維持某一種生活的方式。"); result.Add(5, "常常讓人找不到的就是你這種瓶子啦!朋友也是多不勝數。"); result.Add(6, "你是比較重感情的瓶子,也比較桃花,感情問題會比較多。"); result.Add(7, "你是瓶子中最為理性的,太過聰明的話有時候會不近人情。"); result.Add(8, "你是瓶子中比較重視物質的,會去追求自己所想要的生活。"); result.Add(9, "你的理想非常高遠,如果持續努力,成功的機會是很大的。"); return result; } /// <summary> /// 雙魚座生命靈數 /// </summary> /// <returns></returns> private static Dictionary<int, string> CreatePieces() { var result = new Dictionary<int, string>(); result.Add(1, "你容易沉溺在自己的世界的,忘掉了身邊還有別人存在。"); result.Add(2, "你很容易受到別人的引導,而忘記了自己原本的方向哦!"); result.Add(3, "你是天生的藝術家,不過還是要稍為注意一下現實環境。"); result.Add(4, "你是追求穩定生活的魚座,不喜歡太過混亂的生活。"); result.Add(5, "你比較沒有目標,幾乎什麼事都會去做做看,但都維持不久。"); result.Add(6, "感情是你最煩惱的事,常常因此而受到打擊或挫折。"); result.Add(7, "你想得很多,但是一旦遇到自己的事情就會比較主觀。"); result.Add(8, "你是喜歡享受的魚座,對於生活上的小事都非常的注意。"); result.Add(9, "你對於某些事都抱著很大的熱誠,過度的話會顯得特別偏執。"); return result; } } }
namespace Uintra.Features.Media.Strategies.Preset { public static class PresetStrategies { public static CentralFeedPresetStrategy ForCentralFeed = new CentralFeedPresetStrategy(); public static ActivityDetailsPresetStrategy ForActivityDetails = new ActivityDetailsPresetStrategy(); public static MemberProfilePresetStrategy ForMemberProfile = new MemberProfilePresetStrategy(); } }
using Epam.Shops.Entities; using Epam.Shops.Entities.Enums; using System; using System.Collections.Generic; namespace Epam.Shops.DAL.Interfaces { public interface IUserDAO { bool Add(User newUser); bool Remove(Guid id); bool Update(User user); User GetByEmail(string email); bool ContainsEmail(string email); IEnumerable<User> GetAll(); } }
using Aps.Repositories; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace Aps.Controllers { [ApiController] [Route("[controller]")] public class PaisesController : ControllerBase { private readonly PaisesRepo _repo; public PaisesController(PaisesRepo repo) { _repo = repo; } [HttpGet] public async Task<ActionResult<dynamic>> GetAll() { var resp = await _repo.GetPaises(); return Ok(resp); } [HttpGet("{paisId}")] public async Task<ActionResult<dynamic>> GetAll(int paisId) { var resp = await _repo.GetPaisById(paisId); return Ok(resp); } } }
using System; using System.Globalization; using System.Windows.Data; namespace MainTool.WPF.Converters { public class NumberSubtractionConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double v = 0; double p = 0; if (value is double v_double) { v = v_double; } else if (value is int v_int) { v = v_int; } else if ((value is string v_string) && double.TryParse(v_string, out v)) { } if (parameter is double p_double) { p = p_double; } else if (parameter is int p_int) { p = p_int; } else if ((parameter is string p_string) && double.TryParse(p_string, out p)) { } return v - p; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return Binding.DoNothing; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StaticExampleApp { static class Training { public static int Id { get; set; } public static string Name { get; set; } public static string SessionName { get; set; } public static int TotalHour { get; set; } public static int NumberOfTrainee { get; set; } public static string GetInfo(string name, string session) { return "Name : " + name + "SessionName : " + session; } } }
using System; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.TMS { [Serializable] public partial class TransportFlowRoute : EntityBase, IAuditable { #region O/R Mapping Properties public Int32 Id { get; set; } [Display(Name = "TransportFlowMaster_Code", ResourceType = typeof(Resources.TMS.TransportFlow))] public string Flow { get; set; } [Display(Name = "TransportFlow_Sequence", ResourceType = typeof(Resources.TMS.TransportFlow))] public Int32 Sequence { get; set; } [Display(Name = "TransportFlowRoute_ShipAddress", ResourceType = typeof(Resources.TMS.TransportFlow))] public string ShipAddress { get; set; } [Display(Name = "TransportFlowRoute_ShipAddressDescription", ResourceType = typeof(Resources.TMS.TransportFlow))] public string ShipAddressDescription { get; set; } [Display(Name = "Common_CreateUserName", ResourceType = typeof(Resources.SYS.Global))] public string CreateUserName { get; set; } public Int32 CreateUserId { get; set; } [Display(Name = "Common_CreateDate", ResourceType = typeof(Resources.SYS.Global))] public DateTime CreateDate { get; set; } [Display(Name = "Common_LastModifyUserName", ResourceType = typeof(Resources.SYS.Global))] public string LastModifyUserName { get; set; } public Int32 LastModifyUserId { get; set; } [Display(Name = "Common_LastModifyDate", ResourceType = typeof(Resources.SYS.Global))] public DateTime LastModifyDate { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { TransportFlowRoute another = obj as TransportFlowRoute; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System.Collections.Generic; using Profiling2.Domain.Contracts.Queries.Stats; using SharpArch.NHibernate; using System; using Profiling2.Domain.Scr; namespace Profiling2.Infrastructure.Queries.Stats { public class ScreeningCountsQuery : NHibernateQuery, IScreeningCountsQuery { // SELECT YEAR(h.DateStatusReached) AS year, MONTH(h.DateStatusReached) AS month, COUNT(h.ScreeningRequestPersonFinalDecisionID) //FROM [undp-drc-profiling].[dbo].[SCR_ScreeningRequestPersonFinalDecisionHistory] h //GROUP BY YEAR(h.DateStatusReached), MONTH(h.DateStatusReached) //ORDER BY YEAR(h.DateStatusReached) DESC, MONTH(h.DateStatusReached) DESC //public IList<object[]> GetFinalDecsionCount() //{ // return Session.QueryOver<ScreeningRequestPersonFinalDecisionHistory>() // .Select( // //Projections.Group<ScreeningRequestPersonFinalDecisionHistory>(x => x.DateStatusReached.Year), // Projections.SqlGroupProjection("YEAR(DateStatusReached) AS [Year]", "YEAR(DateStatusReached)", new string[] { "YEAR" }, new IType[] { NHibernateUtil.Int32 }), // //Projections.Group<ScreeningRequestPersonFinalDecisionHistory>(x => x.DateStatusReached.Month), // Projections.SqlGroupProjection("MONTH(DateStatusReached) AS [Month]", "MONTH(DateStatusReached)", new string[] { "MONTH" }, new IType[] { NHibernateUtil.Int32 }), // Projections.Count<ScreeningRequestPersonFinalDecisionHistory>(x => x.ScreeningRequestPersonFinalDecision) // ) // //.OrderBy(x => x.DateStatusReached.Year).Desc // .OrderBy(Projections.SqlFunction("YEAR", NHibernateUtil.Int32, Projections.Property<ScreeningRequestPersonFinalDecisionHistory>(x => x.DateStatusReached))).Asc // //.ThenBy(x => x.DateStatusReached.Month).Desc // .ThenBy(Projections.SqlFunction("MONTH", NHibernateUtil.Int32, Projections.Property<ScreeningRequestPersonFinalDecisionHistory>(x => x.DateStatusReached))).Asc // .List<object[]>(); //} /* Returns number of final screening results, by person, sorted by month. * Final screening results are only included if: * - the original request was completed; * - the original request was not archived. * An individual may be screened more than once, but is counted each time they are screened. */ public IList<object[]> GetFinalDecisionCountByMonth() { string sql = @"SELECT YEAR(filtered.DateStatusReached) AS year, MONTH(filtered.DateStatusReached) AS month, COUNT(filtered.ScreeningRequestPersonFinalDecisionID) FROM ( SELECT latestHistory.* FROM SCR_Request r CROSS APPLY ( SELECT TOP 1 rh.* FROM SCR_RequestHistory rh WHERE rh.RequestID = r.RequestID ORDER BY rh.DateStatusReached DESC ) AS latestRequestHistory, SCR_RequestPerson rp, SCR_ScreeningRequestPersonFinalDecision fd CROSS APPLY ( SELECT TOP 1 h.* FROM SCR_ScreeningRequestPersonFinalDecisionHistory h WHERE h.ScreeningRequestPersonFinalDecisionID = fd.ScreeningRequestPersonFinalDecisionID ORDER BY h.DateStatusReached DESC ) AS latestHistory WHERE fd.RequestPersonID = rp.RequestPersonID AND rp.RequestID = r.RequestID AND r.Archive = 0 AND latestRequestHistory.RequestStatusID = 8 ) AS filtered GROUP BY YEAR(filtered.DateStatusReached), MONTH(filtered.DateStatusReached) ORDER BY YEAR(filtered.DateStatusReached) ASC, MONTH(filtered.DateStatusReached) ASC "; return Session.CreateSQLQuery(sql).List<object[]>(); } public IList<object[]> GetFinalDecisionCountByRequestEntity(DateTime start, DateTime end) { string sql = @" SELECT re.RequestEntityName, COUNT(p.personID) FROM SCR_RequestPerson p, SCR_Request r CROSS APPLY ( SELECT TOP 1 x.* FROM SCR_RequestHistory x WHERE x.RequestID = r.RequestID ORDER BY x.DateStatusReached desc ) as rh, SCR_RequestEntity re, SCR_RequestStatus rs, SCR_ScreeningRequestPersonFinalDecision d CROSS APPLY ( SELECT TOP 1 this.DateStatusReached FROM SCR_ScreeningRequestPersonFinalDecisionHistory AS this WHERE this.ScreeningRequestPersonFinalDecisionID = d.ScreeningRequestPersonFinalDecisionID ORDER BY DateStatusReached DESC ) AS h WHERE p.RequestPersonID = d.RequestPersonID AND p.RequestID = r.RequestID AND r.Archive = 0 AND rs.RequestStatusID = rh.RequestStatusID AND rs.RequestStatusName = :requestStatusName AND r.RequestEntityID = re.RequestEntityID AND h.DateStatusReached BETWEEN :startDate AND :endDate GROUP BY re.RequestEntityName ORDER BY re.RequestEntityName "; return Session.CreateSQLQuery(sql) .SetString("requestStatusName", RequestStatus.NAME_COMPLETED) .SetDateTime("startDate", start) .SetDateTime("endDate", end) .List<object[]>(); } } }
 namespace Sfa.Poc.ResultsAndCertification.Dfe.Models { public class TqProviderDetails { public int Id { get; set; } public int AwardingOrganisationId { get; set; } public int ProviderId { get; set; } public int RouteId { get; set; } public int PathwayId { get; set; } public int SpecialismId { get; set; } } }
using System.ComponentModel.DataAnnotations; namespace Pobs.Web.Models.Questions { public class ReportModel { [Required] public string Reason { get; set; } } }
using SciVacancies.Domain.Aggregates; using System; using CommonDomain.Persistence; using MediatR; namespace SciVacancies.WebApp.Commands { public class CreateOrganizationCommandHandler : IRequestHandler<CreateOrganizationCommand, Guid> { private readonly IRepository _repository; public CreateOrganizationCommandHandler(IRepository repository) { _repository = repository; } public Guid Handle(CreateOrganizationCommand msg) { Organization organization = new Organization(Guid.NewGuid(), msg.Data); _repository.Save(organization, Guid.NewGuid(), null); return organization.Id; } } public class UpdateOrganizationCommandHandler : RequestHandler<UpdateOrganizationCommand> { private readonly IRepository _repository; public UpdateOrganizationCommandHandler(IRepository repository) { _repository = repository; } protected override void HandleCore(UpdateOrganizationCommand msg) { if (msg.OrganizationGuid == Guid.Empty) throw new ArgumentNullException($"OrganizationGuid is empty: {msg.OrganizationGuid}"); Organization organization = _repository.GetById<Organization>(msg.OrganizationGuid); organization.Update(msg.Data); _repository.Save(organization, Guid.NewGuid(), null); } } public class RemoveOrganizationCommandHandler : RequestHandler<RemoveOrganizationCommand> { private readonly IRepository _repository; public RemoveOrganizationCommandHandler(IRepository repository) { _repository = repository; } protected override void HandleCore(RemoveOrganizationCommand msg) { if (msg.OrganizationGuid == Guid.Empty) throw new ArgumentNullException($"OrganizationGuid is empty: {msg.OrganizationGuid}"); Organization organization = _repository.GetById<Organization>(msg.OrganizationGuid); organization.Remove(); _repository.Save(organization, Guid.NewGuid(), null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ManageDomain { public enum SystemPermissionKey { None, [PermissionKey("", "员工管理", "")] Manager, [PermissionKey("manager.add", "添加员工", "员工管理")] Manager_Add, [PermissionKey("manager.delete", "删除员工", "员工管理")] Manager_Delete, [PermissionKey("manager.show", "查看员工", "员工管理")] Manager_Show, [PermissionKey("manager.update", "修改员工", "员工管理")] Manager_Update, [PermissionKey("", "分组标签", "")] UserTag, [PermissionKey("usertag.show", "查看分组标签", "分组标签")] UserTag_Show, [PermissionKey("usertag.add", "添加分组标签", "分组标签")] UserTag_Add, [PermissionKey("usertag.delete", "删除分姐标签", "分组标签")] UseTag_Delete, [PermissionKey("", "客户管理", "")] Customer, [PermissionKey("customer.add", "添加客户", "客户管理")] Customer_Add, [PermissionKey("customer.delete", "删除客户", "客户管理")] Customer_Delete, [PermissionKey("customer.show", "查看客户", "客户管理")] Customer_Show, [PermissionKey("customer.update", "修改客户", "客户管理")] Customer_Update, //[PermissionKey("feedback.show", "查看客户反馈问题", "客户管理")] //FeedBack_Show, //[PermissionKey("feedback.edit", "修改反馈问题", "客户管理")] //FeedBack_Update, //[PermissionKey("feedback.add", "添加反馈问题", "客户管理")] //FeedBack_Add, [PermissionKey("", "客户服务记录", "")] Customer_ServiceLog, [PermissionKey("customer.servicelog.show", "查看服务记录", "客户服务记录")] Customer_ServiceLog_Show, [PermissionKey("customer.servicelog.add", "添加服务记录", "客户服务记录")] Customer_ServiceLog_Add, [PermissionKey("customer.servicelog.delete", "删除服务记录", "客户服务记录")] Customer_ServiceLog_Delete, [PermissionKey("customer.probation.show", "查看18直播试用记录", "客户服务记录")] Customer_Probation_Show, [PermissionKey("", "客户反馈列表", "")] Customer_Feedback, [PermissionKey("customer.feedback.show", "查看客户反馈信息", "客户反馈列表")] Customer_Feedback_Show, [PermissionKey("customer.feedback.add", "添加客户反馈信息", "客户反馈列表")] Customer_Feedback_Add, [PermissionKey("customer.feedback.update", "修改客户反馈信息", "客户反馈列表")] Customer_Feedback_Update, [PermissionKey("customer.feedback.delete", "删除客户反馈信息", "客户反馈列表")] Customer_Feedback_Delete, [PermissionKey("customer.feedback.check", "审核客户反馈信息", "客户反馈列表")] Customer_Feedback_Check, [PermissionKey("", "服务器管理", "")] Server, [PermissionKey("server.show", "查看服务器", "服务器管理")] Server_Show, [PermissionKey("server.add", "添加服务器", "服务器管理")] Server_Add, [PermissionKey("server.update", "修改服务器", "服务器管理")] Server_Update, [PermissionKey("server.delete", "删除服务器", "服务器管理")] Server_Delete, [PermissionKey("operationlog.show", "查看操作日志", "服务器管理")] OperationLog_Show, [PermissionKey("", "开发项目管理", "")] Project, [PermissionKey("project.show", "查看项目", "开发项目管理")] Project_Show, [PermissionKey("project.add", "添加项目", "开发项目管理")] Project_Add, [PermissionKey("project.update", "修改项目", "开发项目管理")] Project_Update, [PermissionKey("project.delete", "删除项目", "开发项目管理")] Project_Delete, [PermissionKey("", "服务器项目管理", "")] ServerProject, [PermissionKey("serverproject.show", "查看服务器项目", "服务器项目管理")] ServerProject_Show, [PermissionKey("serverproject.add", "添加服务器项目", "服务器项目管理")] ServerProject_Add, [PermissionKey("serverproject.update", "更新服务器项目", "服务器项目管理")] ServerProject_Update, [PermissionKey("serverproject.delete", "删除服务器项目", "服务器项目管理")] ServerProject_Delete, [PermissionKey("", "命令管理", "")] Command, [PermissionKey("command.show", "查看命令", "命令管理")] Command_Show, [PermissionKey("command.add", "添加命令", "命令管理")] Command_Add, [PermissionKey("command.delete", "删除命令", "命令管理")] Command_Delete, [PermissionKey("", "工作任务", "")] WorkItem, [PermissionKey("workitem.show", "查看工作任务", "工作任务")] WorkItem_Show, [PermissionKey("workitem.add", "添加工作任务", "工作任务")] WorkItem_Add, [PermissionKey("workitem.update", "更新工作任务", "工作任务")] WorkItem_Update, [PermissionKey("workitem.delete", "删除工作任务", "工作任务")] WorkItem_Delete, [PermissionKey("workitem.summary", "任务汇总", "工作任务")] WorkItem_summary, [PermissionKey("workitem.execwork", "执行工作任务", "工作任务")] WorkItem_ExecWork, [PermissionKey("", "工作日志", "")] WorkDaily, [PermissionKey("workdaily.show", "查看工作日志", "工作日志")] WorkDaily_Show, [PermissionKey("workdaily.showother", "查看别人工作日志", "工作日志")] WorkDaily_ShowOther, [PermissionKey("workdaily.add", "添加工作日志", "工作日志")] WorkDaily_Add, [PermissionKey("workdaily.update", "修改工作日志", "工作日志")] WorkDaily_Update, [PermissionKey("workdaily.delete", "删除工作日志", "工作日志")] WorkDaily_Delete, [PermissionKey("workdaily.deleteother", "删除别人的工作日志", "工作日志")] WorkDaily_DeleteOther, [PermissionKey("workdaily.report", "工作日志报表", "工作日志")] WorkDaily_Report, [PermissionKey("", "监控日志", "")] WatchLog, [PermissionKey("watchlog.commlog", "普通日志", "监控日志")] WatchLog_CommLog, [PermissionKey("watchlog.errorlog", "错误日志", "监控日志")] WatchLog_ErrorLog, [PermissionKey("watchlog.timewatch", "耗时日志", "监控日志")] WatchLog_TimeWatch, [PermissionKey("", "任务管理", "")] Task, [PermissionKey("task.show", "查看任务", "任务管理")] Task_Show, [PermissionKey("task.add", "添加任务", "任务管理")] Task_Add, [PermissionKey("task.update", "修改任务", "任务管理")] Task_Update, [PermissionKey("task.delete", "删除任务", "任务管理")] Task_Delete, [PermissionKey("Performance.show", "查看服务器性能", "")] Performance, [PermissionKey("webexception.show", "显示网站操作异常", "")] ShowWebException, } public class PermissionKeyAttribute : Attribute { public string Key { get; private set; } public string Name { get; private set; } public string Group { get; private set; } public string ParentGroup { get; private set; } public PermissionKeyAttribute(string key, string name) : this(key, name, "") { } public PermissionKeyAttribute(string key, string name, string groupname) { this.Key = key; this.Name = name; this.Group = groupname ?? ""; } } }
using BO; using SiteWeb.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Tools; namespace SiteWeb.Controllers { public class WarriorController : Controller { private static List<Warrior> warriors = new List<Warrior>(); private static List<Weapon> weapons; private static int compteur = 1; // GET: Warrior public ActionResult Index() { var id = 1; if (weapons == null) { weapons = new List<Weapon> { new Weapon {Id=id++,Nom="Excalibur",DegatMax=100,DegatMin=50 }, new Weapon {Id=id++,Nom="Masamune",DegatMax=150,DegatMin=10 }, new Weapon {Id=id++,Nom="DeathWhisper",DegatMax=90,DegatMin=70 }, new Weapon {Id=id++,Nom="BF Sword",DegatMax=80,DegatMin=80 }, new Weapon {Id=id++,Nom="BloodThirster",DegatMax=200,DegatMin=0 }, }; } if (warriors.Count == 0) { warriors.Add(new Warrior { Id = compteur++, NomPropre = "Roger Le Lapinou méchant", Titre = "Barbare des cités" }); } return View(warriors); } // GET: Warrior/Details/5 public ActionResult Details(int id) { return View(warriors.GetById(id)); } // GET: Warrior/Create public ActionResult Create() { return CreateEdit(); } private ActionResult CreateEdit(Warrior warrior = null) { var vm = new CreateEditWarriorVM(); vm.Warrior = warrior; vm.Weapons = weapons; if (warrior != null && warrior.Weapon != null) vm.IdSelectedWeapon = warrior.Weapon.Id; return View("CreateEdit", vm); } public ActionResult Edit(int id) { var warrior = warriors.GetById(id); if (warrior != null) return CreateEdit(warrior); return RedirectToAction("Index"); } // POST: Warrior/Create [HttpPost] public ActionResult Create(CreateEditWarriorVM vm) { try { if (vm?.Warrior != null) { vm.Warrior.Id = warriors.Max(w => w.Id) + 1; if (vm.IdSelectedWeapon.HasValue) { var weapon = weapons.GetById(vm.IdSelectedWeapon.Value); vm.Warrior.Weapon = weapon; } warriors.Add(vm.Warrior); return RedirectToAction("Index"); } } catch (Exception ex) { ModelState.AddModelError("Custom", ex.Message); } vm.Weapons = weapons; return View(vm); } // POST: Warrior/Edit/5 [HttpPost] public ActionResult Edit(CreateEditWarriorVM vm) { try { var warriorDB = warriors.GetById(vm.Warrior.Id); warriorDB.NomPropre = vm.Warrior.NomPropre; warriorDB.Titre = vm.Warrior.Titre; if (vm.IdSelectedWeapon.HasValue) { var weapon = weapons.GetById(vm.IdSelectedWeapon.Value); warriorDB.Weapon = weapon; } return RedirectToAction("Index"); } catch { } vm.Weapons = weapons; return View(vm); } // GET: Warrior/Delete/5 public ActionResult Delete(int id) { return View(warriors.GetById(id)); } // POST: Warrior/Delete/5 [HttpPost] public ActionResult Delete(Warrior warrior) { try { var warriorToDelete = warriors.GetById(warrior.Id); if (warriorToDelete != null) warriors.Remove(warriorToDelete); } catch { //gestion des erreurs } return RedirectToAction("Index"); } } }
 using System; using System.Collections.Generic; using System.Linq; using MultiplayerEmotes.Framework.Network; using StardewModdingAPI; using StardewValley; using StardewValley.Buildings; using StardewValley.Network; namespace MultiplayerEmotes.Extensions { public static class MultiplayerExtension { public static void BroadcastEmote(this Multiplayer multiplayer, int emoteIndex, Character character) { if (!Game1.IsMultiplayer) { return; } EmoteMessage message = new EmoteMessage { EmoteIndex = emoteIndex }; switch (character) { case Farmer farmer: message.EmoteSourceId = farmer.UniqueMultiplayerID.ToString(); message.EmoteSourceType = CharacterType.Farmer; break; case NPC npc: message.EmoteSourceId = npc.Name; message.EmoteSourceType = CharacterType.NPC; break; case FarmAnimal farmAnimal: message.EmoteSourceId = farmAnimal.myID.Value.ToString(); message.EmoteSourceType = CharacterType.FarmAnimal; break; } ModEntry.MultiplayerMessage.Send(message); } #if DEBUG public static void TestFunc(string name, bool mustBeVillager = false) { if(Game1.currentLocation != null) { ModEntry.ModMonitor.Log($"- Loop1"); foreach(NPC character in (IEnumerable<NPC>)Game1.currentLocation.getCharacters()) { ModEntry.ModMonitor.Log($"Character: {character.Name}. IsVillager: {character.isVillager()}"); if(character.Name.Equals(name) && (!mustBeVillager || character.isVillager())) ModEntry.ModMonitor.Log($"### Found Character: {character}"); } } ModEntry.ModMonitor.Log($"- Loop2"); for(int index = 0; index < Game1.locations.Count; ++index) { foreach(NPC character in (IEnumerable<NPC>)Game1.locations[index].getCharacters()) { ModEntry.ModMonitor.Log($"Character: {character.Name}. IsVillager: {character.isVillager()}"); if(character.Name.Equals(name) && (!mustBeVillager || character.isVillager())) ModEntry.ModMonitor.Log($"### Found Character: {character.Name}"); } } if(Game1.getFarm() != null) { ModEntry.ModMonitor.Log($"- Loop3"); foreach(Building building in Game1.getFarm().buildings) { if(building.indoors.Value != null) { foreach(NPC character in building.indoors.Value.characters) { ModEntry.ModMonitor.Log($"Character: {character.Name}. IsVillager: {character.isVillager()}"); if(character.Name.Equals(name) && (!mustBeVillager || character.isVillager())) ModEntry.ModMonitor.Log($"### Found Character: {character.Name}"); } } } } } #endif [Obsolete("This method removal is planned. Is not longer in use.", true)] public static void ReceiveEmoteBroadcast(this Multiplayer multiplayer, IncomingMessage msg) { if(msg.Data.Length > 0) { int emoteIndex = msg.Reader.ReadInt32(); msg.SourceFarmer.IsEmoting = false; msg.SourceFarmer.doEmote(emoteIndex); #if DEBUG ModEntry.ModMonitor.Log($"Received player emote broadcast. (Name: \"{msg.SourceFarmer.Name}\", Emote: {emoteIndex})"); #endif } } [Obsolete("This method removal is planned. Is not longer in use.", true)] public static void ReceiveCharacterEmoteBroadcast(this Multiplayer multiplayer, IncomingMessage msg) { if(Context.IsPlayerFree && msg.Data.Length > 0) { int emoteIndex = msg.Reader.ReadInt32(); string characterId = msg.Reader.ReadString(); Character sourceCharacter = null; if(long.TryParse(characterId, out long id)) { sourceCharacter = (Game1.currentLocation as AnimalHouse).animals.Values.FirstOrDefault(x => x.myID.Value == id); } else { sourceCharacter = Game1.getCharacterFromName(characterId); } #if DEBUG TestFunc(characterId); ModEntry.ModMonitor.Log($"Received character emote broadcast. (Name: \"{sourceCharacter.Name}\", Emote: {emoteIndex})"); #endif if(sourceCharacter != null && !sourceCharacter.IsEmoting) { sourceCharacter.doEmote(emoteIndex, true); } } } } }
namespace Reacher.Notification.Pushover { public interface INotificationPushoverService { void Send(string title, string message); } }
using System; namespace wof { public class Word { private string word; public Word() { word = WordBank.GetWord().ToUpper(); } public override string ToString() { return word; } public bool DisplayWord() { string display = "\n"; string[] guesses = Round.GetGuesses(); int correct = 0; for (var i = 0; i < word.Length; i++) { if (Array.Exists(guesses, e => e == word[i].ToString())) { display += $" {word[i]} "; correct += 1; } else { if (word[i] != ' ') { display += "_ "; } else { display += " "; correct += 1; } } } display += "\n"; Console.Clear(); Console.WriteLine(display); return correct == word.Length; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebCrawler { public abstract class HandlerBase { public Requester req { get; set; } public abstract void Start(); public MissionHandleResult Completed() { return new MissionHandleResult(MissionHandleStatus.Completed); } public MissionHandleResult Failure(string message) { return new MissionHandleResult(MissionHandleStatus.Failure, message); } public MissionHandleResult Error(string message) { return new MissionHandleResult(MissionHandleStatus.Error, message); } } }
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace Vanara.PInvoke { public static partial class Ole32 { /// <summary> /// <para> /// Represents information about the effects of a drag-and-drop operation. The <c>DoDragDrop</c> function and many of the methods in /// the <c>IDropSource</c> and <c>IDropTarget</c> use the values of this enumeration. /// </para> /// </summary> /// <remarks> /// <para> /// Your application should always mask values from the <c>DROPEFFECT</c> enumeration to ensure compatibility with future /// implementations. Presently, only some of the positions in a <c>DROPEFFECT</c> value have meaning. In the future, more /// interpretations for the bits will be added. Drag sources and drop targets should carefully mask these values appropriately before /// comparing. They should never compare a <c>DROPEFFECT</c> against, say, DROPEFFECT_COPY by doing the following: /// </para> /// <para>Instead, the application should always mask for the value or values being sought as using one of the following techniques:</para> /// <para>This allows for the definition of new drop effects, while preserving backward compatibility with existing code.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/com/dropeffect-constants [PInvokeData("OleIdl.h", MSDNShortId = "d8e46899-3fbf-4012-8dd3-67fa627526d5")] // public static extern public enum DROPEFFECT : uint { /// <summary>Drop target cannot accept the data.</summary> DROPEFFECT_NONE = 0, /// <summary>Drop results in a copy. The original data is untouched by the drag source.</summary> DROPEFFECT_COPY = 1, /// <summary>Drag source should remove the data.</summary> DROPEFFECT_MOVE = 2, /// <summary>Drag source should create a link to the original data.</summary> DROPEFFECT_LINK = 4, /// <summary> /// Scrolling is about to start or is currently occurring in the target. This value is used in addition to the other values. /// </summary> DROPEFFECT_SCROLL = 0x80000000, } /// <summary> /// <para> /// The <c>IDropSource</c> interface is one of the interfaces you implement to provide drag-and-drop operations in your application. /// It contains methods used in any application used as a data source in a drag-and-drop operation. The data source application in a /// drag-and-drop operation is responsible for: /// </para> /// <list type="bullet"> /// <item> /// <term>Determining the data being dragged based on the user's selection.</term> /// </item> /// <item> /// <term>Initiating the drag-and-drop operation based on the user's mouse actions.</term> /// </item> /// <item> /// <term> /// Generating some of the visual feedback during the drag-and-drop operation, such as setting the cursor and highlighting the data /// selected for the drag-and-drop operation. /// </term> /// </item> /// <item> /// <term>Canceling or completing the drag-and-drop operation based on the user's mouse actions.</term> /// </item> /// <item> /// <term>Performing any action on the original data caused by the drop operation, such as deleting the data on a drag move.</term> /// </item> /// </list> /// <para> /// <c>IDropSource</c> contains the methods for generating visual feedback to the end user and for canceling or completing the /// drag-and-drop operation. You also need to call the DoDragDrop, RegisterDragDrop, and RevokeDragDrop functions in drag-and-drop operations. /// </para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nn-oleidl-idropsource [PInvokeData("oleidl.h", MSDNShortId = "963a36bc-4ad7-4591-bffc-a96b4310177d")] [ComImport, Guid("00000121-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDropSource { /// <summary> /// <para> /// Determines whether a drag-and-drop operation should be continued, canceled, or completed. You do not call this method /// directly. The OLE DoDragDrop function calls this method during a drag-and-drop operation. /// </para> /// </summary> /// <param name="fEscapePressed"> /// <para> /// Indicates whether the Esc key has been pressed since the previous call to <c>QueryContinueDrag</c> or to DoDragDrop if this /// is the first call to <c>QueryContinueDrag</c>. A <c>TRUE</c> value indicates the end user has pressed the escape key; a /// <c>FALSE</c> value indicates it has not been pressed. /// </para> /// </param> /// <param name="grfKeyState"> /// <para> /// The current state of the keyboard modifier keys on the keyboard. Possible values can be a combination of any of the flags /// MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON. /// </para> /// </param> /// <returns> /// <para>This method can return the following values.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>S_OK</term> /// <term> /// The drag operation should continue. This result occurs if no errors are detected, the mouse button starting the drag-and-drop /// operation has not been released, and the Esc key has not been detected. /// </term> /// </item> /// <item> /// <term>DRAGDROP_S_DROP</term> /// <term> /// The drop operation should occur completing the drag operation. This result occurs if grfKeyState indicates that the key that /// started the drag-and-drop operation has been released. /// </term> /// </item> /// <item> /// <term>DRAGDROP_S_CANCEL</term> /// <term> /// The drag operation should be canceled with no drop operation occurring. This result occurs if fEscapePressed is TRUE, /// indicating the Esc key has been pressed. /// </term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// The DoDragDrop function calls <c>QueryContinueDrag</c> whenever it detects a change in the keyboard or mouse button state /// during a drag-and-drop operation. <c>QueryContinueDrag</c> must determine whether the drag-and-drop operation should be /// continued, canceled, or completed based on the contents of the parameters grfKeyState and fEscapePressed. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nf-oleidl-idropsource-querycontinuedrag HRESULT QueryContinueDrag( // BOOL fEscapePressed, DWORD grfKeyState ); [PInvokeData("oleidl.h", MSDNShortId = "96ea44fc-5046-4e31-abfc-659d8ef3ca8f")] [PreserveSig] HRESULT QueryContinueDrag([MarshalAs(UnmanagedType.Bool)] bool fEscapePressed, uint grfKeyState); /// <summary> /// <para> /// Enables a source application to give visual feedback to the end user during a drag-and-drop operation by providing the /// DoDragDrop function with an enumeration value specifying the visual effect. /// </para> /// </summary> /// <param name="dwEffect"> /// <para>The DROPEFFECT value returned by the most recent call to IDropTarget::DragEnter, IDropTarget::DragOver, or IDropTarget::DragLeave.</para> /// </param> /// <returns> /// <para>This method returns S_OK on success. Other possible values include the following.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>DRAGDROP_S_USEDEFAULTCURSORS</term> /// <term> /// Indicates successful completion of the method, and requests OLE to update the cursor using the OLE-provided default cursors. /// </term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// When your application detects that the user has started a drag-and-drop operation, it should call the DoDragDrop function. /// <c>DoDragDrop</c> enters a loop, calling IDropTarget::DragEnter when the mouse first enters a drop target window, /// IDropTarget::DragOver when the mouse changes its position within the target window, and IDropTarget::DragLeave when the mouse /// leaves the target window. /// </para> /// <para> /// For every call to either IDropTarget::DragEnter or IDropTarget::DragOver, DoDragDrop calls <c>IDropSource::GiveFeedback</c>, /// passing it the DROPEFFECT value returned from the drop target call. /// </para> /// <para> /// DoDragDrop calls IDropTarget::DragLeave when the mouse has left the target window. Then, <c>DoDragDrop</c> calls /// <c>IDropSource::GiveFeedback</c> and passes the DROPEFFECT_NONE value in the dwEffect parameter. /// </para> /// <para> /// The dwEffect parameter can include DROPEFFECT_SCROLL, indicating that the source should put up the drag-scrolling variation /// of the appropriate pointer. /// </para> /// <para>Notes to Implementers</para> /// <para> /// This function is called frequently during the DoDragDrop loop, so you can gain performance advantages if you optimize your /// implementation as much as possible. /// </para> /// <para> /// <c>IDropSource::GiveFeedback</c> is responsible for changing the cursor shape or for changing the highlighted source based on /// the value of the dwEffect parameter. If you are using default cursors, you can return DRAGDROP_S_USEDEFAULTCURSORS, which /// causes OLE to update the cursor for you, using its defaults. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nf-oleidl-idropsource-givefeedback HRESULT GiveFeedback( DWORD // dwEffect ); [PInvokeData("oleidl.h", MSDNShortId = "dde37299-ad7c-4f59-af99-e75b72ad9188")] [PreserveSig] HRESULT GiveFeedback(DROPEFFECT dwEffect); } /// <summary> /// <para> /// The <c>IDropTarget</c> interface is one of the interfaces you implement to provide drag-and-drop operations in your application. /// It contains methods used in any application that can be a target for data during a drag-and-drop operation. A drop-target /// application is responsible for: /// </para> /// <list type="bullet"> /// <item> /// <term>Determining the effect of the drop on the target application.</term> /// </item> /// <item> /// <term>Incorporating any valid dropped data when the drop occurs.</term> /// </item> /// <item> /// <term> /// Communicating target feedback to the source so the source application can provide appropriate visual feedback such as setting the cursor. /// </term> /// </item> /// <item> /// <term>Implementing drag scrolling.</term> /// </item> /// <item> /// <term>Registering and revoking its application windows as drop targets.</term> /// </item> /// </list> /// <para> /// The <c>IDropTarget</c> interface contains methods that handle all these responsibilities except registering and revoking the /// application window as a drop target, for which you must call the RegisterDragDrop and the RevokeDragDrop functions. /// </para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nn-oleidl-idroptarget [PInvokeData("oleidl.h", MSDNShortId = "13fbe834-1ef8-4944-b2e4-9f5c413c65c8")] [ComImport, Guid("00000122-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDropTarget { /// <summary>Indicates whether a drop can be accepted, and, if so, the effect of the drop.</summary> /// <param name="pDataObj"> /// A pointer to the IDataObject interface on the data object. This data object contains the data being transferred in the /// drag-and-drop operation. If the drop occurs, this data object will be incorporated into the target. /// </param> /// <param name="grfKeyState"> /// The current state of the keyboard modifier keys on the keyboard. Possible values can be a combination of any of the flags /// MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON. /// </param> /// <param name="pt">A POINTL structure containing the current cursor coordinates in screen coordinates.</param> /// <param name="pdwEffect"> /// On input, pointer to the value of the pdwEffect parameter of the DoDragDrop function. On return, must contain one of the /// DROPEFFECT flags, which indicates what the result of the drop operation would be. /// </param> /// <returns> /// <para>This method returns S_OK on success. Other possible values include the following.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>E_UNEXPECTED</term> /// <term>An unexpected error has occurred.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The pdwEffect parameter is NULL on input.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>There was insufficient memory available for this operation.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// You do not call <c>DragEnter</c> directly; instead the DoDragDrop function calls it to determine the effect of a drop the /// first time the user drags the mouse into the registered window of a drop target. /// </para> /// <para> /// To implement <c>DragEnter</c>, you must determine whether the target can use the data in the source data object by checking /// three things: /// </para> /// <list type="bullet"> /// <item> /// <term>The format and medium specified by the data object</term> /// </item> /// <item> /// <term>The input value of pdwEffect</term> /// </item> /// <item> /// <term>The state of the modifier keys</term> /// </item> /// </list> /// <para> /// To check the format and medium, use the IDataObject pointer passed in the pDataObject parameter to call /// IDataObject::EnumFormatEtc so you can enumerate the FORMATETC structures the source data object supports. Then call /// IDataObject::QueryGetData to determine whether the data object can render the data on the target by examining the formats and /// medium specified for the data object. /// </para> /// <para> /// On entry to <c>IDropTarget::DragEnter</c>, the pdwEffect parameter is set to the effects given to the pdwOkEffect parameter /// of the DoDragDrop function. The <c>IDropTarget::DragEnter</c> method must choose one of these effects or disable the drop. /// </para> /// <para>The following modifier keys affect the result of the drop.</para> /// <list type="table"> /// <listheader> /// <term>Key Combination</term> /// <term>User-Visible Feedback</term> /// <term>Drop Effect</term> /// </listheader> /// <item> /// <term>CTRL + SHIFT</term> /// <term>=</term> /// <term>DROPEFFECT_LINK</term> /// </item> /// <item> /// <term>CTRL</term> /// <term>+</term> /// <term>DROPEFFECT_COPY</term> /// </item> /// <item> /// <term>No keys or SHIFT</term> /// <term>None</term> /// <term>DROPEFFECT_MOVE</term> /// </item> /// </list> /// <para> /// On return, the method must write the effect, one of the DROPEFFECT flags, to the pdwEffect parameter. DoDragDrop then takes /// this parameter and writes it to its pdwEffect parameter. You communicate the effect of the drop back to the source through /// <c>DoDragDrop</c> in the pdwEffect parameter. The <c>DoDragDrop</c> function then calls IDropSource::GiveFeedback so that the /// source application can display the appropriate visual feedback to the user through the target window. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nf-oleidl-idroptarget-dragenter HRESULT DragEnter( IDataObject // *pDataObj, DWORD grfKeyState, POINTL pt, DWORD *pdwEffect ); [PreserveSig] HRESULT DragEnter([In] IDataObject pDataObj, [In] uint grfKeyState, [In] Point pt, [In, Out] ref DROPEFFECT pdwEffect); /// <summary> /// Provides target feedback to the user and communicates the drop's effect to the DoDragDrop function so it can communicate the /// effect of the drop back to the source. /// </summary> /// <param name="grfKeyState"> /// The current state of the keyboard modifier keys on the keyboard. Valid values can be a combination of any of the flags /// MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON. /// </param> /// <param name="pt">A POINTL structure containing the current cursor coordinates in screen coordinates.</param> /// <param name="pdwEffect"> /// On input, pointer to the value of the pdwEffect parameter of the DoDragDrop function. On return, must contain one of the /// DROPEFFECT flags, which indicates what the result of the drop operation would be. /// </param> /// <returns> /// <para>This method returns S_OK on success. Other possible values include the following.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>E_UNEXPECTED</term> /// <term>An unexpected error has occurred.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The pdwEffect value is not valid.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>There was insufficient memory available for this operation.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// You do not call <c>DragOver</c> directly. The DoDragDrop function calls this method each time the user moves the mouse across /// a given target window. <c>DoDragDrop</c> exits the loop if the drag-and-drop operation is canceled, if the user drags the /// mouse out of the target window, or if the drop is completed. /// </para> /// <para> /// In implementing <c>IDropTarget::DragOver</c>, you must provide features similar to those in IDropTarget::DragEnter. You must /// determine the effect of dropping the data on the target by examining the FORMATETC defining the data object's formats and /// medium, along with the state of the modifier keys. The mouse position may also play a role in determining the effect of a /// drop. The following modifier keys affect the result of the drop. /// </para> /// <list type="table"> /// <listheader> /// <term>Key Combination</term> /// <term>User-Visible Feedback</term> /// <term>Drop Effect</term> /// </listheader> /// <item> /// <term>CTRL + SHIFT</term> /// <term>=</term> /// <term>DROPEFFECT_LINK</term> /// </item> /// <item> /// <term>CTRL</term> /// <term>+</term> /// <term>DROPEFFECT_COPY</term> /// </item> /// <item> /// <term>No keys or SHIFT</term> /// <term>None</term> /// <term>DROPEFFECT_MOVE</term> /// </item> /// </list> /// <para> /// You communicate the effect of the drop back to the source through DoDragDrop in pdwEffect. The <c>DoDragDrop</c> function /// then calls IDropSource::GiveFeedback so the source application can display the appropriate visual feedback to the user. /// </para> /// <para> /// On entry to <c>IDropTarget::DragOver</c>, the pdwEffect parameter must be set to the allowed effects passed to the /// pdwOkEffect parameter of the DoDragDrop function. The <c>IDropTarget::DragOver</c> method must be able to choose one of these /// effects or disable the drop. /// </para> /// <para> /// Upon return, pdwEffect is set to one of the DROPEFFECT flags. This value is then passed to the pdwEffect parameter of /// DoDragDrop. Reasonable values are DROPEFFECT_COPY to copy the dragged data to the target, DROPEFFECT_LINK to create a link to /// the source data, or DROPEFFECT_MOVE to allow the dragged data to be permanently moved from the source application to the target. /// </para> /// <para> /// You may also wish to provide appropriate visual feedback in the target window. There may be some target feedback already /// displayed from a previous call to <c>IDropTarget::DragOver</c> or from the initial IDropTarget::DragEnter. If this feedback /// is no longer appropriate, you should remove it. /// </para> /// <para> /// For efficiency reasons, a data object is not passed in <c>IDropTarget::DragOver</c>. The data object passed in the most /// recent call to IDropTarget::DragEnter is available and can be used. /// </para> /// <para> /// When <c>IDropTarget::DragOver</c> has completed its operation, the DoDragDrop function calls IDropSource::GiveFeedback so the /// source application can display the appropriate visual feedback to the user. /// </para> /// <para>Notes to Implementers</para> /// <para> /// This function is called frequently during the DoDragDrop loop so it makes sense to optimize your implementation of the /// <c>DragOver</c> method as much as possible. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nf-oleidl-idroptarget-dragover HRESULT DragOver( DWORD // grfKeyState, POINTL pt, DWORD *pdwEffect ); [PreserveSig] HRESULT DragOver([In] uint grfKeyState, [In] Point pt, [In, Out] ref DROPEFFECT pdwEffect); /// <summary>Removes target feedback and releases the data object.</summary> /// <returns> /// <para>This method returns S_OK on success. Other possible values include the following.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>There is insufficient memory available for this operation.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para>You do not call this method directly. The DoDragDrop function calls this method in either of the following cases:</para> /// <list type="bullet"> /// <item> /// <term>When the user drags the cursor out of a given target window.</term> /// </item> /// <item> /// <term>When the user cancels the current drag-and-drop operation.</term> /// </item> /// </list> /// <para> /// To implement <c>IDropTarget::DragLeave</c>, you must remove any target feedback that is currently displayed. You must also /// release any references you hold to the data transfer object. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nf-oleidl-idroptarget-dragleave HRESULT DragLeave( ); [PreserveSig] HRESULT DragLeave(); /// <summary>Incorporates the source data into the target window, removes target feedback, and releases the data object.</summary> /// <param name="pDataObj"> /// A pointer to the IDataObject interface on the data object being transferred in the drag-and-drop operation. /// </param> /// <param name="grfKeyState"> /// The current state of the keyboard modifier keys on the keyboard. Possible values can be a combination of any of the flags /// MK_CONTROL, MK_SHIFT, MK_ALT, MK_BUTTON, MK_LBUTTON, MK_MBUTTON, and MK_RBUTTON. /// </param> /// <param name="pt">A POINTL structure containing the current cursor coordinates in screen coordinates.</param> /// <param name="pdwEffect"> /// On input, pointer to the value of the pdwEffect parameter of the DoDragDrop function. On return, must contain one of the /// DROPEFFECT flags, which indicates what the result of the drop operation would be. /// </param> /// <returns> /// <para>This method returns S_OK on success. Other possible values include the following.</para> /// <list type="table"> /// <listheader> /// <term>Return code</term> /// <term>Description</term> /// </listheader> /// <item> /// <term>E_UNEXPECTED</term> /// <term>An unexpected error has occurred.</term> /// </item> /// <item> /// <term>E_INVALIDARG</term> /// <term>The pdwEffect parameter is not valid.</term> /// </item> /// <item> /// <term>E_OUTOFMEMORY</term> /// <term>There is insufficient memory available for this operation.</term> /// </item> /// </list> /// </returns> /// <remarks> /// <para> /// You do not call this method directly. The DoDragDrop function calls this method when the user completes the drag-and-drop operation. /// </para> /// <para> /// In implementing <c>Drop</c>, you must incorporate the data object into the target. Use the formats available in IDataObject, /// available through pDataObj, along with the current state of the modifier keys to determine how the data is to be /// incorporated, such as linking or embedding. /// </para> /// <para>In addition to incorporating the data, you must also clean up as you do in the IDropTarget::DragLeave method:</para> /// <list type="bullet"> /// <item> /// <term>Remove any target feedback that is currently displayed.</term> /// </item> /// <item> /// <term>Release any references to the data object.</term> /// </item> /// </list> /// <para> /// You also pass the effect of this operation back to the source application through DoDragDrop, so the source application can /// clean up after the drag-and-drop operation is complete: /// </para> /// <list type="bullet"> /// <item> /// <term>Remove any source feedback that is being displayed.</term> /// </item> /// <item> /// <term>Make any necessary changes to the data, such as removing the data if the operation was a move.</term> /// </item> /// </list> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nf-oleidl-idroptarget-drop HRESULT Drop( IDataObject *pDataObj, // DWORD grfKeyState, POINTL pt, DWORD *pdwEffect ); [PreserveSig] HRESULT Drop([In] IDataObject pDataObj, [In] uint grfKeyState, [In] Point pt, [In, Out] ref DROPEFFECT pdwEffect); } /// <summary> /// The IOleWindow interface provides methods that allow an application to obtain the handle to the various windows that participate /// in in-place activation, and also to enter and exit context-sensitive help mode. /// </summary> [PInvokeData("Oleidl.h")] [ComImport, Guid("00000114-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IOleWindow { /// <summary> /// Retrieves a handle to one of the windows participating in in-place activation (frame, document, parent, or in-place object window). /// </summary> /// <returns>A pointer to a variable that receives the window handle.</returns> HWND GetWindow(); /// <summary>Determines whether context-sensitive help mode should be entered during an in-place activation session.</summary> /// <param name="fEnterMode"><c>true</c> if help mode should be entered; <c>false</c> if it should be exited.</param> void ContextSensitiveHelp([MarshalAs(UnmanagedType.Bool)] bool fEnterMode); } /// <summary> /// <para> /// Provides the CLSID of an object that can be stored persistently in the system. Allows the object to specify which object handler /// to use in the client process, as it is used in the default implementation of marshaling. /// </para> /// <para> /// <c>IPersist</c> is the base interface for three other interfaces: IPersistStorage, IPersistStream, and IPersistFile. Each of /// these interfaces, therefore, includes the GetClassID method, and the appropriate one of these three interfaces is implemented on /// objects that can be serialized to a storage, a stream, or a file. The methods of these interfaces allow the state of these /// objects to be saved for later instantiations, and load the object using the saved state. Typically, the persistence interfaces /// are implemented by an embedded or linked object, and are called by the container application or the default object handler. /// </para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nn-objidl-ipersist [PInvokeData("objidl.h", MSDNShortId = "932eb0e2-35a6-482e-9138-00cff30508a9")] [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("0000010c-0000-0000-C000-000000000046")] public interface IPersist { /// <summary>Retrieves the class identifier (CLSID) of the object.</summary> /// <returns> /// <para> /// A pointer to the location that receives the CLSID on return. The CLSID is a globally unique identifier (GUID) that uniquely /// represents an object class that defines the code that can manipulate the object's data. /// </para> /// <para>If the method succeeds, the return value is S_OK. Otherwise, it is E_FAIL.</para> /// </returns> /// <remarks> /// <para> /// The <c>GetClassID</c> method retrieves the class identifier (CLSID) for an object, used in later operations to load /// object-specific code into the caller's context. /// </para> /// <para>Notes to Callers</para> /// <para> /// A container application might call this method to retrieve the original CLSID of an object that it is treating as a different /// class. Such a call would be necessary if a user performed an editing operation that required the object to be saved. If the /// container were to save it using the treat-as CLSID, the original application would no longer be able to edit the object. /// Typically, in this case, the container calls the OleSave helper function, which performs all the necessary steps. For this /// reason, most container applications have no need to call this method directly. /// </para> /// <para> /// The exception would be a container that provides an object handler for certain objects. In particular, a container /// application should not get an object's CLSID and then use it to retrieve class specific information from the registry. /// Instead, the container should use IOleObject and IDataObject interfaces to retrieve such class-specific information directly /// from the object. /// </para> /// <para>Notes to Implementers</para> /// <para> /// Typically, implementations of this method simply supply a constant CLSID for an object. If, however, the object's /// <c>TreatAs</c> registry key has been set by an application that supports emulation (and so is treating the object as one of a /// different class), a call to <c>GetClassID</c> must supply the CLSID specified in the <c>TreatAs</c> key. For more information /// on emulation, see CoTreatAsClass. /// </para> /// <para> /// When an object is in the running state, the default handler calls an implementation of <c>GetClassID</c> that delegates the /// call to the implementation in the object. When the object is not running, the default handler instead calls the ReadClassStg /// function to read the CLSID that is saved in the object's storage. /// </para> /// <para> /// If you are writing a custom object handler for your object, you might want to simply delegate this method to the default /// handler implementation (see OleCreateDefaultHandler). /// </para> /// <para>URL Moniker Notes</para> /// <para>This method returns CLSID_StdURLMoniker.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersist-getclassid HRESULT GetClassID( CLSID *pClassID ); Guid GetClassID(); } /// <summary>Enables the saving and loading of objects that use a simple serial stream for their storage needs.</summary> /// <remarks> /// <para> /// One way in which this interface is used is to support OLE moniker implementations. Each of the OLE-provided moniker interfaces /// provides an <c>IPersistStream</c> implementation through which the moniker saves or loads itself. An instance of the OLE generic /// composite moniker class calls the <c>IPersistStream</c> methods of its component monikers to load or save the components in the /// proper sequence in a single stream. /// </para> /// <para>IPersistStream URL Moniker Implementation</para> /// <para> /// The URL moniker implementation of <c>IPersistStream</c> is found on an URL moniker object, which supports IUnknown, /// <c>IAsyncMoniker</c>, and IMoniker. The <c>IMoniker</c> interface inherits its definition from <c>IPersistStream</c> and thus, /// the URL moniker also provides an implementation of <c>IPersistStream</c> as part of its implementation of <c>IMoniker</c>. /// </para> /// <para> /// The IAsyncMoniker interface on an URL moniker is simply IUnknown (there are no additional methods); it is used to allow clients /// to determine if a moniker supports asynchronous binding. To get a pointer to the IMoniker interface on this object, call the /// <c>CreateURLMonikerEx</c> function. Then, to get a pointer to <c>IPersistStream</c>, call the QueryInterface method. /// </para> /// <para> /// <c>IPersistStream</c>, in addition to inheriting its definition from IUnknown, also inherits the single method of IPersist, GetClassID. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nn-objidl-ipersiststream [PInvokeData("objidl.h", MSDNShortId = "97ea64ee-d950-4872-add6-1f532a6eb33f")] [ComImport, Guid("00000109-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersistStream : IPersist { /// <summary>Retrieves the class identifier (CLSID) of the object.</summary> /// <returns> /// <para> /// A pointer to the location that receives the CLSID on return. The CLSID is a globally unique identifier (GUID) that uniquely /// represents an object class that defines the code that can manipulate the object's data. /// </para> /// <para>If the method succeeds, the return value is S_OK. Otherwise, it is E_FAIL.</para> /// </returns> /// <remarks> /// <para> /// The <c>GetClassID</c> method retrieves the class identifier (CLSID) for an object, used in later operations to load /// object-specific code into the caller's context. /// </para> /// <para>Notes to Callers</para> /// <para> /// A container application might call this method to retrieve the original CLSID of an object that it is treating as a different /// class. Such a call would be necessary if a user performed an editing operation that required the object to be saved. If the /// container were to save it using the treat-as CLSID, the original application would no longer be able to edit the object. /// Typically, in this case, the container calls the OleSave helper function, which performs all the necessary steps. For this /// reason, most container applications have no need to call this method directly. /// </para> /// <para> /// The exception would be a container that provides an object handler for certain objects. In particular, a container /// application should not get an object's CLSID and then use it to retrieve class specific information from the registry. /// Instead, the container should use IOleObject and IDataObject interfaces to retrieve such class-specific information directly /// from the object. /// </para> /// <para>Notes to Implementers</para> /// <para> /// Typically, implementations of this method simply supply a constant CLSID for an object. If, however, the object's /// <c>TreatAs</c> registry key has been set by an application that supports emulation (and so is treating the object as one of a /// different class), a call to <c>GetClassID</c> must supply the CLSID specified in the <c>TreatAs</c> key. For more information /// on emulation, see CoTreatAsClass. /// </para> /// <para> /// When an object is in the running state, the default handler calls an implementation of <c>GetClassID</c> that delegates the /// call to the implementation in the object. When the object is not running, the default handler instead calls the ReadClassStg /// function to read the CLSID that is saved in the object's storage. /// </para> /// <para> /// If you are writing a custom object handler for your object, you might want to simply delegate this method to the default /// handler implementation (see OleCreateDefaultHandler). /// </para> /// <para>URL Moniker Notes</para> /// <para>This method returns CLSID_StdURLMoniker.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersist-getclassid HRESULT GetClassID( CLSID *pClassID ); new Guid GetClassID(); /// <summary>Determines whether an object has changed since it was last saved to its stream.</summary> /// <returns>This method returns S_OK to indicate that the object has changed. Otherwise, it returns S_FALSE.</returns> /// <remarks> /// <para> /// Use this method to determine whether an object should be saved before closing it. The dirty flag for an object is /// conditionally cleared in the IPersistStream::Save method. /// </para> /// <para>Notes to Callers</para> /// <para> /// You should treat any error return codes as an indication that the object has changed. Unless this method explicitly returns /// S_FALSE, assume that the object must be saved. /// </para> /// <para> /// Note that the OLE-provided implementations of the <c>IPersistStream::IsDirty</c> method in the OLE-provided moniker /// interfaces always return S_FALSE because their internal state never changes. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersiststream-isdirty HRESULT IsDirty( ); [PreserveSig] HRESULT IsDirty(); /// <summary>Initializes an object from the stream where it was saved previously.</summary> /// <param name="pstm">The PSTM.</param> /// <remarks> /// <para> /// This method loads an object from its associated stream. The seek pointer is set as it was in the most recent /// IPersistStream::Save method. This method can seek and read from the stream, but cannot write to it. /// </para> /// <para>Notes to Callers</para> /// <para> /// Rather than calling <c>IPersistStream::Load</c> directly, you typically call the OleLoadFromStream function does the following: /// </para> /// <list type="number"> /// <item> /// <term>Calls the ReadClassStm function to get the class identifier from the stream.</term> /// </item> /// <item> /// <term>Calls the CoCreateInstance function to create an instance of the object.</term> /// </item> /// <item> /// <term>Queries the instance for IPersistStream.</term> /// </item> /// <item> /// <term>Calls <c>IPersistStream::Load</c>.</term> /// </item> /// </list> /// <para> /// The OleLoadFromStream function assumes that objects are stored in the stream with a class identifier followed by the object /// data. This storage pattern is used by the generic, composite-moniker implementation provided by OLE. /// </para> /// <para>If the objects are not stored using this pattern, you must call the methods separately yourself.</para> /// <para>URL Moniker Notes</para> /// <para> /// Initializes an URL moniker from data within a stream, usually stored there previously using its IPersistStream::Save (using /// OleSaveToStream). The binary format of the URL moniker is its URL string in Unicode (may be a full or partial URL string, see /// CreateURLMonikerEx for details). This is represented as a <c>ULONG</c> count of characters followed by that many Unicode characters. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersiststream-load HRESULT Load( IStream *pStm ); void Load([In, MarshalAs(UnmanagedType.Interface)] IStream pstm); /// <summary>Saves an object to the specified stream.</summary> /// <param name="pstm">The PSTM.</param> /// <param name="fClearDirty"> /// Indicates whether to clear the dirty flag after the save is complete. If <c>TRUE</c>, the flag should be cleared. If /// <c>FALSE</c>, the flag should be left unchanged. /// </param> /// <remarks> /// <para> /// <c>IPersistStream::Save</c> saves an object into the specified stream and indicates whether the object should reset its dirty flag. /// </para> /// <para> /// The seek pointer is positioned at the location in the stream at which the object should begin writing its data. The object /// calls the ISequentialStream::Write method to write its data. /// </para> /// <para> /// On exit, the seek pointer must be positioned immediately past the object data. The position of the seek pointer is undefined /// if an error returns. /// </para> /// <para>Notes to Callers</para> /// <para> /// Rather than calling <c>IPersistStream::Save</c> directly, you typically call the OleSaveToStream helper function which does /// the following: /// </para> /// <list type="number"> /// <item> /// <term>Calls GetClassID to get the object's CLSID.</term> /// </item> /// <item> /// <term>Calls the WriteClassStm function to write the object's CLSID to the stream.</term> /// </item> /// <item> /// <term>Calls <c>IPersistStream::Save</c>.</term> /// </item> /// </list> /// <para>If you call these methods directly, you can write other data into the stream after the CLSID before calling <c>IPersistStream::Save</c>.</para> /// <para>The OLE-provided implementation of IPersistStream follows this same pattern.</para> /// <para>Notes to Implementers</para> /// <para> /// The <c>IPersistStream::Save</c> method does not write the CLSID to the stream. The caller is responsible for writing the CLSID. /// </para> /// <para> /// The <c>IPersistStream::Save</c> method can read from, write to, and seek in the stream; but it must not seek to a location in /// the stream before that of the seek pointer on entry. /// </para> /// <para>URL Moniker Notes</para> /// <para> /// Saves an URL moniker to a stream. The binary format of URL moniker is its URL string in Unicode (may be a full or partial URL /// string, see CreateURLMonikerEx for details). This is represented as a <c>ULONG</c> count of characters followed by that many /// Unicode characters. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersiststream-save HRESULT Save( IStream *pStm, BOOL // fClearDirty ); void Save([In, MarshalAs(UnmanagedType.Interface)] IStream pstm, [In, MarshalAs(UnmanagedType.Bool)] bool fClearDirty); /// <summary>Retrieves the size of the stream needed to save the object.</summary> /// <returns>The size in bytes of the stream needed to save this object, in bytes.</returns> /// <remarks> /// <para> /// This method returns the size needed to save an object. You can call this method to determine the size and set the necessary /// buffers before calling the IPersistStream::Save method. /// </para> /// <para>Notes to Implementers</para> /// <para> /// The <c>GetSizeMax</c> implementation should return a conservative estimate of the necessary size because the caller might /// call the IPersistStream::Save method with a non-growable stream. /// </para> /// <para>URL Moniker Notes</para> /// <para> /// This method retrieves the maximum number of bytes in the stream that will be required by a subsequent call to /// IPersistStream::Save. This value is sizeof(ULONG)==4 plus sizeof(WCHAR)*n where n is the length of the full or partial URL /// string, including the NULL terminator. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersiststream-getsizemax HRESULT GetSizeMax( // ULARGE_INTEGER *pcbSize ); ulong GetSizeMax(); } /// <summary> /// <para>A replacement for IPersistStream that adds an initialization method.</para> /// <para> /// This interface is not derived from IPersistStream; it is mutually exclusive with <c>IPersistStream</c>. An object chooses to /// support only one of the two interfaces, based on whether it requires the InitNew method. /// </para> /// </summary> // https://docs.microsoft.com/en-us/windows/desktop/api/ocidl/nn-ocidl-ipersiststreaminit [PInvokeData("ocidl.h", MSDNShortId = "49c413b3-3523-4602-9ec1-19f4e0fe5651")] [ComImport, Guid("7FD52380-4E07-101B-AE2D-08002B2EC713"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersistStreamInit : IPersist { /// <summary>Retrieves the class identifier (CLSID) of the object.</summary> /// <returns> /// <para> /// A pointer to the location that receives the CLSID on return. The CLSID is a globally unique identifier (GUID) that uniquely /// represents an object class that defines the code that can manipulate the object's data. /// </para> /// <para>If the method succeeds, the return value is S_OK. Otherwise, it is E_FAIL.</para> /// </returns> /// <remarks> /// <para> /// The <c>GetClassID</c> method retrieves the class identifier (CLSID) for an object, used in later operations to load /// object-specific code into the caller's context. /// </para> /// <para>Notes to Callers</para> /// <para> /// A container application might call this method to retrieve the original CLSID of an object that it is treating as a different /// class. Such a call would be necessary if a user performed an editing operation that required the object to be saved. If the /// container were to save it using the treat-as CLSID, the original application would no longer be able to edit the object. /// Typically, in this case, the container calls the OleSave helper function, which performs all the necessary steps. For this /// reason, most container applications have no need to call this method directly. /// </para> /// <para> /// The exception would be a container that provides an object handler for certain objects. In particular, a container /// application should not get an object's CLSID and then use it to retrieve class specific information from the registry. /// Instead, the container should use IOleObject and IDataObject interfaces to retrieve such class-specific information directly /// from the object. /// </para> /// <para>Notes to Implementers</para> /// <para> /// Typically, implementations of this method simply supply a constant CLSID for an object. If, however, the object's /// <c>TreatAs</c> registry key has been set by an application that supports emulation (and so is treating the object as one of a /// different class), a call to <c>GetClassID</c> must supply the CLSID specified in the <c>TreatAs</c> key. For more information /// on emulation, see CoTreatAsClass. /// </para> /// <para> /// When an object is in the running state, the default handler calls an implementation of <c>GetClassID</c> that delegates the /// call to the implementation in the object. When the object is not running, the default handler instead calls the ReadClassStg /// function to read the CLSID that is saved in the object's storage. /// </para> /// <para> /// If you are writing a custom object handler for your object, you might want to simply delegate this method to the default /// handler implementation (see OleCreateDefaultHandler). /// </para> /// <para>URL Moniker Notes</para> /// <para>This method returns CLSID_StdURLMoniker.</para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/objidl/nf-objidl-ipersist-getclassid HRESULT GetClassID( CLSID *pClassID ); new Guid GetClassID(); /// <summary> /// <para>Determines whether an object has changed since it was last saved to its stream.</para> /// </summary> /// <returns> /// <para>This method returns S_OK to indicate that the object has changed. Otherwise, it returns S_FALSE.</para> /// </returns> /// <remarks> /// <para> /// Use this method to determine whether an object should be saved before closing it. The dirty flag for an object is /// conditionally cleared in the IPersistStreamInit::Save method. /// </para> /// <para>Notes to Callers</para> /// <para> /// You should treat any error return codes as an indication that the object has changed. Unless this method explicitly returns /// S_FALSE, assume that the object must be saved. /// </para> /// <para> /// Note that the OLE-provided implementations of the <c>IPersistStreamInit::IsDirty</c> method in the OLE-provided moniker /// interfaces always return S_FALSE because their internal state never changes. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/ocidl/nf-ocidl-ipersiststreaminit-isdirty HRESULT IsDirty( ); [PreserveSig] HRESULT IsDirty(); /// <summary>Initializes an object from the stream where it was saved previously.</summary> /// <param name="pstm">The PSTM.</param> /// <remarks> /// <para> /// This method loads an object from its associated stream. The seek pointer is set as it was in the most recent /// IPersistStreamInit::Save method. This method can seek and read from the stream, but cannot write to it. /// </para> /// <para>Notes to Callers</para> /// <para> /// Rather than calling <c>IPersistStreamInit::Load</c> directly, you typically call the OleLoadFromStream function does the following: /// </para> /// <list type="number"> /// <item> /// <term>Calls the ReadClassStm function to get the class identifier from the stream.</term> /// </item> /// <item> /// <term>Calls the CoCreateInstance function to create an instance of the object.</term> /// </item> /// <item> /// <term>Queries the instance for IPersistStreamInit.</term> /// </item> /// <item> /// <term>Calls <c>IPersistStreamInit::Load</c>.</term> /// </item> /// </list> /// <para> /// The OleLoadFromStream function assumes that objects are stored in the stream with a class identifier followed by the object /// data. This storage pattern is used by the generic, composite-moniker implementation provided by OLE. /// </para> /// <para>If the objects are not stored using this pattern, you must call the methods separately yourself.</para> /// <para>URL Moniker Notes</para> /// <para> /// Initializes an URL moniker from data within a stream, usually stored there previously using its IPersistStreamInit::Save /// (using OleSaveToStream). The binary format of the URL moniker is its URL string in Unicode (may be a full or partial URL /// string, see CreateURLMonikerEx for details). This is represented as a <c>ULONG</c> count of characters followed by that many /// Unicode characters. /// </para> /// </remarks> // HRESULT Load( LPSTREAM pStm ); https://msdn.microsoft.com/en-us/library/ms864774.aspx void Load([In, MarshalAs(UnmanagedType.Interface)] IStream pstm); /// <summary>Saves an object to the specified stream.</summary> /// <param name="pstm">The PSTM.</param> /// <param name="fClearDirty"> /// Indicates whether to clear the dirty flag after the save is complete. If <c>TRUE</c>, the flag should be cleared. If /// <c>FALSE</c>, the flag should be left unchanged. /// </param> /// <remarks> /// <para> /// <c>IPersistStreamInit::Save</c> saves an object into the specified stream and indicates whether the object should reset its /// dirty flag. /// </para> /// <para> /// The seek pointer is positioned at the location in the stream at which the object should begin writing its data. The object /// calls the ISequentialStream::Write method to write its data. /// </para> /// <para> /// On exit, the seek pointer must be positioned immediately past the object data. The position of the seek pointer is undefined /// if an error returns. /// </para> /// <para>Notes to Implementers</para> /// <para> /// The <c>IPersistStreamInit::Save</c> method does not write the CLSID to the stream. The caller is responsible for writing the CLSID. /// </para> /// <para> /// The <c>IPersistStreamInit::Save</c> method can read from, write to, and seek in the stream; but it must not seek to a /// location in the stream before that of the seek pointer on entry. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/ocidl/nf-ocidl-ipersiststreaminit-save HRESULT Save( LPSTREAM pStm, BOOL // fClearDirty ); void Save([In, MarshalAs(UnmanagedType.Interface)] IStream pstm, [In, MarshalAs(UnmanagedType.Bool)] bool fClearDirty); /// <summary>Retrieves the size of the stream needed to save the object.</summary> /// <returns>The size in bytes of the stream needed to save this object, in bytes.</returns> /// <remarks> /// <para> /// This method returns the size needed to save an object. You can call this method to determine the size and set the necessary /// buffers before calling the IPersistStreamInit::Save method. /// </para> /// <para>Notes to Implementers</para> /// <para> /// The <c>GetSizeMax</c> implementation should return a conservative estimate of the necessary size because the caller might /// call the IPersistStreamInit::Save method with a non-growable stream. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/ocidl/nf-ocidl-ipersiststreaminit-getsizemax HRESULT GetSizeMax( // ULARGE_INTEGER *pCbSize ); ulong GetSizeMax(); /// <summary>Initializes an object to a default state. This method is to be called instead of IPersistStreamInit::Load.</summary> /// <remarks>If the object has already been initialized with IPersistStreamInit::Load, then this method must return E_UNEXPECTED.</remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/ocidl/nf-ocidl-ipersiststreaminit-initnew HRESULT InitNew( ); void InitNew(); } /// <summary> /// Indicates the number of menu items in each of the six menu groups of a menu shared between a container and an object server /// during an in-place editing session. This is the mechanism for building a shared menu. /// </summary> [PInvokeData("Oleidl.h", MSDNShortId = "ms693766")] [StructLayout(LayoutKind.Sequential)] public struct OLEMENUGROUPWIDTHS { /// <summary> /// An array whose elements contain the number of menu items in each of the six menu groups of a shared in-place editing menu. /// Each menu group can have any number of menu items. The container uses elements 0, 2, and 4 to indicate the number of menu /// items in its File, View, and Window menu groups. The object server uses elements 1, 3, and 5 to indicate the number of menu /// items in its Edit, Object, and Help menu groups. /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public uint[] width; } } }
using System; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace BridgeProject { public partial class DB_FoldersManagerForm : Form { public DB_FoldersManagerForm() { InitializeComponent(); LoadFoldersToCombo(m_combo1); LoadFoldersToCombo(m_combo2); } int SELECTOR_FOLDER = -1; // -1 для NULL bool SELECTOR_FOLDER__is_enabled = false; int SELECTOR_FOLDER2 = -1; // -1 для NULL bool SELECTOR_FOLDER2__is_enabled = false; // Выбрана папка: private void m_combo1_SelectedIndexChanged(object sender, EventArgs e) { // Заполнить название в поле "Переименовать" if (m_combo1.SelectedIndex == -1) { SELECTOR_FOLDER__is_enabled = false; m_textbox2.Text = ""; } else { int id = ((comboitem_id_name)m_combo1.Items[m_combo1.SelectedIndex]).GetId(); SELECTOR_FOLDER = id; SELECTOR_FOLDER__is_enabled = true; if (id == -1) { m_textbox2.Text = ""; // т.к. NULL } else { System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT Name FROM Folders WHERE id=" + id; object o = DB.ExecuteScalar(sqlQuery); if (o == null || o == DBNull.Value) m_textbox2.Text = "?"; else m_textbox2.Text = ((string)o).Trim(); } } } // Выбрана папка "to": private void m_combo2_SelectedIndexChanged(object sender, EventArgs e) { if (m_combo2.SelectedIndex == -1) { SELECTOR_FOLDER2__is_enabled = false; } else { int id = ((comboitem_id_name)m_combo2.Items[m_combo2.SelectedIndex]).GetId(); SELECTOR_FOLDER2 = id; SELECTOR_FOLDER2__is_enabled = true; } } // Добавить папку: private void m_btn1_Click(object sender, EventArgs e) { string name = m_textbox1.Text.Trim(); if (name.Length == 0) { MessageBox.Show("Название не введено!"); return; } else { string name__cut = DB.DB_GetCuttedString(name, "Folders", "Name"); System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT id FROM Folders WHERE Name='" + name__cut + "'"; object o = DB.ExecuteScalar(sqlQuery); if (o != null && o != DBNull.Value) { MessageBox.Show("Папка с таким именем уже есть!"); return; } else { sqlQuery.CommandText = "INSERT INTO Folders(Name) VALUES('" + name__cut + "')"; int new_folder_id; while (DB.ExecuteNonQuery(sqlQuery, true, out new_folder_id) == 0) { if (MessageBox.Show("Папка [" + name__cut + "] не была добавлена!", "db error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.Retry) { DB.sqlConnection.Close(); DB.sqlConnection.Open(); } else { return; } } // ОБНОВИТЬ КОМБЫ LoadFoldersToCombo(m_combo1); LoadFoldersToCombo(m_combo2); MessageBox.Show("Папка [" + GetFolderName(new_folder_id) + "] добавлена!"); return; } } } // Переименовать папку: private void m_btn3_Click(object sender, EventArgs e) { if(m_combo1.SelectedIndex == -1) { MessageBox.Show("Папка не выбрана!"); return; } string name = m_textbox2.Text.Trim(); int id = ((comboitem_id_name)m_combo1.Items[m_combo1.SelectedIndex]).GetId(); if (name.Length == 0) { MessageBox.Show("Название не введено!"); return; } else if(id == -1) //NULL { MessageBox.Show("Выберите другую папку!"); return; } else { string name__cut = DB.DB_GetCuttedString(name, "Folders", "Name"); System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT id FROM Folders WHERE Name='" + name__cut + "'"; object o = DB.ExecuteScalar(sqlQuery); if (o != null && o != DBNull.Value) { MessageBox.Show("Папка с таким именем уже есть!"); return; } else { sqlQuery.CommandText = "UPDATE Folders SET Name='" + name__cut + "' WHERE id=" + id; while (DB.ExecuteNonQuery(sqlQuery, true) == 0) { if (MessageBox.Show("Папка не была переименована!", "db error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) == DialogResult.Retry) { DB.sqlConnection.Close(); DB.sqlConnection.Open(); } else { return; } } // ОБНОВИТЬ КОМБЫ LoadFoldersToCombo(m_combo1); LoadFoldersToCombo(m_combo2); MessageBox.Show("Папка переименована в [" + GetFolderName(id) + "]!"); return; } } } // Переместить игры в другую папку: private void m_btn2_Click(object sender, EventArgs e) { if (m_combo1.SelectedIndex == -1) { MessageBox.Show("Начальная папка не выбрана!"); return; } if (m_combo2.SelectedIndex == -1) { MessageBox.Show("Конечная папка не выбрана!"); return; } int id1 = ((comboitem_id_name)m_combo1.Items[m_combo1.SelectedIndex]).GetId(); int id2 = ((comboitem_id_name)m_combo2.Items[m_combo2.SelectedIndex]).GetId(); if (id1 == id2) { MessageBox.Show("Начальная и конечная папки совпадают!"); return; } if (MessageBox.Show("Переместить игры из [" + GetFolderName(id1) + "] в [" + GetFolderName(id2) + "]?", "Уверены?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes) return; System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "UPDATE Games SET fk_Folder_id = " + (id2 == -1 ? "NULL" : id2.ToString()) + " WHERE fk_Folder_id" + (id1 == -1 ? " IS NULL" : "=" + id1); int rows_affected = DB.ExecuteNonQuery(sqlQuery, true); // ОБНОВИТЬ КОМБЫ LoadFoldersToCombo(m_combo1); LoadFoldersToCombo(m_combo2); MessageBox.Show("Перемещено " + rows_affected + " игр из [" + GetFolderName(id1) + "] в [" + GetFolderName(id2) + "]!"); return; } // Очистить: private void m_btn4_Click(object sender, EventArgs e) { if (m_combo1.SelectedIndex == -1) { MessageBox.Show("Папка не выбрана!"); return; } int id = ((comboitem_id_name)m_combo1.Items[m_combo1.SelectedIndex]).GetId(); if (MessageBox.Show("Очистить папку [" + GetFolderName(id) + "]?", "Уверены?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes) return; System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "DELETE FROM Games WHERE fk_Folder_id" + (id == -1 ? " IS NULL" : "=" + id); int rows_affected = DB.ExecuteNonQuery(sqlQuery, true); // ОБНОВИТЬ КОМБЫ LoadFoldersToCombo(m_combo1); LoadFoldersToCombo(m_combo2); MessageBox.Show("Папка [" + GetFolderName(id) + "] очищена!\nБыло удалено " + rows_affected + " игр."); return; } // Удалить: private void m_btn5_Click(object sender, EventArgs e) { if (m_combo1.SelectedIndex == -1) { MessageBox.Show("Папка не выбрана!"); return; } int id = ((comboitem_id_name)m_combo1.Items[m_combo1.SelectedIndex]).GetId(); string name = GetFolderName(id); if (id == -1) { MessageBox.Show("Папку [NULL] нельзя удалить!"); return; } if (MessageBox.Show("Удалить папку [" + name + "]?", "Уверены?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes) return; System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "DELETE FROM Games WHERE fk_Folder_id=" + id; int rows_affected = DB.ExecuteNonQuery(sqlQuery, true); sqlQuery.CommandText = "DELETE FROM Folders WHERE id=" + id; int rows_affected_f = DB.ExecuteNonQuery(sqlQuery, true); if (rows_affected_f == 0) { MessageBox.Show("Папка [" + name + "] не была удалена!\nИз нее удалено " + rows_affected + " игр.", "db error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } else { // ОБНОВИТЬ КОМБЫ LoadFoldersToCombo(m_combo1); LoadFoldersToCombo(m_combo2); MessageBox.Show("Папка [" + name + "] удалена!\nБыло удалено " + rows_affected + " игр."); return; } } // **** контролы **** //m_textbox1 добавить //m_textbox2 переименовать //m_combo1 source //m_combo2 destination //---------------------------------------------------------------------------------------------------- //Загрузка комбы папок void LoadFoldersToCombo(ComboBox combo) { bool is_from = (combo == m_combo1); bool is_to = (combo == m_combo2); // Сохранить SELECTOR_FOLDER... int saved__SELECTOR_FOLDER = SELECTOR_FOLDER; int saved__SELECTOR_FOLDER2 = SELECTOR_FOLDER2; bool saved__SELECTOR_FOLDER__is_enabled = SELECTOR_FOLDER__is_enabled; bool saved__SELECTOR_FOLDER2__is_enabled = SELECTOR_FOLDER2__is_enabled; // Сначала очистить: combo.Items.Clear(); combo.SelectedIndex = -1; // Теперь загрузить: //1. NULL System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT COUNT(id) FROM Games WHERE fk_Folder_id is NULL"; object o = DB.ExecuteScalar(sqlQuery); int fid = -1; string fname = "- нет папки -"; if (o != null && o != DBNull.Value) fname += " (" + (int)o + ")"; int index = combo.Items.Add(new comboitem_id_name(fid, fname)); // Выбрать: if (is_from && saved__SELECTOR_FOLDER__is_enabled && saved__SELECTOR_FOLDER == fid || is_to && saved__SELECTOR_FOLDER2__is_enabled && saved__SELECTOR_FOLDER2 == fid) { combo.SelectedIndex = index; } // 2. остальные sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT f.id as [fid], f.Name as [fname], COUNT(g.id) as [fcount] FROM Folders f LEFT JOIN Games g ON f.id=g.fk_Folder_id GROUP BY f.id, f.Name ORDER BY [fname]"; System.Data.SqlServerCe.SqlCeDataReader sqlReader = DB.ExecuteReader(sqlQuery); while (sqlReader.Read()) { fid = sqlReader.IsDBNull(sqlReader.GetOrdinal("fid")) ? -1 : sqlReader.GetInt32(sqlReader.GetOrdinal("fid")); fname = ""; if (fid == -1) fname = "- нет папки -"; if (!sqlReader.IsDBNull(sqlReader.GetOrdinal("fname"))) fname = sqlReader.GetString(sqlReader.GetOrdinal("fname")); fname += " (" + (sqlReader.IsDBNull(sqlReader.GetOrdinal("fcount")) ? 0 : sqlReader.GetInt32(sqlReader.GetOrdinal("fcount"))) + ")"; index = combo.Items.Add(new comboitem_id_name(fid, fname)); // Выбрать: if (is_from && saved__SELECTOR_FOLDER__is_enabled && saved__SELECTOR_FOLDER == fid || is_to && saved__SELECTOR_FOLDER2__is_enabled && saved__SELECTOR_FOLDER2 == fid) { combo.SelectedIndex = index; } } sqlReader.Close(); } //----------------------------------------- // Имя папки? string GetFolderName(int id) { if (id == -1) { return "NULL"; } else { System.Data.SqlServerCe.SqlCeCommand sqlQuery = DB.CreateQuery(); sqlQuery.CommandText = "SELECT Name FROM Folders WHERE id=" + id; object o = DB.ExecuteScalar(sqlQuery); if (o == null || o == DBNull.Value) return "?"; else return ((string)o).Trim(); } } } }
// ----------------------------------------------------------------------- // <copyright file="EventHandelExtensions.cs" company="AnoriSoft"> // Copyright (c) AnoriSoft. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Anori.Extensions { using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Anori.Common; using JetBrains.Annotations; /// <summary> /// Event Handel Extensions. /// </summary> public static class EventHandelExtensions { /// <summary> /// Raises the specified sender. /// </summary> /// <param name="eventHandler">The event handler.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise(this EventHandler? eventHandler, object sender, EventArgs e) { if (eventHandler == null) { return false; } eventHandler(sender, e); return true; } /// <summary> /// Raises the specified e. /// </summary> /// <param name="eventHandler">The event handler.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> /// <returns> /// Is any raised. /// </returns> public static bool Raise(this EventHandler? eventHandler, EventArgs e) { if (eventHandler == null) { return false; } eventHandler(null, e); return true; } /// <summary> /// Raises the specified e. /// </summary> /// <param name="eventHandler">The event handler.</param> /// <param name="propertyName">Name of the property.</param> /// <returns> /// Is any raised. /// </returns> public static bool Raise( this PropertyChangedEventHandler? eventHandler, [CallerMemberName] string? propertyName = null!) { if (eventHandler == null) { return false; } eventHandler(null, new PropertyChangedEventArgs(propertyName)); return true; } /// <summary> /// Raises the specified sender. /// </summary> /// <param name="eventHandler">The event handler.</param> /// <param name="sender">The sender.</param> /// <param name="propertyName">Name of the property.</param> /// <returns>Is any raised.</returns> public static bool Raise( this PropertyChangedEventHandler? eventHandler, [CanBeNull] INotifyPropertyChanged sender, [CallerMemberName] string? propertyName = null!) { if (eventHandler == null) { return false; } eventHandler(sender, new PropertyChangedEventArgs(propertyName)); return true; } /// <summary> /// Raises the specified action. /// </summary> /// <param name="action">The action.</param> /// <returns>Is any raised.</returns> public static bool Raise(this Action? action) { if (action == null) { return false; } action(); return true; } /// <summary> /// Raises the specified function. /// </summary> /// <typeparam name="T">Resukt Type.</typeparam> /// <param name="func">The function.</param> /// <returns>Function result.</returns> public static T Raise<T>(this Func<T>? func) { if (func == null) { return default!; } return func(); } /// <summary> /// Raises the specified parameter. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="action">The action.</param> /// <param name="parameter">The parameter.</param> /// <returns>Is any is raised.</returns> public static bool Raise<T>(this Action<T>? action, T parameter) { if (action == null) { return false; } action(parameter); return true; } /// <summary> /// Raises the specified parameter1. /// </summary> /// <typeparam name="T1">The type of the 1.</typeparam> /// <typeparam name="T2">The type of the 2.</typeparam> /// <param name="action">The action.</param> /// <param name="parameter1">The parameter1.</param> /// <param name="parameter2">The parameter2.</param> /// <returns>When one has been raised.</returns> public static bool Raise<T1, T2>(this Action<T1, T2>? action, T1 parameter1, T2 parameter2) { if (action != null) { action(parameter1, parameter2); return true; } return false; } /// <summary> /// Raises the specified parameter1. /// </summary> /// <typeparam name="T1">The type of the 1.</typeparam> /// <typeparam name="T2">The type of the 2.</typeparam> /// <typeparam name="T3">The type of the 3.</typeparam> /// <param name="action">The action.</param> /// <param name="parameter1">The parameter1.</param> /// <param name="parameter2">The parameter2.</param> /// <param name="parameter3">The parameter3.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise<T1, T2, T3>( this Action<T1, T2, T3>? action, T1 parameter1, T2 parameter2, T3 parameter3) { if (action == null) { return false; } action(parameter1, parameter2, parameter3); return true; } /// <summary> /// Raises the specified parameter1. /// </summary> /// <typeparam name="T1">The type of the 1.</typeparam> /// <typeparam name="T2">The type of the 2.</typeparam> /// <typeparam name="T3">The type of the 3.</typeparam> /// <typeparam name="T4">The type of the 4.</typeparam> /// <param name="action">The action.</param> /// <param name="parameter1">The parameter1.</param> /// <param name="parameter2">The parameter2.</param> /// <param name="parameter3">The parameter3.</param> /// <param name="parameter4">The parameter4.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise<T1, T2, T3, T4>( this Action<T1, T2, T3, T4>? action, T1 parameter1, T2 parameter2, T3 parameter3, T4 parameter4) { if (action == null) { return false; } action(parameter1, parameter2, parameter3, parameter4); return true; } /// <summary> /// Raises the specified sender. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="eventHandler">The event handler.</param> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise<T>(this EventHandler<T>? eventHandler, object sender, T e) where T : EventArgs { if (eventHandler == null) { return false; } eventHandler(sender, e); return true; } /// <summary> /// Raises the specified e. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="eventHandler">The event handler.</param> /// <param name="e">The e.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise<T>(this EventHandler<T>? eventHandler, T e) where T : EventArgs { if (eventHandler == null) { return false; } eventHandler(null, e); return true; } /// <summary> /// Raises the specified sender. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="eventHandler">The event handler.</param> /// <param name="sender">The sender.</param> /// <param name="value">The value.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise<T>(this EventHandler<EventArgs<T>>? eventHandler, object sender, T value) { if (eventHandler == null) { return false; } eventHandler(sender, new EventArgs<T>(value)); return true; } /// <summary> /// Raises the specified value. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="eventHandler">The event handler.</param> /// <param name="value">The value.</param> /// <returns> /// When one has been raised. /// </returns> public static bool Raise<T>(this EventHandler<EventArgs<T>>? eventHandler, T value) { if (eventHandler == null) { return false; } eventHandler(null, new EventArgs<T>(value)); return true; } /// <summary> /// Raises the asynchronous. /// </summary> /// <param name="func">The function.</param> /// <returns> /// Result of RaiseAsync as Boolean. /// </returns> public static async Task<bool> RaiseAsync(this Func<Task>? func) { if (func == null) { return false; } await func.Invoke(); return true; } /// <summary> /// Raises the asynchronous. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="func">The function.</param> /// <param name="arg">The argument.</param> /// <returns> /// Result of RaiseAsync as Boolean. /// </returns> public static async Task<bool> RaiseAsync<T>(this Func<T, Task>? func, T arg) { if (func == null) { return false; } await func.Invoke(arg); return true; } /// <summary> /// Raises the empty. /// </summary> /// <param name="eventHandler">The event handler.</param> /// <returns> /// When one has been raised. /// </returns> public static bool RaiseEmpty(this EventHandler? eventHandler) => Raise(eventHandler, EventArgs.Empty); /// <summary> /// Raises the empty. /// </summary> /// <param name="eventHandler">The event handler.</param> /// <param name="sender">The sender.</param> /// <returns> /// When one has been raised. /// </returns> public static bool RaiseEmpty(this EventHandler? eventHandler, object sender) => Raise(eventHandler, sender, EventArgs.Empty); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BaseEnemy : MonoBehaviour, BaseCharacter { private string _name; private string _description; private string _characterName; private float _characterHealth; private List<Sprite> _characterImages; private List<BaseCharacterEffect> _attachedCardEffects; private ThingType _thingType; private ThingInfo _thingInfo; public string Name { get { return _name; } set { _name = value; } } public string Description { get { return _description; } set { _description = value; } } public string CharacterName { get { return _characterName; } set { _characterName = value; } } public List<Sprite> CharacterImages { get { return _characterImages; } set { _characterImages = value; } } public ThingType ThingType { get { return _thingType; } set { _thingType = value; } } public float CharacterHealth { get { return _characterHealth; } set { _characterHealth = value; } } public ThingInfo ThingInfo { get { return _thingInfo; } } public List<BaseCharacterEffect> AttachedCardEffects { get { return _attachedCardEffects; } } public EnemyEncounterAI CombatAI; public void InitialiseThing(string name, string desc, string charName, List<Sprite> charImgs, ThingType thingType, ThingInfo info) { Name = name; Description = desc; CharacterName = charName; CharacterImages = charImgs; ThingType = thingType; _thingInfo = info; } public void InitialiseThingForCombat(float health) { _characterHealth = health; CombatAI = gameObject.GetComponent<EnemyEncounterAI>(); CombatAI.InitFSM(); } public void InitialiseThingPersonality(CharacterPersonality type) { //GenDialogueLines = type.GeneralDialogueLines; //CbtDialogueLines = type.CombatDialogueLines; } public void AttachNewCardEffectToEnemy(BaseCharacterEffect effect) { // TODO: check if effect already exists? _attachedCardEffects.Add(effect); } }
using System; using System.Collections.Generic; namespace Algorithms.LeetCode { public class FindLongestPathTask { public int FindLongestPath(bool[][] matrix) { var maxPath = 0; // Error: forgot j++ part // for (int j = 0; j < matrix[0].Length) for (int j = 0; j < matrix[0].Length; ++j) { //Error: () in wrong place // var visited = VisitAllPaths(0, j, matrix, new HashSet<(int, int)>)(); var visited = VisitAllPaths(0, j, matrix, new HashSet<(int, int)>()); maxPath = Math.Max(maxPath, visited.Count); } return maxPath; } public HashSet<(int, int)> VisitAllPaths(int i, int j, bool[][] matrix, HashSet<(int, int)> visited) { var curVisited = new HashSet<(int, int)>(visited); if (!matrix[i][j]) // Error: return value // return; return curVisited; if (visited.Contains((i, j))) { return curVisited; } else { curVisited.Add((i, j)); } // Error: Contains tuple -> forgot () // if (matrix.Length - 1 == i && (curVisited.Contains((i, j - 1)) || j - 1 < 0) && (curVisited.Contains(i, j + 1) || j + 1 == matrix[0].Length)) if (matrix.Length - 1 == i && (curVisited.Contains((i, j - 1)) || j - 1 < 0) && (curVisited.Contains((i, j + 1)) || j + 1 == matrix[0].Length)) return curVisited; // Error: remove () and initialize //HashSet<(int, int)>() temp; HashSet<(int, int)> temp = new HashSet<(int, int)>(); if (j - 1 >= 0) temp = VisitAllPaths(i, j - 1, matrix, curVisited); if (j + 1 < matrix[0].Length) { var t = VisitAllPaths(i, j + 1, matrix, curVisited); if (t.Count > temp.Count) temp = t; } if (i < matrix.Length - 1) { var t = VisitAllPaths(i + 1, j, matrix, curVisited); if (t.Count > temp.Count) temp = t; } return temp; } public static void Test() { var obj = new FindLongestPathTask(); // [..] result: 4 // [..] var data = new bool[2][]{ new bool[]{ true, true}, new bool[]{ true, true} }; obj.FindLongestPath(data); // #.#..# result: 9 // #.#..# // #.##.# // #..#.# // #..#.# // #..#.# data = new bool[6][]{ new bool[]{ false, true, false, true, true, false}, new bool[]{ false, true, false, true, true, false}, new bool[]{ false, true, false, false, true, false}, new bool[]{ false, true, true, false, true, false}, new bool[]{ false, true, true, false, true, false}, new bool[]{ false, true, true, false, true, false}, }; obj.FindLongestPath(data); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace GameProject { public static class SpriteRenderer { public static List<Sprite> Sprites = new List<Sprite>(); public static void DrawSprites(SpriteBatch spriteBatch, GameTime gameTime) { foreach(Sprite s in Sprites) { if (s.IsAlive) s.Draw(spriteBatch, gameTime); } } } }
using RealEstate.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace RealEstate.Controllers { public class PropertyController : Controller { RealEstateEntities db = new RealEstateEntities(); BL bl = new BL(); // GET: Property public ActionResult Index() { return View(); } [CHAA] public ActionResult Create() { return View(); } [CHAA] [HttpPost] public ActionResult Create(PropertyVM mod) { if (ModelState.IsValid) { try { if (mod.SocietyID <= 0) { tblSociety soc = new tblSociety { CityID = mod.CityID, Society = mod.OtherSociety, Status = true }; db.tblSocieties.Add(soc); db.SaveChanges(); mod.SocietyID = soc.SocietyID; } tblProperty tbl = new tblProperty { CityID = mod.CityID, Description = mod.Description, IsFeatured = mod.IsFeatured, LandArea = mod.LandArea, Price = mod.Price, PropertyTitle = mod.PropertyTitle, Purpose = mod.Purpose, SocietyID = mod.SocietyID, Status = "H", TransDate = DateTime.Now.AddHours(12), TypeID = mod.TypeID, UOMID = mod.UOMID, UserID = bl.GetUserID(System.Web.HttpContext.Current), Block = mod.Block, ContactNo = mod.ContactNo, Estate = mod.Estate, IsDealer = mod.IsDealer, Owner = mod.Owner, PlotNo = mod.PlotNo }; db.tblProperties.Add(tbl); db.SaveChanges(); var coun = Request.Files.Count; for (int i = 0; i < coun; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetExtension(file.FileName); tblImage img = new tblImage { PropertyID = tbl.PropertyID, ImagePath = fileName, Status = true }; db.tblImages.Add(img); db.SaveChanges(); var path = Path.Combine(Server.MapPath("~/Images/"), img.ImageID+fileName); file.SaveAs(path); } } return RedirectToAction("Create"); } catch (Exception) { } } return View(mod); } [CHAA] public ActionResult RemoveImage(long ID, long PropertyID) { try { var tbl = db.tblImages.Find(ID); db.tblImages.Remove(tbl); db.SaveChanges(); return RedirectToAction("Edit", new { ID = PropertyID }); } catch (Exception ex) { } return View("Edit"); } [CHAA] public ActionResult Edit(long ID) { var mod = bl.GetPropertyForEdit(ID); return View(mod); } [CHAA] [HttpPost] public ActionResult Edit(PropertyVM mod) { if (ModelState.IsValid) { try { var mo = db.tblProperties.Find(mod.PropertyID); if (mod.SocietyID <= 0) { tblSociety soc = new tblSociety { CityID = mod.CityID, Society = mod.OtherSociety, Status = true }; db.tblSocieties.Add(soc); db.SaveChanges(); mod.SocietyID = soc.SocietyID; } //tblProperty tbl = new tblProperty //{ mo.CityID = mod.CityID; mo.Description = mod.Description; //IsFeatured = mod.IsFeatured; mo.LandArea = mod.LandArea; mo.Price = mod.Price; mo.PropertyTitle = mod.PropertyTitle; mo.Purpose = mod.Purpose; mo.SocietyID = mod.SocietyID; //mo.Status = "H"; //TransDate = DateTime.Now; mo.TypeID = mod.TypeID; mo.UOMID = mod.UOMID; mo.UserID = bl.GetUserID(System.Web.HttpContext.Current); mo.Block = mod.Block; mo.ContactNo = mod.ContactNo; mo.Estate = mod.Estate; mo.IsDealer = mod.IsDealer; mo.Owner = mod.Owner; mo.PlotNo = mod.PlotNo; //}; //db.tblProperties.Add(tbl); db.SaveChanges(); var coun = Request.Files.Count; for (int i = 0; i < coun; i++) { var file = Request.Files[i]; if (file != null && file.ContentLength > 0) { var fileName = Path.GetExtension(file.FileName); tblImage img = new tblImage { PropertyID = mod.PropertyID, ImagePath = fileName, Status = true }; db.tblImages.Add(img); db.SaveChanges(); var path = Path.Combine(Server.MapPath("~/Images/"), img.ImageID + fileName); file.SaveAs(path); //return Json(new { Message = fileName }); } } return RedirectToAction("Properties", new { ID = mod.Purpose }); } catch (Exception) { } } return View(mod); } [CHAA] public ActionResult UploadFile(HttpPostedFileBase uploadFile) { var file = Request.Files[0]; //foreach (var v in file) //{ if (file != null && file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/Images/"), fileName); file.SaveAs(path); return Json(new { Message = fileName }); } //} return Json(new { Message = "" }); //return View(); } public JsonResult CityList() { var lst = bl.CityList(); //db.tblCities.Where(x => x.Status).Select(x => new { CityID = x.CityID,City = x.City}).ToList(); return Json(lst, JsonRequestBehavior.AllowGet); } public JsonResult TypeList() { var lst = bl.TypeList(); //db.tblTypes.Where(x => x.Status).Select(x => new { TypeID = x.TypeID, Type = x.Type }).ToList(); return Json(lst, JsonRequestBehavior.AllowGet); } public JsonResult SocietyList(int CityID) { var lst = bl.SocietyList(CityID); //db.tblSocieties.Where(x => x.Status && x.CityID == CityID).Select(x => new { SocietyID = x.SocietyID, Society = x.Society }).ToList(); lst.Add(new SocietyVM { SocietyID = 0, Society = "Other" }); return Json(lst, JsonRequestBehavior.AllowGet); } public JsonResult UOMList() { var lst = bl.UOMList(); //db.tblUOMs.Where(x => x.Status).Select(x => new { UOMID = x.UOMID, UOM = x.UOM }).ToList(); return Json(lst, JsonRequestBehavior.AllowGet); } public JsonResult TypeLists() { var lst = bl.TypeList(); //db.tblTypes.Where(x => x.Status).Select(x => new { TypeID = x.TypeID, Type = x.Type }).ToList(); lst.Insert(0, new TypeVM { TypeID = 0, Type = "All Types" }); return Json(lst, JsonRequestBehavior.AllowGet); } public JsonResult SocietyLists(int CityID) { var lst = bl.SocietyList(CityID); //db.tblSocieties.Where(x => x.Status && x.CityID == CityID).Select(x => new { SocietyID = x.SocietyID, Society = x.Society }).ToList(); lst.Insert(0, new SocietyVM { SocietyID = 0, Society = "All Societies" }); return Json(lst, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult Search1(FormCollection frm) { SearchPropertyVM mod = new SearchPropertyVM(); mod.Purpose = frm["Purpose1"]; mod.Type = Convert.ToInt32(frm["TypeID1"]); mod.City = Convert.ToInt32(frm["CityID1"]); mod.Society = frm["SocietyID1"] == null ? 0 : Convert.ToInt32(frm["SocietyID1"]); mod.FromArea = String.IsNullOrEmpty(frm["FromArea1"]) ? 0 : Convert.ToInt32(frm["FromArea1"]); mod.ToArea = String.IsNullOrEmpty(frm["ToArea1"]) ? 0 : Convert.ToInt32(frm["ToArea1"]); mod.UOM = Convert.ToInt32(frm["UOMID1"]); mod.FromPrice = String.IsNullOrEmpty(frm["FromPrice1"]) ? 0 : Convert.ToInt64(frm["FromPrice1"]); mod.ToPrice = String.IsNullOrEmpty(frm["ToPrice1"]) ? 0 : Convert.ToInt32(frm["ToPrice1"]); mod.OrderID = 1; mod.PageNo = 1; int page = mod.PageNo; mod.PageNo = (mod.PageNo - 1) * 8; var lst = bl.SearchPropertyList(mod, bl.GetUserID(System.Web.HttpContext.Current)); mod.TotalPage = (lst.Count() / 8) + 1; switch (mod.OrderID) { case 1: lst = lst.OrderByDescending(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 2: lst = lst.OrderBy(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 3: lst = lst.OrderByDescending(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; case 4: lst = lst.OrderBy(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; } mod.PageNo = page; ViewBag.PropertyList = lst; //ViewBag.Para = mod; return View("SearchResult", mod); //return RedirectToAction("SearchResult", mod); //return View(); } public ActionResult Search2(FormCollection frm) { SearchPropertyVM mod = new SearchPropertyVM(); mod.Purpose = frm["Purpose2"]; mod.Type = Convert.ToInt32(frm["TypeID2"]); mod.City = Convert.ToInt32(frm["CityID2"]); mod.Society = frm["SocietyID2"] == null ? 0 : Convert.ToInt32(frm["SocietyID2"]); mod.FromArea = String.IsNullOrEmpty(frm["FromArea2"]) ? 0 : Convert.ToInt32(frm["FromArea2"]); mod.ToArea = String.IsNullOrEmpty(frm["ToArea2"]) ? 0 : Convert.ToInt32(frm["ToArea2"]); mod.UOM = Convert.ToInt32(frm["UOMID2"]); mod.FromPrice = String.IsNullOrEmpty(frm["FromPrice2"]) ? 0 : Convert.ToInt64(frm["FromPrice2"]); mod.ToPrice = String.IsNullOrEmpty(frm["ToPrice2"]) ? 0 : Convert.ToInt32(frm["ToPrice2"]); mod.OrderID = 1; mod.PageNo = 1; int page = mod.PageNo; mod.PageNo = (mod.PageNo - 1) * 8; var lst = bl.SearchPropertyList(mod, bl.GetUserID(System.Web.HttpContext.Current)); mod.TotalPage = (lst.Count() / 8) + 1; switch (mod.OrderID) { case 1: lst = lst.OrderByDescending(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 2: lst = lst.OrderBy(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 3: lst = lst.OrderByDescending(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; case 4: lst = lst.OrderBy(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; } mod.PageNo = page; ViewBag.PropertyList = lst; //ViewBag.Para = mod; return View("SearchResult", mod); //return RedirectToAction("SearchResult", mod); //return View(); } [HttpPost] public ActionResult SearchResult([Bind(Include = "Purpose,Type,City,Society,FromArea,ToArea,UOM,FromPrice,ToPrice,OrderID,PageNo,TotalPage")] SearchPropertyVM mod) { int page = mod.PageNo; mod.PageNo = (mod.PageNo - 1) * 8; var lst = bl.SearchPropertyList(mod,bl.GetUserID(System.Web.HttpContext.Current)); mod.TotalPage = (lst.Count() / 8) + 1; switch (mod.OrderID) { case 1: lst = lst.OrderByDescending(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 2: lst = lst.OrderBy(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 3: lst = lst.OrderByDescending(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; case 4: lst = lst.OrderBy(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; } mod.PageNo = page; ViewBag.PropertyList = lst; //ViewBag.Para = mod; return View(mod); } public ActionResult Properties(string ID) { SearchPropertyVM mod = new SearchPropertyVM(); mod.Purpose = ID; mod.Type = 0; mod.City = 1; mod.Society = 0; mod.FromArea = 0; mod.ToArea = 0; mod.UOM = 1; mod.FromPrice = 0; mod.ToPrice = 0; mod.OrderID = 1; mod.PageNo = 1; int page = mod.PageNo; mod.PageNo = (mod.PageNo - 1) * 8; var lst = bl.SearchPropertyList(mod, bl.GetUserID(System.Web.HttpContext.Current)); mod.TotalPage = (lst.Count() / 8) + 1; switch (mod.OrderID) { case 1: lst = lst.OrderByDescending(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 2: lst = lst.OrderBy(x => x.TransDate).Skip(mod.PageNo).Take(8).ToList(); break; case 3: lst = lst.OrderByDescending(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; case 4: lst = lst.OrderBy(x => x.Price).Skip(mod.PageNo).Take(8).ToList(); break; } mod.PageNo = page; ViewBag.PropertyList = lst; //ViewBag.Para = mod; return View("SearchResult", mod); } public ActionResult PropertyDetail(long ID) { var mod = bl.GetPropertyByID(ID); return View(mod); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Audio; using TMPro; [RequireComponent(typeof(AudioSource))] public class CarSoundHandler : MonoBehaviour { [Tooltip("The name/id of the sound from SoundAssets that the engine of this car should make.")] public string soundName; [Range(-3.0f, 3.0f)] public float minPitch; [Range(-3.0f, 3.0f)] public float maxPitch; [Tooltip("Once the car starts falling, how many seconds does it take before the engine sound pitch starts to slowly drop?")] public float fallTimerDuration = 0.7f; private AudioSource output; private Sound sound; private float velocity = 0f; private bool grounded = false; // private float pitchChangeSpeed = 5f; private float pitchDifference; private float effectivePitch = 1f; private float fallTimer = 0; private bool fallTiming = false; private bool fallPitchDrop = false; void Awake() { output = GetComponent<AudioSource>(); foreach (Sound item in SoundAssets.Instance.soundEffects) { if (item.name == soundName) { sound = item; break; } } output.clip = sound.audioClip; output.outputAudioMixerGroup = sound.audioMixer; output.loop = true; output.volume = sound.volume; pitchDifference = maxPitch - minPitch; } void OnEnable() { output.Play(); } void OnDisable() { output.Stop(); } public void RecieveVelocityData(float p_velocity) { if (grounded) velocity = p_velocity; } public void RecieveGroundedData(bool p_grounded) { bool prevGrounded = grounded; grounded = p_grounded; if (prevGrounded == true && grounded == false) { if (fallTiming == false) StartFallTimer(); } else if (prevGrounded == false && grounded == true) { if (fallTiming) { fallTimer = 0f; fallTiming = false; } } } private void Update() { if (velocity >= 0) { if (fallTiming) { fallTimer -= Time.deltaTime; if (fallTimer <= 0f) { fallTimer = 0f; fallTiming = false; fallPitchDrop = true; } } else if (fallPitchDrop) { if (!grounded) { velocity = Mathf.Clamp(velocity - (0.3f * Time.deltaTime), 0f, 1f); effectivePitch = minPitch + (pitchDifference * velocity); output.pitch = effectivePitch; } else fallPitchDrop = false; } else { effectivePitch = Mathf.Clamp(minPitch + (pitchDifference * velocity), minPitch, maxPitch); output.pitch = effectivePitch; } } } private void StartFallTimer() { fallTimer = fallTimerDuration; fallTiming = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shooting : MonoBehaviour { [SerializeField] private Movement_Camera _Camera; [SerializeField] private GameObject _PlayerObject; [SerializeField] private Transform _ShootPos; [SerializeField] private ObjectPool _ObjectPool; [SerializeField] private float _ShootSpeed; [SerializeField] private float _Accuracty; private float _Timer; void Update() { if (Input.GetMouseButton(0)) { _Timer += 1 * Time.deltaTime; } if(_Timer > _ShootSpeed) { Spawn(); _Camera.Effect_ScreenShake(0.1f, 0.1f); _Timer = 0; } } private void Spawn() { AudioHandler.AUDIO.PlayTrack("GunShot"); GameObject bulletobj = _ObjectPool.GetObject("Bullet1"); bulletobj.transform.position = _ShootPos.position; bulletobj.transform.rotation = Quaternion.Euler(_PlayerObject.transform.rotation.eulerAngles.x, _PlayerObject.transform.rotation.eulerAngles.y + Random.Range(-_Accuracty, _Accuracty), _PlayerObject.transform.rotation.eulerAngles.z); bulletobj.SetActive(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Kingdee.BOS.Core.DynamicForm.PlugIn.Args { public static class BeginSetStatusTransactionArgsExtension { public static BeginSetStatusTransactionArgs AsBeginSetStatusTransactionArgs(this BeginOperationTransactionArgs args) { return args.AsType<BeginSetStatusTransactionArgs>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using AcessoBancoDados; using DTO; namespace Negocios { public class TCCNegocios { AcessoDadosSqlServer acessoDadosSqlServer = new AcessoDadosSqlServer(); public string Inserir(TCC tcc) { try { acessoDadosSqlServer.LimparParametros(); acessoDadosSqlServer.AdicionarParametros("@TCCTitulo", tcc.TCCTitulo); acessoDadosSqlServer.AdicionarParametros("@TCCGrandeArea", tcc.TCCGrandeArea); acessoDadosSqlServer.AdicionarParametros("@TCCArea", tcc.TCCArea); acessoDadosSqlServer.AdicionarParametros("@TCCSubarea", tcc.TCCSubarea); acessoDadosSqlServer.AdicionarParametros("@TCCEspecialidade", tcc.TCCEspecialidade); acessoDadosSqlServer.AdicionarParametros("@TCCResumo", tcc.TCCResumo); acessoDadosSqlServer.AdicionarParametros("@TCCPaginas", tcc.TCCPaginas); acessoDadosSqlServer.AdicionarParametros("@TCCData", tcc.TCCData); acessoDadosSqlServer.AdicionarParametros("@TCCSalaID", tcc.TCCSalaID); acessoDadosSqlServer.AdicionarParametros("@TCCAlunoID", tcc.TCCAlunoID); acessoDadosSqlServer.AdicionarParametros("@TCCOrientadorID", tcc.TCCOrientadorID); string tccID = acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "INSERT INTO tblTCC (TCCTitulo,TCCGrandeArea,TCCArea,TCCSubarea,TCCEspecialidade,TCCResumo,TCCPaginas,TCCData,TCCSalaID,TCCAlunoID,TCCOrientadorID) VALUES (@TCCTitulo,@TCCGrandeArea,@TCCArea,@TCCSubarea,@TCCEspecialidade,@TCCResumo,@TCCPaginas,@TCCData,@TCCSalaID,@TCCAlunoID,@TCCOrientadorID) SELECT @@IDENTITY AS RETORNO").ToString(); return tccID; } catch (Exception ex) { return ex.Message; } } public string Alterar(TCC tcc) { try { acessoDadosSqlServer.LimparParametros(); acessoDadosSqlServer.AdicionarParametros("@TCCID", tcc.TCCID); acessoDadosSqlServer.AdicionarParametros("@TCCTitulo", tcc.TCCTitulo); acessoDadosSqlServer.AdicionarParametros("@TCCGrandeArea", tcc.TCCGrandeArea); acessoDadosSqlServer.AdicionarParametros("@TCCArea", tcc.TCCArea); acessoDadosSqlServer.AdicionarParametros("@TCCSubarea", tcc.TCCSubarea); acessoDadosSqlServer.AdicionarParametros("@TCCEspecialidade", tcc.TCCEspecialidade); acessoDadosSqlServer.AdicionarParametros("@TCCResumo", tcc.TCCResumo); acessoDadosSqlServer.AdicionarParametros("@TCCPaginas", tcc.TCCPaginas); acessoDadosSqlServer.AdicionarParametros("@TCCData", tcc.TCCData); acessoDadosSqlServer.AdicionarParametros("@TCCSalaID", tcc.TCCSalaID); acessoDadosSqlServer.AdicionarParametros("@TCCAlunoID", tcc.TCCAlunoID); acessoDadosSqlServer.AdicionarParametros("@TCCOrientadorID", tcc.TCCOrientadorID); string TCCID = acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "UPDATE tblTCC SET TCCTitulo = @TCCTitulo,TCCGrandeArea = @TCCGrandeArea,TCCArea = @TCCArea,TCCSubarea = @TCCSubarea,TCCEspecialidade = @TCCEspecialidade,TCCResumo = @TCCResumo,TCCPaginas = @TCCPaginas,TCCData = @TCCData,TCCSalaID = @TCCSalaID, TCCAlunoID = @TCCAlunoID, TCCOrientadorID = @TCCOrientadorID WHERE TCCID = @TCCID SELECT @TCCID AS RETORNO").ToString(); return TCCID; } catch (Exception ex) { return ex.Message; } } public string Excluir(TCC tcc) { try { acessoDadosSqlServer.LimparParametros(); acessoDadosSqlServer.AdicionarParametros("@TCCID", tcc.TCCID); string TCCID = acessoDadosSqlServer.ExecutarManipulacao(CommandType.Text, "DELETE FROM tblTCC WHERE TCCID = @TCCID SELECT @TCCID AS RETORNO").ToString(); return TCCID; } catch (Exception ex) { return ex.Message; } } public TCCColecao ConsultarPorTitulo(string titulo) { //Criar uma nova coleção de clientes (aqui ela está vazia) TCCColecao tccColecao = new TCCColecao(); acessoDadosSqlServer.LimparParametros(); acessoDadosSqlServer.AdicionarParametros("@TCCTitulo", titulo); DataTable dataTableTCC = acessoDadosSqlServer.ExecutarConsulta(CommandType.Text, "SELECT TCCID AS ID, AlunoID AS AlunoID, AlunoNome AS Aluno, TCCTitulo AS Titulo, ProfessorID AS OrientadorID, ProfessorNome AS Orientador, TCCGrandeArea AS 'Grande Area', TCCArea AS Area, TCCSubarea AS Subarea, TCCEspecialidade AS Especialidade, TCCPaginas AS 'N de Paginas', TCCData AS Data, SalaID AS SalaID, SalaNome AS Sala, UnidadeNome AS Unidade, TCCResumo AS Resumo FROM tblTCC INNER JOIN tblAluno ON TCCAlunoID = AlunoID INNER JOIN tblSala ON TCCSalaID = SalaID INNER JOIN tblUnidade ON SalaUnidadeID = UnidadeID INNER JOIN tblProfessor ON TCCOrientadorID = ProfessorID WHERE TCCTitulo LIKE '%' + @TCCTitulo + '%'"); //Percorrer o DataTable e transformar em coleção de cliente //Cada linha do DataTable é um cliente foreach (DataRow linha in dataTableTCC.Rows) { //Criar um cliente vazio //Colocar os dados da linha dele //Adicionar ele na coleção TCC tcc = new TCC(); tcc.TCCID = Convert.ToInt32(linha["ID"]); tcc.TCCAlunoID = Convert.ToInt32(linha["AlunoID"]); tcc.TCCAlunoNome = Convert.ToString(linha["Aluno"]); tcc.TCCTitulo = Convert.ToString(linha["Titulo"]); tcc.TCCOrientadorID = Convert.ToInt32(linha["OrientadorID"]); tcc.TCCOrientadorNome = Convert.ToString(linha["Orientador"]); tcc.TCCGrandeArea = Convert.ToString(linha["Grande Area"]); tcc.TCCArea = Convert.ToString(linha["Area"]); tcc.TCCSubarea = Convert.ToString(linha["Subarea"]); tcc.TCCEspecialidade = Convert.ToString(linha["Especialidade"]); tcc.TCCPaginas = Convert.ToInt32(linha["N de Paginas"]); tcc.TCCSalaID = Convert.ToInt32(linha["SalaID"]); tcc.TCCSalaNome = Convert.ToString(linha["Sala"]); tcc.TCCUnidade = Convert.ToString(linha["Unidade"]); tcc.TCCData = Convert.ToDateTime(linha["Data"]); tcc.TCCResumo = Convert.ToString(linha["Resumo"]); tccColecao.Add(tcc); } return tccColecao; } public TCCColecao ConsultarPorAluno(string aluno) { //Criar uma nova coleção de clientes (aqui ela está vazia) TCCColecao tccColecao = new TCCColecao(); acessoDadosSqlServer.LimparParametros(); acessoDadosSqlServer.AdicionarParametros("@TCCAlunoNome", aluno); DataTable dataTableTCC = acessoDadosSqlServer.ExecutarConsulta(CommandType.Text, "SELECT TCCID AS ID, AlunoID AS AlunoID, AlunoNome AS Aluno, TCCTitulo AS Titulo, ProfessorID AS OrientadorID, ProfessorNome AS Orientador, TCCGrandeArea AS 'Grande Area', TCCArea AS Area, TCCSubarea AS Subarea, TCCEspecialidade AS Especialidade, TCCPaginas AS 'N de Paginas', TCCData AS Data, SalaID AS SalaID, SalaNome AS Sala, UnidadeNome AS Unidade, TCCResumo AS Resumo FROM tblTCC INNER JOIN tblAluno ON TCCAlunoID = AlunoID INNER JOIN tblSala ON TCCSalaID = SalaID INNER JOIN tblUnidade ON SalaUnidadeID = UnidadeID INNER JOIN tblProfessor ON TCCOrientadorID = ProfessorID WHERE AlunoNome LIKE '%' + @TCCAlunoNome + '%'"); //Percorrer o DataTable e transformar em coleção de cliente //Cada linha do DataTable é um cliente foreach (DataRow linha in dataTableTCC.Rows) { //Criar um cliente vazio //Colocar os dados da linha dele //Adicionar ele na coleção TCC tcc = new TCC(); tcc.TCCID = Convert.ToInt32(linha["ID"]); tcc.TCCAlunoID = Convert.ToInt32(linha["AlunoID"]); tcc.TCCAlunoNome = Convert.ToString(linha["Aluno"]); tcc.TCCTitulo = Convert.ToString(linha["Titulo"]); tcc.TCCOrientadorID = Convert.ToInt32(linha["OrientadorID"]); tcc.TCCOrientadorNome = Convert.ToString(linha["Orientador"]); tcc.TCCGrandeArea = Convert.ToString(linha["Grande Area"]); tcc.TCCArea = Convert.ToString(linha["Area"]); tcc.TCCSubarea = Convert.ToString(linha["Subarea"]); tcc.TCCEspecialidade = Convert.ToString(linha["Especialidade"]); tcc.TCCPaginas = Convert.ToInt32(linha["N de Paginas"]); tcc.TCCSalaID = Convert.ToInt32(linha["SalaID"]); tcc.TCCSalaNome = Convert.ToString(linha["Sala"]); tcc.TCCUnidade = Convert.ToString(linha["Unidade"]); tcc.TCCData = Convert.ToDateTime(linha["Data"]); tcc.TCCResumo = Convert.ToString(linha["Resumo"]); tccColecao.Add(tcc); } return tccColecao; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; using Nito.HashAlgorithms; namespace UnitTests { public class CRC16UnitTests { [Fact] public void CRC16_Default_ChecksumVerification() { var calculator = new CRC16(); var test = Encoding.ASCII.GetBytes("123456789"); var result = calculator.ComputeHash(test, 0, test.Length); Assert.Equal(0xBB3D, BitConverter.ToUInt16(result, 0)); } [Fact] public void CRC16_CcittFalse_ChecksumVerification() { var calculator = new CRC16(CRC16.Definition.CcittFalse); var test = Encoding.ASCII.GetBytes("123456789"); var result = calculator.ComputeHash(test, 0, test.Length); Assert.Equal((ushort)0x29B1, BitConverter.ToUInt16(result, 0)); } [Fact] public void CRC16_Ccitt_ChecksumVerification() { var calculator = new CRC16(CRC16.Definition.Ccitt); var test = Encoding.ASCII.GetBytes("123456789"); var result = calculator.ComputeHash(test, 0, test.Length); Assert.Equal((ushort)0x2189, BitConverter.ToUInt16(result, 0)); } [Fact] public void CRC16_XModem_ChecksumVerification() { var calculator = new CRC16(CRC16.Definition.XModem); var test = Encoding.ASCII.GetBytes("123456789"); var result = calculator.ComputeHash(test, 0, test.Length); Assert.Equal((ushort)0x31C3, BitConverter.ToUInt16(result, 0)); } [Fact] public void CRC16_X25_ChecksumVerification() { var calculator = new CRC16(CRC16.Definition.X25); var test = Encoding.ASCII.GetBytes("123456789"); var result = calculator.ComputeHash(test, 0, test.Length); Assert.Equal((ushort)0x906E, BitConverter.ToUInt16(result, 0)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using NLog; namespace Booking.Data { public static class Mailer { private static Logger logger = LogManager.GetCurrentClassLogger(); private readonly static string _Alias = "info@koblevo.co"; private readonly static string _Domain = "koblevo.onmicrosoft.com"; private readonly static string _Password = "()_Koblevo()_"; private readonly static string _UserName = "mail@koblevo.onmicrosoft.com"; private readonly static string _smtp = "smtp.office365.com"; private readonly static int _port = 587; public static void SendMail(string address, string subject, string body) { MailAddress from = new MailAddress(_Alias); MailAddress to = new MailAddress(address); MailMessage m = new MailMessage(from, to); m.Subject = subject; m.Body = "<meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>" + body; m.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(_smtp, _port); smtp.EnableSsl = true; smtp.Credentials = new NetworkCredential() { Domain = _Domain, Password = _Password, UserName = _UserName }; try { smtp.Send(m); } catch (Exception ex) { logger.Error(ex); } } } }
#if NET6_0_OR_GREATER using System; using System.Collections.Generic; using System.Globalization; namespace NStandard { public static class DateOnlyEx { /// <summary> /// Gets a System.DateOnly object that is set to the current date on this computer. /// </summary> /// <returns></returns> public static DateOnly Today => DateOnly.FromDateTime(DateTime.Now); /// <summary> /// The number of complete years in the period. [ Similar as DATEDIF(*, *, "Y") function in Excel. ] /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static int Years(DateOnly start, DateOnly end) { var offset = end.Year - start.Year; var target = DateOnlyExtensions.AddYears(start, offset); if (end >= start) return end >= target ? offset : offset - 1; else return end <= target ? offset : offset + 1; } /// <summary> /// The number of complete months in the period, similar as DATEDIF(*, *, "M") function in Excel, but more accurate. /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static int Months(DateOnly start, DateOnly end) { var offset = (end.Year - start.Year) * 12 + end.Month - start.Month; var target = DateOnlyExtensions.AddMonths(start, offset); if (end >= start) return end >= target ? offset : offset - 1; else return end <= target ? offset : offset + 1; } /// <summary> /// The number of complete years in the period, expressed in whole and fractional year. [ Similar as DATEDIF(*, *, "Y") function in Excel. ] /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static double TotalYears(DateOnly start, DateOnly end) { var integer = Years(start, end); var targetStart = DateOnlyExtensions.AddYears(start, integer); if (end >= start) { var targetEnd = DateOnlyExtensions.AddYears(start, integer + 1); var fractional = (double)(end.DayNumber - targetStart.DayNumber) / (targetEnd.DayNumber - targetStart.DayNumber); return integer + fractional; } else { var targetEnd = DateOnlyExtensions.AddYears(start, integer - 1); var fractional = (double)(targetStart.DayNumber - end.DayNumber) / (targetStart.DayNumber - targetEnd.DayNumber); return integer - fractional; } } /// <summary> /// The number of complete months in the period, expressed in whole and fractional month. [ similar as DATEDIF(*, *, "M") function in Excel. ] /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static double TotalMonths(DateOnly start, DateOnly end) { var integer = Months(start, end); var targetStart = DateOnlyExtensions.AddMonths(start, integer); if (end >= start) { var targetEnd = DateOnlyExtensions.AddMonths(start, integer + 1); var fractional = (double)(end.DayNumber - targetStart.DayNumber) / (targetEnd.DayNumber - targetStart.DayNumber); return integer + fractional; } else { var targetEnd = DateOnlyExtensions.AddMonths(start, integer - 1); var fractional = (double)(targetStart.DayNumber - end.DayNumber) / (targetStart.DayNumber - targetEnd.DayNumber); return integer - fractional; } } /// <summary> /// Gets a DateOnly for the specified week of year. /// </summary> /// <param name="year"></param> /// <param name="week"></param> /// <param name="weekStart"></param> /// <returns></returns> public static DateOnly ParseFromWeek(int year, int week, DayOfWeek weekStart = DayOfWeek.Sunday) { var day1 = new DateOnly(year, 1, 1); var week0 = DateOnlyExtensions.PastDay(day1, weekStart, true); if (week0.Year == year) week0 = week0.AddDays(-7); return week0.AddDays(week * 7); } } } #endif
using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Reflection; using System.Xml; using Telerik.OpenAccess; namespace Telerik.OpenAccess.Tools { public sealed class OpenAccessProperties : Task { private bool help; private ITaskItem projFile; private bool doEnhance; private int level; private string config; private string connId = string.Empty; private bool doUpdate; private bool useMSBuild; private readonly string version; private ITaskItem apiAssembly; [Output] public ITaskItem Assembly { get { return this.apiAssembly; } } [Output] public string ConfigFile { get { return this.config; } set { this.config = value; } } [Output] public string ConnectionId { get { return this.connId; } set { this.connId = value; } } [Output] public int EnhancementOutputLevel { get { return this.level; } set { this.level = value; } } [Output] public bool Enhancing { get { return this.doEnhance; } set { this.doEnhance = value; } } public bool Help { get { return this.help; } set { this.help = value; } } [Required] public ITaskItem ProjectFile { get { return this.projFile; } set { this.projFile = value; } } [Output] public bool UpdateDatabase { get { return this.doUpdate; } set { this.doUpdate = value; } } [Output] public bool UseMSBuild { get { return this.useMSBuild; } set { this.useMSBuild = value; } } [Output] public string Version { get { return this.version; } } public OpenAccessProperties() { this.version = typeof(Enhancer).Assembly.GetName().Version.ToString(); } public override bool Execute() { base.Log.LogMessage(MessageImportance.Normal, string.Concat("Checking properties from ", this.projFile.ItemSpec), new object[0]); if (this.Help) { base.Log.LogMessage(MessageImportance.Normal, "Properies task help", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] UseMSBuild=bool", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] Enhancing=bool", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] EnhancementOutputLevel=integer", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] ConfigFile=filename", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] ConnectionId=string", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] UpdateDatabase=bool", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] Version=string", new object[0]); base.Log.LogMessage(MessageImportance.Normal, " [Out] Assembly=filename", new object[0]); string projectFileOfTaskNode = base.BuildEngine.ProjectFileOfTaskNode; base.Log.LogMessage(MessageImportance.Normal, string.Concat("Called by ", projectFileOfTaskNode), new object[0]); } this.apiAssembly = new TaskItem(typeof(PersistentAttribute).Assembly.Location ?? "<no-OpenAccess-location-found>"); XmlNode xmlNodes = OpenAccessProperties.OurNode(this.projFile.GetMetadata("FullPath")); if (xmlNodes != null) { if (this.Help) { base.Log.LogMessage(MessageImportance.Normal, "Found Telerik Data Access enabled project", new object[0]); } XmlAttributeCollection attributes = xmlNodes.Attributes; if (attributes != null) { this.Fill(attributes, "Enhancing"); this.Fill(attributes, "EnhancementOutputLevel"); this.Fill(attributes, "ConfigFile"); this.Fill(attributes, "ConnectionId"); this.Fill(attributes, "UpdateDatabase"); this.Fill(attributes, "UseMSBuild"); } } return true; } private void Fill(XmlAttributeCollection attrs, string what) { string value; PropertyInfo property = base.GetType().GetProperty(what); if (property == null) { throw new Exception(string.Concat("Wrong property name ", what)); } XmlAttribute itemOf = attrs[string.Concat("OpenAccess_", what)]; if (itemOf != null) { value = itemOf.Value; } else { value = null; } string str = value; if (str == null) { return; } if (property.PropertyType == typeof(string)) { property.SetValue(this, str, null); return; } if (property.PropertyType == typeof(bool)) { property.SetValue(this, bool.Parse(str), null); return; } if (property.PropertyType != typeof(int)) { throw new Exception(string.Concat("Wrong property type for ", what)); } property.SetValue(this, int.Parse(str), null); } private static XmlNode FindNode(XmlNode n, string name) { XmlNode xmlNodes; if (n == null) { return null; } IEnumerator enumerator = n.ChildNodes.GetEnumerator(); try { while (enumerator.MoveNext()) { XmlNode current = (XmlNode)enumerator.Current; if (!name.Equals(current.Name)) { continue; } xmlNodes = current; return xmlNodes; } return null; } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } return xmlNodes; } private static XmlNode OurNode(string projFile) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(projFile); XmlNode xmlNodes = OpenAccessProperties.FindNode(xmlDocument, "Project"); xmlNodes = OpenAccessProperties.FindNode(xmlNodes, "ProjectExtensions"); return OpenAccessProperties.FindNode(OpenAccessProperties.FindNode(xmlNodes, "VisualStudio"), "UserProperties"); } } }
using System.Collections.Generic; using Profiling2.Domain.Prf.Events; using Profiling2.Domain.Prf.Persons; using Profiling2.Domain.Prf.Suggestions; using SharpArch.Domain.DomainModel; namespace Profiling2.Infrastructure.Suggestions { public class EventRelationshipSuggestions : BaseSuggestions { public EventRelationshipSuggestions(Person p, IEnumerable<EventRelationship> relationships) : base(p) { foreach (EventRelationship er in relationships) { Event other = null; Event responsibleEvent = null; if (!er.SubjectEvent.IsPersonResponsible(p)) { other = er.SubjectEvent; responsibleEvent = er.ObjectEvent; } else if (!er.ObjectEvent.IsPersonResponsible(p)) { other = er.ObjectEvent; responsibleEvent = er.SubjectEvent; } if (other != null && !other.Archive) { SuggestedFeature sf = new SuggestedFeature() { FeatureID = this.Features[AdminSuggestionFeaturePersonResponsibility.RESPONSIBLE_FOR_RELATED_EVENT].Id }; this.AddSuggestionFeatureWithReason(sf, other, responsibleEvent); } } } protected override string ConstructSuggestionReason(Entity entity) { if (entity != null) { Event e = (Event)entity; return "(Profiled) " + this.Person.Name + " bears responsibility for " + e.ToString() + " which is related to this event."; } return string.Empty; } } }
using System.Linq; using System.Web.Mvc; using System.Web.Routing; namespace Pe.Stracon.Politicas.Presentacion { /// <summary> /// Controlador que muestra la configuración de la ruta /// </summary> /// <remarks> /// Creación: GMD 20150430 <br /> /// Modificación: <br /> /// </remarks> public class RouteConfig { /// <summary> /// Método para Registrar Routes /// </summary> /// <param name="routes">Routes</param> public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Where(r => r is Route).ToList().ForEach(r => { Route router = (Route)r; if (router.DataTokens != null && router.DataTokens.ContainsKey("area")) { router.DataTokens["Namespaces"] = "Pe.Stracon.Politicas.Presentacion.Core.Controllers." + router.DataTokens["area"]; } }); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { areaDefault = "General", controller = "UnidadOperativa", action = "Index", id = UrlParameter.Optional } ).DataTokens.Add("area", "General"); } } }
using UnityEngine; using System.Collections; public class PointClickCity : MonoBehaviour { Vector3 spot; // Use this for initialization void Start () { spot = transform.position; } // Update is called once per frame void Update () { Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition ); RaycastHit rayHit = new RaycastHit(); if (Input.GetMouseButtonDown(0)){ if ( Physics.Raycast(ray, out rayHit)){ spot = rayHit.point; if (Input.GetKeyDown(KeyCode.LeftArrow)){ transform.Rotate ( 0f, -45f ,0f ); } } } } void FixedUpdate (){ Vector3 direction = Vector3.Normalize( spot - transform.position ); if (Vector3.Distance(spot, transform.position) > 35){ rigidbody.AddForce( direction * 50 ); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PersonasPhone.Entidades; using PersonasPhone.BLL; using System.Linq.Expressions; using PersonasPhone.UI.Registros; using PersonasPhone.DAL; namespace PersonasPhone.UI { public partial class TelefonoDetalleForm : Form { public List<TelefonoDetalle> Detalle { get; set; } Expression<Func<TelefonoDetalle, bool>> filtrar = x => true; public TelefonoDetalleForm() { InitializeComponent(); this.Detalle = new List<TelefonoDetalle>(); LlenarComboBox(); Llenaclase(); } private void CargarGrid() { DetalledataGridView.DataSource = null; DetalledataGridView.DataSource = this.Detalle; } public void Limpiar() { errorProvider.Clear(); IdnumericUpDown.Value = 0; NombretextBox.Clear(); CedulamaskedTextBox.Text = string.Empty; DirecciontextBox.Clear(); FechadateTimePicker.Value = DateTime.Now; this.Detalle = new List<TelefonoDetalle>(); CargarGrid(); } private void LlenarComboBox() { Repositorio<Persona> persona = new Repositorio<Persona>(new Contexto()); TypecomboBox.DataSource = persona.GetList(c => true); TypecomboBox.ValueMember = "TypeTelefono"; TypecomboBox.DisplayMember = "TypeTelefono"; } private void LlenarCampos(Persona persona) { IdnumericUpDown.Value = persona.IdPersona; NombretextBox.Text = persona.Nombre; CedulamaskedTextBox.Text = persona.Cedula.ToString(); DirecciontextBox.Text = persona.Direccion; FechadateTimePicker.Value = persona.FechaNacimiento; this.Detalle = persona.Telefonos; CargarGrid(); } private Persona Llenaclase() { Persona persona = new Persona(); if (IdnumericUpDown.Value == 0) { persona.IdPersona = 0; } else { persona.IdPersona = Convert.ToInt32(IdnumericUpDown.Value); } persona.Nombre = NombretextBox.Text; persona.Cedula = Convert.ToInt32(CedulamaskedTextBox.Text); persona.Direccion = DirecciontextBox.Text; persona.FechaNacimiento = FechadateTimePicker.Value; return persona; } private bool Validar(int error) { bool paso = false; if (error == 1 && IdnumericUpDown.Value == 0) { IderrorProvider.SetError(IdnumericUpDown, "Llenar Id"); paso = true; } if (error == 2 && TypecomboBox.Text == string.Empty) { errorProvider.SetError(TypecomboBox, "Debes seleccionar un Tipo"); paso = true; } if (error == 2 && CedulamaskedTextBox.Text == string.Empty) { errorProvider.SetError(CedulamaskedTextBox, "Debes ingresar una Cedula"); paso = true; } if (error == 2 && NombretextBox.Text == string.Empty) { errorProvider.SetError(NombretextBox, "Debes ingresar un Nombre"); paso = true; } if (error == 2 && DirecciontextBox.Text == string.Empty) { errorProvider.SetError(DirecciontextBox, "Debes ingresar una Direccion"); paso = true; } if (error == 2 && TelefonomaskedTextBox.Text == string.Empty) { errorProvider.SetError(TelefonomaskedTextBox, "Debes ingresar un numero de Telefono"); paso = true; } return paso; } private void Buscarbutton_Click(object sender, EventArgs e) { if (Validar(1)) { MessageBox.Show("Favor de llenar casilla para poder Buscar"); } else { int id = Convert.ToInt32(IdnumericUpDown.Value); Persona persona = BLL.PersonaBLL.Buscar(id); if (persona != null) { IdnumericUpDown.Value = persona.IdPersona; NombretextBox.Text = persona.Nombre; CedulamaskedTextBox.Text = persona.Cedula.ToString(); DirecciontextBox.Text = persona.Direccion.ToString(); FechadateTimePicker.Value = persona.FechaNacimiento; CargarGrid(); } else { MessageBox.Show("No Fue Encontrado!", "Fallido", MessageBoxButtons.OK, MessageBoxIcon.Error); } errorProvider.Clear(); } } private void NuevoButtton_Click(object sender, EventArgs e) { IdnumericUpDown.Value = 0; NombretextBox.Clear(); DirecciontextBox.Clear(); FechadateTimePicker.Value = DateTime.Now; TelefonomaskedTextBox.Clear(); TypecomboBox.SelectedValue = null; TelefonomaskedTextBox.Clear(); DetalledataGridView.DataSource = null; } private void GuardarButton_Click(object sender, EventArgs e) { Persona persona = new Persona(); if (Validar(2)) { MessageBox.Show("Llenar Campos vacios"); errorProvider.Clear(); return; } else { persona = Llenaclase(); if (IdnumericUpDown.Value == 0) { if (BLL.PersonaBLL.Guardar(persona)) { MessageBox.Show("Guardado!", "Exitoso", MessageBoxButtons.OK, MessageBoxIcon.Information); Limpiar(); } else { MessageBox.Show("No se pudo Guardar!!"); } } else { var result = MessageBox.Show("Seguro de Modificar?", "+Persona", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { if (BLL.PersonaBLL.Modificar(Llenaclase())) { MessageBox.Show("Modificado!!"); Limpiar(); } else { MessageBox.Show("No se pudo Guardar!!"); } } } } } private void EliminarButton_Click(object sender, EventArgs e) { if (Validar(1)) { MessageBox.Show("Llenar campos Vacios"); return; } var result = MessageBox.Show("Seguro de Eliminar?", "+Partidos", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { if (BLL.PersonaBLL.Eliminar(Convert.ToInt32(IdnumericUpDown.Value))) { MessageBox.Show("Eliminado"); Limpiar(); } else { MessageBox.Show("No se pudo eliminar"); } } } private void Addbutton_Click(object sender, EventArgs e) { TypeTelefonoForm typeTelefono = new TypeTelefonoForm(); typeTelefono.Show(); } private void Agregarbutton_Click(object sender, EventArgs e) { List<TelefonoDetalle> telefonoDetalles = new List<TelefonoDetalle>(); if (Validar(2)) { MessageBox.Show("Llene los Campos", "Validacion", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { Detalle.Add(new TelefonoDetalle( id: 0, idPersona: (int)IdnumericUpDown.Value, telefonos:TelefonomaskedTextBox.Text, typeTelefono: TypecomboBox.Text )); //Cargar el detalle al Grid CargarGrid(); TelefonomaskedTextBox.Focus(); TelefonomaskedTextBox.Clear(); TypecomboBox.ResetText(); DetalledataGridView.DataSource = null; } } private void Borrarbutton_Click(object sender, EventArgs e) { if (DetalledataGridView.Rows.Count > 0 && DetalledataGridView.CurrentRow != null) { Detalle.RemoveAt(DetalledataGridView.CurrentRow.Index); CargarGrid(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Description résumée de ModuleRepository /// </summary> public class ModuleRepository { protected TypeModuleRepository typeModuleRepository; protected ComposantRepository composantRepository; public ModuleRepository() { typeModuleRepository = new TypeModuleRepository(); composantRepository = new ComposantRepository(); } public void Add(Module module) { MODULE entity = new MODULE(); entity.MODULE_ID = module.Id; entity.MODULE_NOM = module.Nom; entity.MODULE_TYPE = module.Type; entity.MODULE_MARGE_COMMERCIAL = module.MargeCommercial; entity.MODULE_MARGE_ENTREPRISE = module.MargeEntreprise; // temp entity.PERSONNEL_ID = 0; using (var db = new maderaEntities()) { db.MODULE.Add(entity); db.SaveChanges(); } } public List<ModuleCompose> GetCompositionByModeleGamme(ModeleDeGamme modeleGamme) { List<ModuleCompose> dtos = new List<ModuleCompose>(); using (var db = new maderaEntities()) { var queryLierModule = from a in db.LIER_MODULE where a.MODELE_GAMME_ID.Equals(modeleGamme.Id) select a; foreach (var item in queryLierModule) { ModuleCompose dto = new ModuleCompose(); dto.Section = item.SECTION; dto.Module = GetOne(item.MODULE_ID); dto.Hauteur = item.HAUTEUR; dto.Longueur = item.LONGUEUR; dto.Identification = item.IDENTIFICATION; dtos.Add(dto); } } return dtos; } public List<ModuleCompose> GetCompositionByIdModeleGamme(int id) { List<ModuleCompose> dtos = new List<ModuleCompose>(); using (var db = new maderaEntities()) { var queryLierModule = from a in db.LIER_MODULE where a.MODELE_GAMME_ID.Equals(id) select a; foreach (var item in queryLierModule) { ModuleCompose dto = new ModuleCompose(); dto.Section = item.SECTION; dto.Module = GetOne(item.MODULE_ID); dto.Hauteur = item.HAUTEUR; dto.Longueur = item.LONGUEUR; dto.Identification = item.IDENTIFICATION; dtos.Add(dto); } } return dtos; } public Module GetOne(int id) { Module dto = new Module(); using (var db = new maderaEntities()) { var query = from a in db.MODULE where a.MODULE_ID.Equals(id) select a; dto.Id = query.First().MODULE_ID; dto.MargeCommercial = query.First().MODULE_MARGE_COMMERCIAL; dto.MargeEntreprise = query.First().MODULE_MARGE_ENTREPRISE; dto.Nom = query.First().MODULE_NOM; dto.TypeModule = typeModuleRepository.GetOne(query.First().TYPE_MODULE_ID); dto.ComposantsCoupePrincipe = composantRepository.GetComposantCoupePrincipeByModule(dto); var queryAssoc = from a in db.ASSOC_MODULE where a.MODULE_PARENT_ID.Equals(dto.Id) select a; List<Module> enfants = new List<Module>(); foreach (var item in queryAssoc) { Module enfant = GetOne(item.MODULE_ENFANT_ID); enfant.QuantiteCompositionParent = item.QUANTITE; enfants.Add(enfant); } dto.Enfants = enfants; } return dto; } public List<Module> GetByGamme(Gamme gamme) { List<Module> dtos = new List<Module>(); using (var db = new maderaEntities()) { var query = from a in db.EST_DISPONIBLE where a.GAMME_ID.Equals(gamme.Id) select a; foreach (var item in query) { Module module = GetOne(item.MODULE_ID); dtos.Add(module); } } return dtos; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Z.Framework.Common; namespace Z.Framework.DAL { public class BasicOperation { DbEntity.zEntity Db = new DbEntity.zEntity(); ResultInfo rst = new ResultInfo(); public ResultInfo GetConnection() { var ip = "127.0.0.0"; return GetConnection(ip); } public ResultInfo GetConnection(string ip) { try { var count = Db.T_ACCOUNT.Count(); if (ip != string.Empty) { } rst.IsSuccessed = true; return rst; } catch(Exception ex) { rst.IsSuccessed = false; rst.ErrorText = ex.Message; return rst; } } } }
namespace TPMDocs.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("sbyt.tbContractCategories")] public partial class tbContractCategory { public int? Category { get; set; } [Key] [Column(Order = 0)] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Code { get; set; } [StringLength(100)] public string Name1 { get; set; } [StringLength(100)] public string Name2 { get; set; } [StringLength(100)] public string Name3 { get; set; } public double? Double1 { get; set; } public double? Double2 { get; set; } public int? Long1 { get; set; } public int? Long2 { get; set; } public bool? IsArchived { get; set; } public DateTime? CrDate { get; set; } [Key] [Column(Order = 1, TypeName = "timestamp")] [MaxLength(8)] [Timestamp] public byte[] SSMA_TimeStamp { get; set; } } }
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; namespace WorkProgramsSequelApp { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void buttonDB_Click(object sender, EventArgs e) { var dbForm = new DataBaseForm(); dbForm.ShowDialog(); } private void buttonSelectDoc_Click(object sender, EventArgs e) { var genForm = new GenerateForm(); genForm.ShowDialog(); } } }
// // Copyright (c) Christopher Kyle Horton. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Collections.Generic; namespace FileFilters { /// <summary> /// A class used to construct file filter strings. /// </summary> public class SimpleFileFilterBuilder { private SortedSet<FileFilterExtension> _fileExtensions; /// <summary> /// Gets or sets the name displayed at the front of this file filter. /// </summary> public string Name { get; set; } = "Files"; /// <summary> /// Gets a sorted array of all <see cref="FileFilterExtension"/> objects /// currently stored within this instance. /// </summary> public FileFilterExtension[] FileExtensions { get { FileFilterExtension[] fileExtensionsArray = new FileFilterExtension[_fileExtensions.Count]; _fileExtensions.CopyTo(fileExtensionsArray); return fileExtensionsArray; } } /// <summary> /// Gets the number of file extensions currently stored in this /// <see cref="SimpleFileFilterBuilder"/> instance. /// </summary> public int FileExtensionCount { get { return _fileExtensions.Count; } } /// <summary> /// Gets the filter pattern portion of the current file filter represented /// by this instance. /// </summary> public string FilterPattern { get { return "*." + string.Join(";*.", _fileExtensions); } } /// <summary> /// Initializes a new instance of the <see cref="SimpleFileFilterBuilder"/> class. /// </summary> public SimpleFileFilterBuilder() { _fileExtensions = new SortedSet<FileFilterExtension>(); } /// <summary> /// Initializes a new instance of the <see cref="SimpleFileFilterBuilder"/> class. /// </summary> /// <param name="name">The name to display at the front of the file filter.</param> public SimpleFileFilterBuilder(string name) { Name = name; _fileExtensions = new SortedSet<FileFilterExtension>(); } /// <summary> /// Initializes a new instance of the <see cref="SimpleFileFilterBuilder"/> class /// using the provided <see cref="IEnumerable{T}"/> of file extensions. /// </summary> /// <param name="fileExtensions"> /// The enumerable collection of file extensions to copy and initialize this /// instance with. /// </param> public SimpleFileFilterBuilder(IEnumerable<FileFilterExtension> fileExtensions) { _fileExtensions = new SortedSet<FileFilterExtension>(fileExtensions); } /// <summary> /// Initializes a new instance of the <see cref="SimpleFileFilterBuilder"/> class /// using the provided <see cref="IEnumerable{T}"/> of file extensions. /// </summary> /// <param name="name">The name to display at the front of the file filter.</param> /// <param name="fileExtensions"> /// The enumerable collection of file extensions to copy and initialize this /// instance with. /// </param> public SimpleFileFilterBuilder(string name, IEnumerable<FileFilterExtension> fileExtensions) { Name = name; _fileExtensions = new SortedSet<FileFilterExtension>(fileExtensions); } /// <summary> /// Adds a file extension to this <see cref="SimpleFileFilterBuilder"/> and returns /// a value indicating whether the addition was successful. /// </summary> /// <param name="extension">The file extension to add.</param> /// <returns>True if the addition was successful; false otherwise.</returns> public bool AddFileExtension(FileFilterExtension extension) { return _fileExtensions.Add(extension); } /// <summary> /// Returns the current <see cref="string"/> representation of this file filter. /// </summary> /// <remarks> /// The <see cref="string"/> returned by this function can be directly used /// in the <code>FileFilter</code> property of Windows Forms' <code>FileDialog</code> /// class. /// </remarks> /// <returns>The current <see cref="string"/> representation of this file filter.</returns> public override string ToString() { return string.Format("{0} ({1})|{1}", Name, FilterPattern); } } }
using Microsoft.AspNetCore.Diagnostics; using NetSix.Errors; using NetSix.Services; var builder = WebApplication.CreateBuilder(args); builder.Services.AddHttpContextAccessor(); builder.Services.AddSingleton<IUsersService, UsersService>(); var app = builder.Build(); app.UseExceptionHandler("/error"); app.MapGet("users/{id}", (Guid id, IUsersService usersService) => usersService.Get(id)); app.Map("/error", (IHttpContextAccessor httpContextAccessor) => { Exception? exception = httpContextAccessor.HttpContext? .Features.Get<IExceptionHandlerFeature>()? .Error; return exception is ServiceException e ? Results.Problem(title: e.ErrorMessage, statusCode: e.HttpStatusCode) : Results.Problem(title: "An error occurred while processing your request", statusCode: StatusCodes.Status500InternalServerError); }); app.Run();
using System; using System.Linq; // ReSharper disable once CheckNamespace namespace Microsoft.AspNetCore.Http { public static class HttpContextExtensions { public static string? GetCorrelationId(this HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } return context.Request.Headers.TryGetValue(WellKnownHttpHeaders.CorrelationId, out var header) ? header.FirstOrDefault() : null; } public static string? GetRequestId(this HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } return context.Request.Headers.TryGetValue(WellKnownHttpHeaders.RequestId, out var header) ? header.FirstOrDefault() : null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08.Maximum_Sum { class MaximalSum { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); int[] numbers = new int[n]; for (int i = 0; i < numbers.Length; i++) { numbers[i] = int.Parse(Console.ReadLine()); } Console.WriteLine(findMaxSum(numbers)); } public static int findMaxSum(int[] anArray) { int currentSum = 0; int currentMax = 0; for (int j = 0; j < anArray.Length; j++) { currentSum += anArray[j]; if (currentMax < currentSum) currentMax = currentSum; else if (currentSum < 0) currentSum = 0; } return currentMax; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Menui : MonoBehaviour { private FPScontroller fpsController; private Canvas menui; void Start() { menui = GetComponent<Canvas>(); fpsController = FindObjectOfType<FPScontroller>(); } public void Back() { menui.enabled = !menui.enabled; } public void Sensitivity(float sens) { fpsController.sensitivity = sens; } public void SensitivityAds(float sens) { fpsController.sensitivityADS = sens; } }
using ClaimDi.DataAccess.Object.API; using System.IO; using System.ServiceModel; using System.ServiceModel.Web; namespace Claimdi.WCF.Consumer { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ITask" in both code and config file together. [ServiceContract] public interface ITaskInfo { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/upload_image", ResponseFormat = WebMessageFormat.Json)] BaseResult<APIUploadImageResponse> UploadImage(Stream data); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/update_flag_upload_image", ResponseFormat = WebMessageFormat.Json)] BaseResult<bool?> UpdateIsUploadPicture(APIUpdateIsUploadPicture request); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "/tasks", ResponseFormat = WebMessageFormat.Json)] BaseResult<APITasksResponse> GetTasks(APITaskSearch request); } }
using UnityEngine; using UnityEngine.Events; public class Player : MonoBehaviour { public Transform cam; public float speed = 5f; public float jumpForce = 0.1f; public float gravityMultiplier = 0.1f; public float maxHP; public float HP; private float xRot = 0; private float yRot = 0; private float dxRot = 0; private float dyRot = 0; private Vector3 gravity; private CharacterController controller; [ColorUsage(true, true)] public Color fullColor; [ColorUsage(true, true)] public Color emptyColor; [ColorUsage(true, true)] public Color stopGlowColor; public Material EnergyVisualiser; public Material HealthVisualiser; public float playerEnergy = 5; //[System.NonSerialized] public float energy = 5; private Vector3 movement; private GameObject cmhelper; private Vector2 camMotion; private Vector2 camLast; public bool dead = false; private bool invokedEvent = false; public AudioSource stepSource; public UnityEvent onEnergyEnd; #region Singleton public static Player instance; private void Awake() { if (instance != null) { Destroy(instance); } instance = this; } #endregion private void Start() { TimeController.instance.frame = 0; playerEnergy = LevelInfo.instance.playerEnergy; energy = LevelInfo.instance.playerEnergy; HP = LevelInfo.instance.playerHealth; maxHP = LevelInfo.instance.playerHealth; dyRot = transform.rotation.eulerAngles.y; yRot = transform.rotation.eulerAngles.y; Cursor.lockState = CursorLockMode.Locked; controller = GetComponent<CharacterController>(); cmhelper = new GameObject("Camera Rotation Helper"); HP = maxHP; } private void Update() { if(energy <= 0 && !invokedEvent) { invokedEvent = true; onEnergyEnd.Invoke(); } HealthVisualiser.SetFloat("Saturation", HP / maxHP); EnergyVisualiser.SetColor("_EmissionColor", Color.Lerp(emptyColor, fullColor, energy / playerEnergy)); if (Input.GetKeyDown(KeyCode.R)) { LevelInfo.instance.ReloadLevel(); } if (Input.GetKeyDown(KeyCode.M)) { LevelInfo.instance.Menu(); } if (dead) { return; } camMotion = new Vector2(xRot, yRot) - camLast; camLast = new Vector2(xRot, yRot); if (TimeController.instance.playbackMode) { return; } gravity = Vector3.zero; dxRot -= Input.GetAxis("Mouse Y"); dyRot += Input.GetAxis("Mouse X"); //limit rotation if (dxRot > 90) { dxRot = 90; } if (dxRot < -90) { dxRot = -90; } xRot = Mathf.Lerp(xRot, dxRot, Time.deltaTime * 50); yRot = Mathf.Lerp(yRot, dyRot, Time.deltaTime * 50); transform.rotation = Quaternion.Euler(0, yRot, 0); cam.localRotation = Quaternion.Euler(xRot, 0, 0); if (HP < 0) { Die(); } float my = movement.y; movement = (transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal")) * speed; movement.y = my; if(movement.x + movement.z != 0) { if(!stepSource.loop) { stepSource.loop = true; stepSource.Play(); } } else { stepSource.loop = false; stepSource.Stop(); } if (controller.isGrounded) { movement.y = 0; if (Input.GetButton("Jump")) { movement.y = jumpForce; } } movement.y -= gravityMultiplier * Time.deltaTime; controller.Move(Time.deltaTime * movement); } public void CameraLook(Vector3 position) { cmhelper.transform.LookAt(position); dyRot -= camMotion.y * 70; dxRot -= camMotion.x * 70; } public void Damage(float amount) { HP -= amount; } public void Die() { if (dead) return; HP = 0; dead = true; Time.timeScale = 0.2f; LevelInfo.instance.Death(); } public void StopRewind() { TimeController.instance.playbackMode = false; } }
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 MOTHER3; using Extensions; namespace MOTHER3Funland { public partial class frmTownMapEditor : M3Form { bool loading = false; // Text cache string[] mapnames = null; public frmTownMapEditor() { InitializeComponent(); // Get the map names mapnames = Properties.Resources.townmapnames.SplitN(); loading = true; for (int i = 0; i < mapnames.Length; i++) cboMap.Items.Add("[" + i.ToString("X2") + "] " + mapnames[i]); loading = false; cboMap.SelectedIndex = 0; } public override void SelectIndex(int[] index) { cboMap.SelectedIndex = index[0]; if (index.Length == 1) return; arrEditor.CurrentPalette = index[1]; arrEditor.CurrentTile = index[2]; arrEditor.SplitMainPosition = index[3]; arrEditor.SplitLeftPosition = index[4]; arrEditor.GridArr = index[5] != 0; arrEditor.ZoomArr = index[6]; arrEditor.GridTileset = index[7] != 0; arrEditor.ZoomTileset = index[8]; arrEditor.GridTile = index[9] != 0; arrEditor.ZoomTile = index[10]; } public override int[] GetIndex() { return new int[] { cboMap.SelectedIndex, arrEditor.CurrentPalette, arrEditor.CurrentTile, arrEditor.SplitMainPosition, arrEditor.SplitLeftPosition, arrEditor.GridArr ? 1 : 0, arrEditor.ZoomArr, arrEditor.GridTileset ? 1 : 0, arrEditor.ZoomTileset, arrEditor.GridTile ? 1 : 0, arrEditor.ZoomTile }; } private void cboMap_SelectedIndexChanged(object sender, EventArgs e) { if (loading) return; int index = cboMap.SelectedIndex; // Arrangement arrEditor.Clear(); int[] gfxEntry = GfxTownMaps.GetEntry(index * 3); var palette = GfxTownMaps.GetPalette((index * 3) + 1); var arr = GfxTownMaps.GetArr((index * 3) + 2); byte[] tileset = new byte[0x8000]; Array.Copy(M3Rom.Rom, gfxEntry[0], tileset, 0, gfxEntry[1]); arrEditor.SetTileset(tileset, 0, -1, gfxEntry[1] >> 5); arrEditor.SetArrangement(arr, 64, 64); arrEditor.SetPalette(palette); arrEditor.RenderArr(); arrEditor.RenderTileset(); arrEditor.CurrentTile = 0; arrEditor.RefreshArr(); } private void btnApply_Click(object sender, EventArgs e) { int index = cboMap.SelectedIndex; // Arrangement GfxTownMaps.SetArr((index * 3) + 2, arrEditor.GetArrangement()); // Graphics byte[] tileset = arrEditor.GetTileset(); int[] gfxEntry = GfxTownMaps.GetEntry(index * 3); Array.Copy(tileset, 0, M3Rom.Rom, gfxEntry[0], gfxEntry[1]); // Palette int[] palEntry = GfxTownMaps.GetEntry((index * 3) + 1); var palette = arrEditor.GetPalette(); M3Rom.Rom.WritePal(palEntry[0], palette); M3Rom.IsModified = true; int currentpal = arrEditor.CurrentPalette; int currenttile = arrEditor.CurrentTile; int primarycol = arrEditor.PrimaryColorIndex; int secondarycol = arrEditor.SecondaryColorIndex; cboMap_SelectedIndexChanged(null, null); arrEditor.CurrentPalette = currentpal; arrEditor.PrimaryColorIndex = primarycol; arrEditor.SecondaryColorIndex = secondarycol; arrEditor.CurrentTile = currenttile; } } }
/**************************************************************************************** * Wakaka Studio 2017 * Author: iLYuSha Dawa-mumu Wakaka Kocmocovich Kocmocki KocmocA * Project:: 0escape Medieval - Round Table * Tools: Unity 5/C# + Arduino/C++ * Last Updated: 2017/07/29 ****************************************************************************************/ using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; using DG.Tweening; public class WakakaGalaxy : MonoBehaviour { public void Quit() { Application.Quit(); } public GameObject Observatory; //private int pentagramOrder; // 五芒星棋盤10條線的編號 private string[] roundTableKnight; // 圓柱目前所屬的騎士 public GameObject roundTableThrone; public GameObject[] roundTableTristana; public GameObject[] roundTableGalahad; public GameObject[] roundTableArthur; public GameObject[] roundTableLancelot; public Transform[] roundTable; public Transform star; public Transform[] starNode; public GameObject table; public Transform goal; private bool ready; private bool roll; public GameObject pentagram; private int laserPoint; public Text rotText; private float startTime; private float recordTime; void Awake() { //if (ArduinoController.instance == null) //{ // PlayerPrefs.SetInt("lastScene", SceneManager.GetActiveScene().buildIndex+100); // SceneManager.LoadScene("Arduino Controller"); //} //roundTableKnight = new string[5]; //roundTableKnight[0] = ""; //roundTableKnight[1] = "Tristan"; //roundTableKnight[2] = "Galahad"; //roundTableKnight[3] = "Arthur"; //roundTableKnight[4] = "Lancelot"; //pentagram.SetActive(false); //ready = true; } IEnumerator End() { DOTween.To(x => pentagram.GetComponent<CanvasGroup>().alpha = x, 1, 0, 3); yield return new WaitForSeconds(3.0f); star.gameObject.SetActive(false); table.SetActive(true); table.transform.DOMove(goal.transform.position, 2.97f); yield return new WaitForSeconds(3.0f); DOTween.To(x => table.GetComponent<CanvasGroup>().alpha = x, 1, 0, 2); } void Update() { if (Input.GetKeyDown(KeyCode.E)) { StartCoroutine(End()); } if (Input.GetKeyDown(KeyCode.F10)) { Observatory.SetActive(ArduinoController.instance.panelSetting.activeSelf); } //ArduinoController.instance.msgBox.AddNewMsg("dasdasd"); rotText.text = string.Format("{0:F2}", pentagram.transform.localEulerAngles.z); if (Input.GetKey(KeyCode.J)) pentagram.transform.rotation *= Quaternion.Euler(0, 0, 0.5f); if (Input.GetKey(KeyCode.K)) pentagram.transform.rotation *= Quaternion.Euler(0, 0, -0.5f); if (Input.GetKey(KeyCode.R)) pentagram.SetActive(true); if (!roll) { // 激活 if (ArduinoController.command == "Active" || Input.GetKey(KeyCode.L)) laserPoint++; if (laserPoint > 30 && laserPoint<10000) { if (startTime == 0) { startTime = Time.time; ArduinoController.arduinoSerialPort.Write("A"); ArduinoController.instance.msgBox.AddNewMsg("雷射陣開啟"); } if (Time.time - startTime > 7.0f) { roll = true; startTime = Time.time; ArduinoController.arduinoSerialPort.Write("S"); ArduinoController.instance.msgBox.AddNewMsg("遊戲開始"); pentagram.SetActive(true); laserPoint += 100000; } } } else { star.rotation = Quaternion.Euler(0, 0, Time.time * 60 * 1); // 結束 if (roundTableKnight[0] == "Arthur" && roundTableKnight[1] == "Lancelot" && roundTableKnight[3] == "Galahad" && roundTableKnight[4] == "Tristan") { ArduinoController.arduinoSerialPort.WriteLine("E"); ArduinoController.instance.msgBox.AddNewMsg("遊戲結束"); Debug.Log("END"); float endTime = Time.time - startTime; if (endTime < PlayerPrefs.GetFloat("recordTime")) PlayerPrefs.SetFloat("recordTime", endTime); roll = false; StartCoroutine(End()); } /* 觸發旋轉 */ if (Input.GetKey(KeyCode.Keypad1) || ArduinoController.command == "ARTHUR") roundTable[0].rotation *= Quaternion.Euler(0, 0, -37 * Time.deltaTime); if (Input.GetKey(KeyCode.Keypad2) || ArduinoController.command == "LANCELOT") roundTable[1].rotation *= Quaternion.Euler(0, 0, 37 * Time.deltaTime); if (Input.GetKey(KeyCode.Keypad3) || ArduinoController.command == "ECTOR") roundTable[2].rotation *= Quaternion.Euler(0, 0, -37 * Time.deltaTime); if (Input.GetKey(KeyCode.Keypad4) || ArduinoController.command == "GALAHAD") roundTable[3].rotation *= Quaternion.Euler(0, 0, -37 * Time.deltaTime); if (Input.GetKey(KeyCode.Keypad5) || ArduinoController.command == "TRISTAN") roundTable[4].rotation *= Quaternion.Euler(0, 0, 37 * Time.deltaTime); /* 觸發移動 */ if (ready) { if (Input.GetKey(KeyCode.Keypad1) && Input.GetKey(KeyCode.Keypad2) || ArduinoController.command == "1") { if (roundTableKnight[0] == "Arthur" && roundTableKnight[1] == "") StartCoroutine(MoveKnight(roundTableKnight[0], 0, 1)); else if (roundTableKnight[0] == "" && roundTableKnight[1] == "Arthur") StartCoroutine(MoveKnight(roundTableKnight[1], 1, 0)); } else if (Input.GetKey(KeyCode.Keypad2) && Input.GetKey(KeyCode.Keypad3) || ArduinoController.command == "2") { if (roundTableKnight[1] != "" && roundTableKnight[2] == "") { if (roundTableKnight[1] == "Arthur" || roundTableKnight[1] == "Tristan" || roundTableKnight[1] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[1], 1, 2)); } else if (roundTableKnight[1] == "" && roundTableKnight[2] != "") { if (roundTableKnight[2] == "Arthur" || roundTableKnight[2] == "Tristan" || roundTableKnight[2] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[2], 2, 1)); } } else if (Input.GetKey(KeyCode.Keypad3) && Input.GetKey(KeyCode.Keypad4) || ArduinoController.command == "3") { if (roundTableKnight[2] != "" && roundTableKnight[3] == "") { if (roundTableKnight[2] == "Arthur" || roundTableKnight[2] == "Tristan" || roundTableKnight[2] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[2], 2, 3)); } else if (roundTableKnight[2] == "" && roundTableKnight[3] != "") { if (roundTableKnight[3] == "Arthur" || roundTableKnight[3] == "Tristan" || roundTableKnight[3] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[3], 3, 2)); } } else if (Input.GetKey(KeyCode.Keypad4) && Input.GetKey(KeyCode.Keypad5) || ArduinoController.command == "4") { if (roundTableKnight[3] != "" && roundTableKnight[4] == "") { if (roundTableKnight[3] == "Arthur" || roundTableKnight[3] == "Tristan" || roundTableKnight[3] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[3], 3, 4)); } else if (roundTableKnight[3] == "" && roundTableKnight[4] != "") { if (roundTableKnight[4] == "Arthur" || roundTableKnight[4] == "Tristan" || roundTableKnight[4] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[4], 4, 3)); } } else if (Input.GetKey(KeyCode.Keypad5) && Input.GetKey(KeyCode.Keypad1) || ArduinoController.command == "5") { if (roundTableKnight[4] == "Arthur" && roundTableKnight[0] == "") StartCoroutine(MoveKnight(roundTableKnight[4], 4, 0)); else if (roundTableKnight[4] == "" && roundTableKnight[0] == "Arthur") StartCoroutine(MoveKnight(roundTableKnight[0], 0, 4)); } else if (Input.GetKey(KeyCode.Keypad1) && Input.GetKey(KeyCode.Keypad3) || ArduinoController.command == "6") { if (roundTableKnight[0] == "Arthur" && roundTableKnight[2] == "") StartCoroutine(MoveKnight(roundTableKnight[0], 0, 2)); else if (roundTableKnight[0] == "" && roundTableKnight[2] == "Arthur") StartCoroutine(MoveKnight(roundTableKnight[2], 2, 0)); } else if (Input.GetKey(KeyCode.Keypad3) && Input.GetKey(KeyCode.Keypad5) || ArduinoController.command == "7") { if (roundTableKnight[2] != "" && roundTableKnight[4] == "") { if (roundTableKnight[2] == "Arthur" || roundTableKnight[2] == "Galahad" || roundTableKnight[2] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[2], 2, 4)); } else if (roundTableKnight[2] == "" && roundTableKnight[4] != "") { if (roundTableKnight[4] == "Arthur" || roundTableKnight[4] == "Galahad" || roundTableKnight[4] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[4], 4, 2)); } } else if (Input.GetKey(KeyCode.Keypad5) && Input.GetKey(KeyCode.Keypad2) || ArduinoController.command == "8") { if (roundTableKnight[4] != "" && roundTableKnight[1] == "") { if (roundTableKnight[4] == "Arthur" || roundTableKnight[4] == "Galahad" || roundTableKnight[4] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[4], 4, 1)); } else if (roundTableKnight[4] == "" && roundTableKnight[1] != "") { if (roundTableKnight[1] == "Arthur" || roundTableKnight[1] == "Galahad" || roundTableKnight[1] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[1], 1, 4)); } } else if (Input.GetKey(KeyCode.Keypad2) && Input.GetKey(KeyCode.Keypad4) || ArduinoController.command == "9") { if (roundTableKnight[1] != "" && roundTableKnight[3] == "") { if (roundTableKnight[1] == "Arthur" || roundTableKnight[1] == "Galahad" || roundTableKnight[1] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[1], 1, 3)); } else if (roundTableKnight[1] == "" && roundTableKnight[3] != "") { if (roundTableKnight[3] == "Arthur" || roundTableKnight[3] == "Galahad" || roundTableKnight[3] == "Lancelot") StartCoroutine(MoveKnight(roundTableKnight[3], 3, 1)); } } else if (Input.GetKey(KeyCode.Keypad4) && Input.GetKey(KeyCode.Keypad1) || ArduinoController.command == "10") { if (roundTableKnight[3] == "Arthur" && roundTableKnight[0] == "") StartCoroutine(MoveKnight(roundTableKnight[3], 3, 0)); else if (roundTableKnight[3] == "" && roundTableKnight[0] == "Arthur") StartCoroutine(MoveKnight(roundTableKnight[0], 0, 3)); } } } } IEnumerator MoveKnight(string knight, int from, int to) { ready = false; roll = false; if (knight == "Tristan") { roundTableTristana[from].SetActive(false); roundTableKnight[from] = ""; star.DOKill(); star.position = starNode[from].position; star.rotation = starNode[from].rotation; star.DOScale(0, 0.73f).SetEase(Ease.InExpo); star.DOMove(starNode[to].position, 0.73f).SetEase(Ease.InQuad); yield return new WaitForSeconds(0.73f); roundTableTristana[to].SetActive(true); roundTableKnight[to] = "Tristan"; } else if (knight == "Galahad") { roundTableGalahad[from].SetActive(false); roundTableKnight[from] = ""; star.DOKill(); star.position = starNode[from].position; star.rotation = starNode[from].rotation; star.DOScale(0, 0.73f).SetEase(Ease.InExpo); star.DOMove(starNode[to].position, 0.73f).SetEase(Ease.InQuad); yield return new WaitForSeconds(0.73f); roundTableGalahad[to].SetActive(true); roundTableKnight[to] = "Galahad"; } else if (knight == "Arthur") { roundTableArthur[from].SetActive(false); roundTableKnight[from] = ""; if (to == 0) roundTableThrone.SetActive(false); star.DOKill(); star.position = starNode[from].position; star.rotation = starNode[from].rotation; star.DOScale(0, 0.73f).SetEase(Ease.InExpo); star.DOMove(starNode[to].position, 0.73f).SetEase(Ease.InQuad); yield return new WaitForSeconds(0.73f); if (from == 0) roundTableThrone.SetActive(true); roundTableArthur[to].SetActive(true); roundTableKnight[to] = "Arthur"; } else if (knight == "Lancelot") { roundTableLancelot[from].SetActive(false); roundTableKnight[from] = ""; star.DOKill(); star.position = starNode[from].position; star.rotation = starNode[from].rotation; star.DOScale(0, 0.73f).SetEase(Ease.InExpo); star.DOMove(starNode[to].position, 0.73f).SetEase(Ease.InQuad); yield return new WaitForSeconds(0.73f); roundTableLancelot[to].SetActive(true); roundTableKnight[to] = "Lancelot"; } StartCoroutine(Buffer()); } IEnumerator Buffer() { star.localScale = Vector3.zero; star.position = starNode[5].position; roll = true; star.DOScale(1, 1.0f); yield return new WaitForSeconds(1.0f); ready = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JDWinService.Model { //物料基础信息修改-工程部 public class JD_IcItemPrjBGApply_Log { /// <summary> /// /// </summary> public int ItemID { get; set; } /// <summary> /// /// </summary> public string Requester { get; set; } /// <summary> /// /// </summary> public DateTime RequestDate { get; set; } /// <summary> /// /// </summary> public int TaskID { get; set; } /// <summary> /// /// </summary> public string SNumber { get; set; } /// <summary> /// /// </summary> public int FItemID { get; set; } /// <summary> /// /// </summary> public string FNumber { get; set; } /// <summary> /// /// </summary> public string FName { get; set; } /// <summary> /// /// </summary> public string FFullName { get; set; } /// <summary> /// /// </summary> public string FNameNew { get; set; } /// <summary> /// /// </summary> public string FModel { get; set; } /// <summary> /// /// </summary> public string FModelNew { get; set; } /// <summary> /// /// </summary> public decimal FNetWeight { get; set; } /// <summary> /// /// </summary> public decimal FNetWeightNew { get; set; } /// <summary> /// /// </summary> public decimal FGrossWeight { get; set; } /// <summary> /// /// </summary> public decimal FGrossWeightNew { get; set; } /// <summary> /// /// </summary> public double FPPQ { get; set; } /// <summary> /// /// </summary> public double FPPQNew { get; set; } /// <summary> /// /// </summary> public string Remarks { get; set; } /// <summary> /// /// </summary> public DateTime UpdateTime { get; set; } /// <summary> /// /// </summary> public int IsUpdate { get; set; } } }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WeSplit { /// <summary> /// Interaction logic for UpdateTrips.xaml /// </summary> public partial class UpdateTrips : UserControl { public Trips _data; BindingList<Trips> _list; string nameTrip; public UpdateTrips(Trips t) { InitializeComponent(); _data = t; nameTrip = _data.Name; } ObservableCollection<string> Members = new ObservableCollection<string>(); ObservableCollection<string> Expenses = new ObservableCollection<string>(); List<string> arr = new List<string>() { "Members", "Expenses", "Routes", "Images", "Leader" }; private void imgCancel_MouseUp(object sender, MouseButtonEventArgs e) { USUpdateTrips.Children.Clear(); USUpdateTrips.Children.Add(new TripsDetail(_data)); } private void Copy(string sourceDir, string targetDir) { Directory.CreateDirectory(targetDir); foreach (var file in Directory.GetFiles(sourceDir)) File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file))); foreach (var directory in Directory.GetDirectories(sourceDir)) Copy(directory, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(directory))); } private void imgSave_MouseUp(object sender, MouseButtonEventArgs e) { if (tripName.Text.Trim() != "" && imgTrip.ImageSource != null && Introduce.Text.Trim() != "") { MessageBoxResult result = MessageBox.Show("Do you want to save", "", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { // Sửa dữ liệu file AllTrips var folder = AppDomain.CurrentDomain.BaseDirectory; var database = $"{folder}AllTrips.txt"; var avatar = $"{folder}Images"; var lines = File.ReadAllLines(database); string imgtripr = System.IO.Path.GetFileName(imgTrip.ImageSource.ToString()); if (_data.Picture != imgtripr) { var imgAv = ((BitmapImage)imgTrip.ImageSource).UriSource.ToString().Remove(0, 8); var appStartPath111 = String.Format(avatar + "\\" + imgtripr); string imgAvName = System.IO.Path.GetFileName(imgAv.ToString()); string appStartPath111Name = System.IO.Path.GetFileName(appStartPath111.ToString()); if (!File.Exists(avatar + "\\" + imgAvName)) { File.Copy(imgAv, appStartPath111, true); } } for (int i = 1; i < lines.Length; i += 6) { string linesMembers = ""; if (lines[i] == nameTrip) { lines[i] = tripName.Text; lines[i + 1] = Introduce.Text; lines[i + 2] = imgtripr; for (int j = 0; j <= Members.Count() - 1; j += 2) { if (j + 1 == Members.Count() - 1) { linesMembers = String.Concat(linesMembers, Members[j]); } else linesMembers = String.Concat(linesMembers, Members[j] + " - "); } lines[i + 4] = linesMembers; lines[i + 5] = Routes.Text.ToString().Replace("\r", "").Replace("\n", "\\\\"); } } File.WriteAllLines(database, lines); String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); appStartPath = appStartPath + $"\\ListTrips"; string path2 = System.IO.Path.Combine(appStartPath, nameTrip); for (int i = 0; i < 4; i++) { string pathDetail = path2 + $"\\{arr[i]}.txt"; switch (i + 1) { case 1: using (StreamWriter sw1 = File.CreateText(pathDetail)) { foreach (string content in Members) { sw1.WriteLine(content); } } break; case 2: using (StreamWriter sw1 = File.CreateText(pathDetail)) { foreach (string content in Expenses) { sw1.WriteLine(content); } } break; case 3: using (StreamWriter sw1 = File.CreateText(pathDetail)) { sw1.Write(Routes.Text); } break; case 4: using (StreamWriter sw1 = File.CreateText(pathDetail)) { foreach (string nameImg in _list[0].Images) { string name = System.IO.Path.GetFileName(nameImg); if (File.Exists(path2 + "\\" + name)) { sw1.WriteLine(name); } else { sw1.WriteLine(name); appStartPath = String.Format(path2 + "\\" + name); File.Copy(nameImg, appStartPath, true); } } //Xoa anh foreach (string item in imagesExsis) { try { File.Delete(item); } catch (IOException) { //file is currently locked } } } break; } } //Đổi tên folder var source = $"{folder}" + $"ListTrips\\{nameTrip}\\"; var des = $"{folder}" + $"ListTrips\\{tripName.Text}\\"; if (nameTrip == tripName.Text) { _data.Introduce = Introduce.Text; _data.Picture = imgtripr; USUpdateTrips.Children.Clear(); USUpdateTrips.Children.Add(new TripsDetail(_data)); } else { _data.Name = tripName.Text; _data.Introduce = Introduce.Text; _data.Picture = imgtripr; if (!Directory.Exists(des)) { Directory.CreateDirectory(des); Copy(source, des); //Directory.Move(source, des); } USUpdateTrips.Children.Clear(); USUpdateTrips.Children.Add(new TripsDetail(_data)); } } } else MessageBox.Show("You did not enter the name, introduce or image trip!!!"); } private void ChooseImg_Click(object sender, RoutedEventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Multiselect = false; open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg; *.png; *.jpeg; *.gif; *.bmp"; bool? result = open.ShowDialog(); if (result == true) { var img = open.FileNames; ImageSource imgsource = new BitmapImage(new Uri(img[0].ToString())); imgTrip.ImageSource = imgsource; } } private void imgAddPays_MouseUp(object sender, MouseButtonEventArgs e) { if (Expenditures.Text.Trim() == "") { MessageBox.Show("Chưa nhập tên khoản chi!!", "", MessageBoxButton.OK); } else { string expenses = Expenditures.Text; string prices = Prices.Text; ulong pr; if (prices == "") { pr = 0; } else pr = Convert.ToUInt64(prices); string ko = expenses + " : " + pr.ToString() + " VNĐ"; _list[0].Expenses.Add(ko); listExpenditures.ItemsSource = _list; Expenses.Add(expenses); Expenses.Add(pr.ToString()); Expenditures.Text = ""; Prices.Text = ""; } } private void imgAddMember_MouseUp(object sender, MouseButtonEventArgs e) { if (memberName.Text.Trim() != "") { string mem = memberName.Text; // advance payment string money = moneyPaid.Text; ulong pr; if (money == "") { pr = 0; } else pr = Convert.ToUInt64(money); string koko = mem + ": " + pr.ToString() + " VNĐ"; _list[0].Members.Add(koko); listMembers.ItemsSource = _list; Members.Add(mem.Trim()); Members.Add(pr.ToString()); memberName.Text = ""; moneyPaid.Text = ""; } else MessageBox.Show("Chưa nhập tên thành viên!!", "", MessageBoxButton.OK); } private void Prices_TextChanged(object sender, TextChangedEventArgs e) { Prices.Text = Regex.Replace(Prices.Text, "[^0-9]+", ""); } private void moneyPaid_TextChanged(object sender, TextChangedEventArgs e) { moneyPaid.Text = Regex.Replace(moneyPaid.Text, "[^0-9]+", ""); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { //this.DataContext = _data; tripName.Text = _data.Name; Introduce.Text = _data.Introduce; Trips ttt = new Trips() { Picture = _data.Picture }; _list = new BindingList<Trips>(); listExpenditures.ItemsSource = _list; listMembers.ItemsSource = _list; listImagessss.ItemsSource = _list; String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); appStartPath = appStartPath + $"\\ListTrips\\{nameTrip}\\"; var t = new Trips() { Expenses = new ObservableCollection<string>(), Routes = new ObservableCollection<string>(), Members = new ObservableCollection<string>(), Images = new BindingList<string>() }; //Images string fileImages = appStartPath + $"Images.txt"; var readImages = File.ReadAllLines(fileImages); for (int i = 0; i < readImages.Length; i++) { t.Images.Add(appStartPath + readImages[i]); listImages.Add(readImages[i]); } //Routes string fileRoutes = appStartPath + $"Routes.txt"; var readRoutes = File.ReadAllText(fileRoutes); Routes.Text = readRoutes; //Members string fileMembers = appStartPath + $"Members.txt"; var readMembers = File.ReadAllLines(fileMembers); t.Leader = readMembers[0].ToString() + " (Leader): " + readMembers[1].ToString() + " VNĐ"; t.Members.Add(t.Leader); Members.Add(readMembers[0]); Members.Add(readMembers[1]); for (int i = 2; i < readMembers.Length; i = i + 2) { string mem = readMembers[i] + ": " + readMembers[i + 1] + " VNĐ"; t.Members.Add(mem); Members.Add(readMembers[i]); Members.Add(readMembers[i + 1]); } //Expenses string fileExpenses = appStartPath + $"Expenses.txt"; var readExpenses = File.ReadAllLines(fileExpenses); for (int i = 0; i < readExpenses.Length; i = i + 2) { string ex = readExpenses[i] + " : " + readExpenses[i + 1] + " VNĐ"; t.Expenses.Add(ex); Expenses.Add(readExpenses[i]); Expenses.Add(readExpenses[i + 1]); } _list.Add(t); } ObservableCollection<string> listImages = new ObservableCollection<string>(); private void Imgsss_Click(object sender, RoutedEventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Multiselect = true; open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg; *.png; *.jpeg; *.gif; *.bmp"; bool? result = open.ShowDialog(); if (result == true) { foreach (string item in open.FileNames) { listImages.Add(item); _list[0].Images.Add(item); } } } private void buttonEditExpenses_Click(object sender, RoutedEventArgs e) { } private void buttonDeleteExpenses_Click(object sender, RoutedEventArgs e) { var item = (sender as FrameworkElement).DataContext; int index = _list[0].Expenses.IndexOf(item.ToString()); _list[0].Expenses.RemoveAt(index); Expenses.RemoveAt(index * 2 + 1); Expenses.RemoveAt(index * 2); } private void buttonEditMembers_Click(object sender, RoutedEventArgs e) { } private void buttonDeleteMembers_Click(object sender, RoutedEventArgs e) { var item = (sender as FrameworkElement).DataContext; int index = _list[0].Members.IndexOf(item.ToString()); if (index == 0) { MessageBox.Show("Đây là leader, không thể xoá!!!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else { _list[0].Members.RemoveAt(index); Members.RemoveAt(index * 2 + 1); Members.RemoveAt(index * 2); } } List<string> imagesExsis = new List<string>(); private void buttonDeleteImages_Click(object sender, RoutedEventArgs e) { var item = (sender as FrameworkElement).DataContext; imagesExsis.Add(item.ToString()); int index = _list[0].Images.IndexOf(item.ToString()); _list[0].Images.RemoveAt(index); listImages.RemoveAt(index); } } }
using System; namespace _2._Weaponsmith { class Program { static void Main(string[] args) { string[] weaponName = Console.ReadLine() .Split("|", StringSplitOptions.RemoveEmptyEntries); string command = Console.ReadLine(); while (command != "Done") { string[] commandSeparated = command .Split(); if (commandSeparated[0] == "Move") { int indexOfCommand = int.Parse(commandSeparated[2]); if (commandSeparated[1] == "Left" && indexOfCommand - 1 >= 0 && indexOfCommand < weaponName.Length) { string temp = weaponName[indexOfCommand]; weaponName[indexOfCommand] = weaponName[indexOfCommand - 1]; weaponName[indexOfCommand - 1] = temp; } else if (commandSeparated[1] == "Right" && indexOfCommand >= 0 && indexOfCommand + 1 < weaponName.Length) { string temp = weaponName[indexOfCommand]; weaponName[indexOfCommand] = weaponName[indexOfCommand + 1]; weaponName[indexOfCommand + 1] = temp; } } else if (commandSeparated[0] == "Check") { if (commandSeparated[1] == "Even") { for (int i = 0; i < weaponName.Length; i += 2) { Console.Write(weaponName[i] + " "); } Console.WriteLine(); } else if (commandSeparated[1] == "Odd") { for (int i = 1; i < weaponName.Length; i += 2) { Console.Write(weaponName[i] + " "); } Console.WriteLine(); } } command = Console.ReadLine(); } Console.WriteLine($"You crafted {String.Join("", weaponName)}!"); } } }
using System; using System.Collections.Generic; using System.Linq; using BashSoft.Exceptions; using BashSoft.Static_data; namespace BashSoft.Models { public class Student { private string _userName; private readonly Dictionary<string, Course> _enrroledCourses; private readonly Dictionary<string, double> _marksByCourseName; public Student(string userName) { this.UserName = userName; this._enrroledCourses = new Dictionary<string, Course>(); this._marksByCourseName = new Dictionary<string, double>(); } public string UserName { get { return this._userName; } private set { if (string.IsNullOrEmpty(value)) { throw new InvalidStringException(); } this._userName = value; } } public IReadOnlyDictionary<string, Course> EnrroledCourses { get { return this._enrroledCourses; } } public IReadOnlyDictionary<string, double> MarksByCourseName { get { return this._marksByCourseName; } } public void EnrollInCourse(Course course) { if (this._enrroledCourses.ContainsKey(course.Name)) { throw new DuplicateEntryInStructureException(this.UserName, course.Name); } this._enrroledCourses.Add(course.Name, course); } public void SetMarksInCourse(string courseName, params int[] scores) { if (!this._enrroledCourses.ContainsKey(courseName)) { throw new Exception(ExceptionMessages.NotEnrolledInCourse); } if (scores.Length > Course.NumberOfTaskOnExam) { throw new Exception(ExceptionMessages.InvalidNumberOfScores); } this._marksByCourseName.Add(courseName, Calculate(scores)); } private double Calculate(int[] scores) { double percentageOfSolvedExam = scores.Sum() / (double)(Course.NumberOfTaskOnExam * Course.MaxScoreOnExamTask); double mark = percentageOfSolvedExam * 4 + 2; return mark; } } }
using AutoMapper; namespace Uintra.Infrastructure.Extensions { public static class AutoMapperExtensions { public static TDestination Map<TDestination>(this object obj) => Mapper.Map<TDestination>(obj); public static TDestination Map<TSource, TDestination>(this TSource src, TDestination destination) => Mapper.Map<TSource, TDestination>(src, destination); } }
using LHRLA.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LHRLA.LHRLA.DAL.DataAccessClasses { public class SectionDataAccess { #region Insert public bool AddSection(tbl_Section row) { try { using (var db = new vt_LHRLAEntities()) { db.tbl_Section.Add(row); db.SaveChanges(); } return true; } catch (Exception ex) { return false; } } #endregion #region Update public bool UpdateSection(tbl_Section row) { try { using (var db = new vt_LHRLAEntities()) { tbl_Section val = new tbl_Section(); val = db.tbl_Section.Where(a => a.ID == row.ID).FirstOrDefault(); val.Title = row.Title; val.Is_Active = row.Is_Active; db.SaveChanges(); } return true; } catch (Exception ex) { return false; } } #endregion #region Delete #endregion #region Select public List<tbl_Section> GetAllSections() { try { List<tbl_Section> lst = new List<tbl_Section>(); using (var db = new vt_LHRLAEntities()) { lst = db.tbl_Section.ToList(); } return lst; } catch (Exception ex) { throw ex; } } public List<tbl_Section> GetAllActiveSections() { try { List<tbl_Section> lst = new List<tbl_Section>(); using (var db = new vt_LHRLAEntities()) { lst = db.tbl_Section.ToList().Where(a => a.Is_Active == true).ToList(); } return lst; } catch (Exception ex) { throw ex; } } public List<tbl_Section> GetSectionbyID(int ID) { try { List<tbl_Section> lst = new List<tbl_Section>(); using (var db = new vt_LHRLAEntities()) { lst = db.tbl_Section.Where(e => e.ID == ID).ToList(); } return lst; } catch (Exception ex) { throw ex; } } public string GetSectionName(int SectionID) { try { string SectionName=""; using (var db = new vt_LHRLAEntities()) { tbl_Section sec = new tbl_Section(); sec = db.tbl_Section.Where(e => e.ID == SectionID).FirstOrDefault(); if (sec != null) { SectionName = sec.Title; } } return SectionName; } catch (Exception ex) { throw ex; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraMovement : MonoBehaviour { public bool Stay; public bool SmoothFollow; Vector3 currentVelocity; [Range(0,1)] public float smoothTime; // Lower value = Faster result; public float maxSpeed = 10; float deltaTime; public Vector3 Offset; private Transform ToFollowObject; public Transform toFollow { get { return ToFollowObject; } set { ToFollowObject = value; } } public void UpdatePosition() { Vector3 currentPos = transform.position; Vector3 targetPos = ToFollowObject.transform.position; deltaTime = Time.deltaTime; if (Stay == false) { if (ToFollowObject.position != transform.position) { if (SmoothFollow == true) { //SmoothFollow: transform.position = Vector3.SmoothDamp(currentPos, targetPos + new Vector3(0, 0, -10) + Offset, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } else { //Basic - instantaneo transform.position = ToFollowObject.position + new Vector3(0, 0, -10); } } } if(smoothTime != 0) { SmoothFollow = true; } else { SmoothFollow = false; } } public void VerifyLimits(Rect rect) { float deltaX = DeltaPosition().x; float deltaY = DeltaPosition().y; if (deltaX > rect.width || deltaX < -rect.width || deltaY > rect.height || deltaY < -rect.height) { //smoothTime = 0.1f; //maxSpeed = 50; } else { //smoothTime = 0.5f; //maxSpeed = 10; } } private Vector2 DeltaPosition() { float objPosX = ToFollowObject.transform.position.x; float objPosY = ToFollowObject.transform.position.y; float camPosX = transform.position.x; float camPosY = transform.position.y; float deltaX = objPosX - camPosX; float deltaY = objPosY - camPosY; return new Vector2(deltaX, deltaY); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Dominio.Validations.Results; using Dominio.Validations; namespace Dominio { public class Modelo<T> where T : Modelo<T>, new() { protected ModelValidator<T> _validator; protected virtual ModelValidator<T> Validator { get; set; } public virtual int Id { get; protected set; } public override bool Equals(object obj) { Type objType = obj.GetType(); Type thisType = this.GetType(); if (obj == null) return false; Modelo<T> specificObject = obj as Modelo<T>; if (specificObject == null) return false; if (Id != specificObject.Id) return false; return true; } public override int GetHashCode() { return Id.GetHashCode() ^ 5; } public virtual ValidationResult Validate() { return (Validator != null) ? Validator.Validate((T)this) : new ValidationResult(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Step_140b { class Program { static void Main(string[] args) { List<Employee> listEmployees = new List<Employee>() { new Employee{FirstName = "Joe", LastName = "Smith", EmpID = 1}, new Employee{FirstName = "Abbey", LastName = "Cleman", EmpID =2}, new Employee{FirstName = "Lane", LastName = "Vehrenkamp", EmpID = 3}, new Employee{FirstName = "Tyler", LastName = "Vehrenkamp", EmpID = 4}, new Employee{FirstName = "Rosemary", LastName = "Vehrenkamp", EmpID = 5}, new Employee{FirstName = "Paul", LastName = "Vehrenkamp", EmpID = 6}, new Employee{FirstName = "John", LastName = "Dietz", EmpID = 7}, new Employee{FirstName = "Casi", LastName = "Johnson", EmpID = 8}, new Employee{FirstName = "Kyle", LastName = "Vehrenkamp", EmpID = 9}, new Employee{FirstName = "Joe", LastName = "Jones", EmpID = 10}, }; //foreach loop //foreach(Employee Jemployee in listEmployees) //{ // if(Jemployee.FirstName == "Joe") // { // Console.WriteLine("Name : " + Jemployee.FirstName + " " + Jemployee.LastName + " \t\tEmployee ID: " + Jemployee.EmpID); // } //} //Lambda expression //foreach (Employee Jemployee in listEmployees.FindAll(e => (e.FirstName == "Joe")).ToList()) //{ // Console.WriteLine("Name : " + Jemployee.FirstName + " " + Jemployee.LastName + " \t\tEmployee ID: " + Jemployee.EmpID); //} foreach (Employee Jemployee in listEmployees.FindAll(e => (e.EmpID >= 5)).ToList()) { Console.WriteLine("Name : " + Jemployee.FirstName + " " + Jemployee.LastName + " \t\tEmployee ID: " + Jemployee.EmpID); } Console.ReadLine(); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class DocuWriterComplex : MonoBehaviour { public WindowBase window; int challengeLvl; //stuff to activate/deactivate public GameObject[] challenge1; public GameObject[] challenge2; public GameObject[] challenge3; //other challenge 2 stuff public Text saveAsText; public GameObject saveAsPopup, saveAsError; //other challenge 3 stuff public GameObject DocuWizard; // Use this for initialization void Awake() { DocuWizard = GameObject.Find("Doc Help Wizard"); } void Start () { challengeLvl = window.challenge; if (challengeLvl > 1) { for (int i = 0; i < challenge1.Length; i++) { challenge1[i].SetActive(false); } switch (challengeLvl) { case 2: for (int i = 0; i < challenge2.Length; i++) { challenge2[i].SetActive(true); } break; case 3: for (int i = 0; i < challenge3.Length; i++) { challenge3[i].SetActive(true); } break; } } } public void SaveAs() { string[] tmpString = saveAsText.text.Split('.'); if (tmpString[tmpString.Length - 1] == "txt" || tmpString[tmpString.Length - 1] == "Txt" || tmpString[tmpString.Length - 1] == "TXT") { window.popupActive = false; string titleString = ""; for (int i = 0; i < tmpString.Length - 1; i++) { titleString += tmpString[i]; } window.SaveFile(); window.SetTitle(titleString); HideSaveAs(); for (int i = 0; i < challenge2.Length; i++) { challenge2[i].SetActive(false); } for (int i = 0; i < challenge1.Length; i++) { challenge1[i].SetActive(true); } } else { saveAsError.SetActive(true); //error sound GameManager.gameManager.PlaySound(0); EmoteTriggers.sammich.EmoteSammich("OhNo"); } } public void SaveWizard() { GameManager.gameManager.PlaySound(3); EmoteTriggers.sammich.EmoteSammich("GrabGlasses"); transform.SetAsLastSibling(); DocuWizard.SetActive(true); DocuWizard.GetComponent<HelpWizard>().window = gameObject.GetComponent<WindowBase>(); window.HideAllDropDowns(); window.popupActive = true; } public void HideError() { saveAsError.SetActive(false); } public void HideSaveAs() { window.popupActive = false; saveAsPopup.SetActive(false); } public void ShowSaveAs() { window.popupActive = true; window.HideAllDropDowns(); saveAsPopup.SetActive(true); transform.SetAsLastSibling(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BookARoom.Model.BLL { public class CustomerTypeClass { //Fält för hantering och validering av bokningsuppgifter [Required(ErrorMessage = "Krav! Ange kundtypsid")] [Range(0, Int32.MaxValue, ErrorMessage = "Kundtypsid måste vara ett positivt heltal.")] public int CustomerTypeId { get; set; } [Required(ErrorMessage = "Krav! Ange kundtypsbeskrivning")] [StringLength(10, ErrorMessage = "Beskrivningen kan bestå av max 10 tecken.")] public string CustomerType { get; set; } } }
using MyBlog.WebApi.Framework.DTOs; namespace MyBlog.WebApi.DTOs.Blogs { public class BlogCommentForUpdateDto : BaseRequestDto { public string CommentText { get; set; } } }
using NfePlusAlpha.Domain.Entities; using NfePlusAlpha.Infra.Data.Context; using NfePlusAlpha.Infra.Data.Retorno; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NfePlusAlpha.Infra.Data.Classes { public class Csosn : IDisposable { NfePlusAlphaContext Db; protected DbSet<tbCsosn> DbSet; public Csosn() { this.Db = new NfePlusAlphaContext(); this.DbSet = this.Db.Set<tbCsosn>(); } public NfePlusAlphaRetorno ObterListaCsosn() { NfePlusAlphaRetorno objRetorno = new NfePlusAlphaRetorno(); try { List<tbCsosn> arrCsosn = this.DbSet .AsNoTracking() .OrderBy(c => c.cso_numero) .ToList(); objRetorno.blnTemErro = false; objRetorno.objRetorno = arrCsosn; } catch (Exception ex) { objRetorno.blnTemErro = true; objRetorno.strMensagemErro = ex.Message; } return objRetorno; } public void Dispose() { this.Db.Dispose(); this.DbSet = null; this.Db = null; GC.SuppressFinalize(this); } } }