text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CardLib { public class Deck { private Random random = new Random(); private List<Card> cards = new List<Card>(); private Card trumphCard; public List<Card> Cards { get { return cards; } set { cards = value; } } public int NumberOfCards { //Shortcut property to get the number of cards in the deck get { return cards.Count; } } public Card GetRandomCard() { // Returns a random card from the deck. // Removes the card from the deck. if (cards.Count == 0) return null; //throw new Exception("EmptyDeckException"); int cardId = -1; do { cardId = random.Next(0, NumberOfCards - 1); Card card1 = cards[cardId]; if (trumphCard == null) break; if (card1 != trumphCard) break; } while (true); Card card = cards[cardId]; this.Cards.Remove(card); return card; } public Card GetTopCard() { // Gets the first (top) card in the deck // Essentially pulling from the top of the deck. // Removes the card from the deck if (cards.Count == 0) throw new Exception("EmptyDeckException"); Card card = cards[0]; this.Cards.Remove(card); return card; } public Card GetBottomCard() { // Gets the last (bottom) card in the deck // Essentially pulling from the bottom of the deck. // Removes the card from the deck if (cards.Count == 0) throw new Exception("EmptyDeckException"); Card card = cards[cards.Count - 1]; this.Cards.Remove(card); return card; } public Card GetCard(int index) { // Gets a card in the deck // Removes the card from the deck if (cards.Count == 0) throw new Exception("EmptyDeckException"); if (cards.Count <= index) throw new Exception("InvalidCardException"); Card card = cards[index]; this.Cards.Remove(card); return card; } public Card GetCard(CardValues cardValue, CardSuits suit) { foreach (Card c in this.Cards) { if (c.Value == cardValue && c.Suit == suit) { this.Cards.Remove(c); return c; } } return null; } public bool Exists(Card aCard) { foreach (Card c in cards) { if (aCard.TextValue == c.TextValue) { return true; } } return false; } public void setTrumphCard(Card trumphCard) { this.trumphCard = trumphCard; } } }
using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Text; namespace ZiZhuJY.Helpers { public static class ExpandoHelper { public static string ToHtmlUnorderedList(this ExpandoObject o, bool format = false, bool lineBreak = false, int level = 0, char tab = ' ', int tabWidth = 4) { var sb = new StringBuilder(); if (format && lineBreak) { sb.AppendLine(); } AppendToStringBuilder(format, level, tab, tabWidth, sb, "<div>{0}</div>", o); if (format) sb.AppendLine(); AppendToStringBuilder(format, level, tab, tabWidth, sb, "<ul>"); foreach (var kvp in o) { if(format) sb.AppendLine(); AppendToStringBuilder(format, level+1, tab, tabWidth, sb, "<li><strong>{0}</strong> = {1}", kvp.Key, kvp.Value); var value = kvp.Value as ExpandoObject; var hasChildren = false; if (value != null) { hasChildren = true; if (format) { sb.AppendLine(); } sb.Append(value.ToHtmlUnorderedList(format, false, level + 2, tab, tabWidth)); //AppendToStringBuilder(format, level + 2, tab, tabWidth, sb, // value.ToHtmlUnorderedList(format, false, level + 2, tab, tabWidth)); } else { var list = kvp.Value as IEnumerable<ExpandoObject>; if (list != null) { hasChildren = true; if (format) sb.AppendLine(); sb.Append(list.ToHtmlOrderedList(format, false, level + 2, tab, tabWidth)); } } AppendToStringBuilder(hasChildren, level+1, tab, tabWidth, sb, "</li>"); } if (format) sb.AppendLine(); AppendToStringBuilder(format, level, tab, tabWidth, sb, "</ul>"); if (format) sb.AppendLine(); if (format && lineBreak) sb.AppendLine(); return sb.ToString(); } public static string ToHtmlOrderedList(this IEnumerable<ExpandoObject> list, bool format = false, bool lineBreak = false, int level = 0, char tab = ' ', int tabWidth = 4) { var sb = new StringBuilder(); if (format && lineBreak) { sb.AppendLine(); } AppendToStringBuilder(format, level, tab, tabWidth, sb, "<div>{0}</div>", list); if (format) sb.AppendLine(); AppendToStringBuilder(format, level, tab, tabWidth, sb, "<ol>"); foreach (var element in list) { if (format) sb.AppendLine(); AppendToStringBuilder(format, level + 1, tab, tabWidth, sb, "<li>"); sb.AppendLine(); sb.Append(element.ToHtmlUnorderedList(format, false, level + 2, tab, tabWidth)); AppendToStringBuilder(format, level + 1, tab, tabWidth, sb, "</li>"); } if (format) sb.AppendLine(); AppendToStringBuilder(format, level, tab, tabWidth, sb, "</ol>"); if (format) sb.AppendLine(); if (format && lineBreak) sb.AppendLine(); return sb.ToString(); } private static void AppendToStringBuilder(bool format, int level, char tab, int tabWidth, StringBuilder sb, string template, params object[] args) { if (format) { sb.AppendFormatToLevel(template, level, tab, tabWidth, args); } else { sb.AppendFormat(template, args); } } } }
using UnityEngine; using System.Collections; public class LampGenerator : GridGenerator<Lamp> { // Use this for initialization void Start () { generate(); } // Update is called once per frame void Update () { } }
using System.Linq; using System.Threading.Tasks; using FastSQL.Core; using FastSQL.Sync.Core.Enums; using FastSQL.Sync.Core.Repositories; namespace FastSQL.Sync.Core.Reporters { public class ErrorReporter : BaseReporter { public ErrorReporter(ErrorReporterOptionManager optionManager) : base(optionManager) { } public override string Id => "hV1AesVeTCwzthQReQGh"; public override string Name => "Error Reporter"; public override async Task Queue() { await Task.Run(() => { using (var messageRepository = ResolverFactory.Resolve<MessageRepository>()) { var limit = 500; var offset = 0; while (true) { var messages = messageRepository.GetUnqueuedMessages(ReporterModel, MessageType.Error, limit, offset); if (messages == null || messages.Count() <= 0) { break; } foreach (var message in messages) { messageRepository.LinkToReporter(message.Id.ToString(), ReporterModel); } offset += limit; } } }); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace CaptiveApiTest { class Program { static void Main(string[] args) { string clientId = "P8PBbxmm?Dy8#gXUz$NF6k5F6Pk#!Du$"; string clientKey = "q4XBBhA$8VTgBh74n@dqzA?Vk4qBT*!b"; string httpMethode = "GET"; string host = @"http://thonhotels.admin.captive.net"; string date = ""+DateTime.Now.ToUniversalTime()+ " GMT"; string path = "api/v1"; string getVariables = ""; string messageString = httpMethode + "/"+host+"/"+date+"/"+path+"/"+getVariables+"/"; byte[] messageByte = Encoding.ASCII.GetBytes(messageString); byte[] keyByte = Encoding.ASCII.GetBytes(clientKey); HMACSHA256 key = new HMACSHA256(keyByte); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host+"/"+path); request.Headers.Add("Authorization", "Credentials="+clientId+",Signature="+key.ComputeHash(messageByte)); request.Method = "GET"; WebResponse response = request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); Console.WriteLine(((HttpWebResponse)response).StatusCode); Stream data = response.GetResponseStream(); Console.WriteLine(data); Console.WriteLine(date); Console.ReadLine(); } } }
namespace Plus.Communication.Packets.Outgoing.Pets { internal class PetBreedingComposer : MessageComposer { public PetBreedingComposer() : base(ServerPacketHeader.PetBreedingMessageComposer) { } public override void Compose(ServerPacket packet) { packet.WriteInteger(219005779); //An Id? { //Pet 1. packet.WriteInteger(2169464); //Pet Id packet.WriteString("Tes"); packet.WriteInteger(69); //Level packet.WriteString("1 22 F2E5CC"); //Breed/figure? packet.WriteString("Sledmore"); //Owner //Pet 2. packet.WriteInteger(2169465); packet.WriteString("Testy"); packet.WriteInteger(1337); packet.WriteString("1 0 D4D4D4"); packet.WriteString("Sledmore"); packet.WriteInteger(4); //Count { packet.WriteInteger(1); packet.WriteInteger(3); packet.WriteInteger(18); packet.WriteInteger(19); packet.WriteInteger(20); packet.WriteInteger(3); packet.WriteInteger(6); packet.WriteInteger(12); packet.WriteInteger(13); packet.WriteInteger(14); packet.WriteInteger(15); packet.WriteInteger(16); packet.WriteInteger(17); packet.WriteInteger(4); packet.WriteInteger(5); packet.WriteInteger(7); packet.WriteInteger(8); packet.WriteInteger(9); packet.WriteInteger(10); packet.WriteInteger(11); packet.WriteInteger(92); packet.WriteInteger(6); packet.WriteInteger(1); packet.WriteInteger(2); packet.WriteInteger(3); packet.WriteInteger(4); packet.WriteInteger(5); packet.WriteInteger(6); } packet.WriteInteger(28); } } } }
using System; using System.Collections.Generic; //Write a program that sorts an array of strings using the quick sort algorithm class Program { static void Main() { List<string> myList = new List<string>(new string[] { "f", "a", "b", "h", "m", "q", "c", "i", "l" }); myList = QuickSort(myList, 0, myList.Count - 1); foreach (var item in myList) { Console.Write(item + " "); } } private static List<string> QuickSort(List<string> list, int left, int right) { int i = left; int j = right; string leftString = list[i]; string rightString = list[j]; string middle = list[(left + right) / 2]; //double pivotValue = ((left + right) / 2); //string middle = a[Convert.ToInt32(pivotValue)]; string temp = null; while (i <= j) { while (list[i].CompareTo(middle) < 0) { i++; leftString = list[i]; } while (list[j].CompareTo(middle) > 0) { j--; rightString = list[j]; } if (i <= j) { temp = list[i]; list[i++] = list[j]; list[j--] = temp; } } if (left < j) { QuickSort(list, left, j); } if (i < right) { QuickSort(list, i, right); } return list; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Drawing; using System.Windows.Media; namespace Aspit.StudentReg.Entities { public class Student : User { /// <summary> /// The student's unilogin /// </summary> string uniLogin; /// <summary> /// The student's current <see cref="AttendanceRegistration"/> /// </summary> AttendanceRegistration attendanceRegistrations; SolidColorBrush color; string icon; /// <summary> /// Intializes a new <see cref="Student"/> using the given parameters /// </summary> /// <param name="id">The student's id</param> /// <param name="name">The student's name</param> /// <param name="uniLogin">The student's unilogin</param> /// <param name="attendanceRegistrations">The student's current <see cref="AttendanceRegistration"/></param> public Student(int id, string name, string uniLogin, AttendanceRegistration attendanceRegistrations = default):base(id,name) { Id = id; Name = name; UniLogin = uniLogin; AttendanceRegistrations = attendanceRegistrations; colorSet(); iconset(); } /// <summary> /// Gets or sets the student's unilogin /// </summary> public string UniLogin { get { return uniLogin; } set { ValidateUniLogin(value); value = value.Trim(); uniLogin = value; } } /// <summary> /// Gets or sets the student's current <see cref="AttendanceRegistration"/> /// </summary> public AttendanceRegistration AttendanceRegistrations { get { return attendanceRegistrations; } set { attendanceRegistrations = value; } } public SolidColorBrush Color { get { return this.color; } set { this.color = value; } } public string Icon { get { return this.icon; } set { this.icon = value; } } /// <summary> /// Tests if a uniLogin string is valid /// </summary> /// <param name="uniLogin">The uniLogin in test</param> /// <returns>true if the uniLogin is valid, throws error if false</returns> public static bool ValidateUniLogin(string uniLogin) { if(string.IsNullOrWhiteSpace(uniLogin)) { throw new ArgumentNullException("Unilogin cannot be null"); } //Trim whitespace uniLogin = uniLogin.Trim(); //Check if value is a correct unilogin format Regex reg = new Regex(@"^[a-x]{4}[a-x0-9]{4}$"); if (!reg.IsMatch(uniLogin)) { throw new ArgumentException("Unilogin is invalid"); } return true; } public override string ToString() { if (AttendanceRegistrations.IsDefault()) { return "✗ - " + Name; } else { return "✓ - " + Name; } } public void colorSet() { if (!AttendanceRegistrations.IsDefault()) { Color = new BrushConverter().ConvertFromString("#27ae60") as SolidColorBrush; } else { Color = new BrushConverter().ConvertFromString("#c0392b") as SolidColorBrush; } } public void iconset() { if (!AttendanceRegistrations.IsDefault()) { Icon = "✓"; } else { Icon = "✗"; } } /// <summary> /// Compares two students and outputs a number based on which student should show first in a list /// </summary> /// <param name="student1">The first student</param> /// <param name="student2">The second student</param> /// <returns>returns 1 if the first student should be highest, -1 if lowest and 0 if it doesnt matter</returns> public static int Compare(Student student1, Student student2) { if(student1.AttendanceRegistrations.IsDefault() && !student2.AttendanceRegistrations.IsDefault()) { return 1; } else if(!student1.AttendanceRegistrations.IsDefault() && student2.AttendanceRegistrations.IsDefault()) { return -1; } else { return string.Compare(student1.ToString(), student2.ToString()); } } } }
using BPiaoBao.AppServices.Contracts.SystemSetting; using BPiaoBao.AppServices.DataContracts.SystemSetting; using BPiaoBao.Client.UIExt; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Threading; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using System.Windows.Input; namespace BPiaoBao.Client.SystemSetting.ViewModel { public class BuyDetailViewModel : ViewModelBase { private bool _isWait; public bool IsWait { get { return _isWait; } set { if (_isWait == value) return; _isWait = value; RaisePropertyChanged("IsWait"); } } private DateTime? _startTime; public DateTime? StartTime { get { return _startTime; } set { if (_startTime == value) return; _startTime = value; RaisePropertyChanged("StartTime"); } } private DateTime? _endTime; public DateTime? EndTime { get { return _endTime; } set { if (_endTime == value) return; _endTime = value; RaisePropertyChanged("EndTime"); } } private int _currentPageIndex; public int CurrentPageIndex { get { return _currentPageIndex; } set { if (_currentPageIndex == value) return; _currentPageIndex = value; RaisePropertyChanged("CurrentPageIndex"); } } private int _totalCount; public int TotalCount { get { return _totalCount; } set { if (_totalCount == value) return; _totalCount = value; RaisePropertyChanged("TotalCount"); } } public int PageSize { get; private set; } public ObservableCollection<BuyDetailDto> List { get; private set; } public ICommand PagerCommand { get; private set; } private static BuyDetailViewModel _instace; private BuyDetailViewModel() { List = new ObservableCollection<BuyDetailDto>(); CurrentPageIndex = 1; PageSize = 15; EndTime = DateTime.Now; StartTime = EndTime.Value.AddMonths(-1); if (IsInDesignMode) return; PagerCommand = new RelayCommand(Init); } public static BuyDetailViewModel CreateInstance() { if (_instace == null) _instace = new BuyDetailViewModel(); _instace.Init(); return _instace; } private bool _result = true; internal void Init() { if (!_result) return; _result = false; IsWait = true; List.Clear(); Action action = () => CommunicateManager.Invoke<IBusinessmanService>(p => { var endTime = EndTime.HasValue ? EndTime.Value.AddDays(1) : EndTime; var dataPack = p.BuyRecordByPage(CurrentPageIndex, PageSize, StartTime, endTime, OutTradeNo); TotalCount = dataPack.TotalCount; dataPack.List.ForEach(x => DispatcherHelper.UIDispatcher.Invoke(new Action<BuyDetailDto>(List.Add), x)); }, UIManager.ShowErr); Task.Factory.StartNew(action).ContinueWith(param => { Action setIsWait = () => { IsWait = false; _result = true; }; DispatcherHelper.UIDispatcher.Invoke(setIsWait); }); } private string _outTradeNo = ""; public string OutTradeNo { get { return _outTradeNo.Trim(); } set { if (_outTradeNo == value) return; _outTradeNo = value; RaisePropertyChanged(OutTradeNo); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// 스태이지 내에서 아이템 생성하고, 플레이어에게 지급하는 로직 처리. /// </summary> public class ItemController : Singleton<ItemController> { [SerializeField] float basicCreateInterval; [SerializeField] float nextStepElapsedTime; [SerializeField] float nextStepDecreaseInterval; private ItemFactory itemFactory; private Dictionary<ItemType, List<IItem>> items = new Dictionary<ItemType, List<IItem>>(); private void Awake() { StageController.Instance.OnStageStart += OnStageStart; itemFactory = gameObject.AddComponent<ItemFactory>(); } private void OnStageStart() { StartCoroutine(ItemCreateProcess()); } private IEnumerator ItemCreateProcess() { // 스테이지 플레이한 시간 지날 수록 아이템이 나올 확률이 올라가도록. float elapsedTime = 0f; while(StageController.Instance.IsStageProcessing == true) { float nextCreateInterval = basicCreateInterval; if(elapsedTime > nextStepElapsedTime) nextCreateInterval = nextStepDecreaseInterval; yield return new WaitForSeconds(nextCreateInterval); ItemType newItemType = GetNewItemType(); IItem newItem = itemFactory.CreateItem(newItemType); newItem.OnDestroy += OnItemDestroy; if(items.ContainsKey(newItemType) == false) { items.Add(newItemType, new List<IItem>()); } items[newItemType].Add(newItem); SfxManager.Instance.Play(SfxType.Item_Create); elapsedTime += Time.deltaTime; } } private void OnItemDestroy(IItem item) { items[item.ItemType].Remove(item); item.OnDestroy -= OnItemDestroy; } private ItemType GetNewItemType() { int randomValue = Random.Range(0, 10); if(randomValue >= 0 && randomValue < 4) { return ItemType.HpPotion; } else if(randomValue >= 4 && randomValue < 8) { return ItemType.MpPotion; } else { return ItemType.ExtremePotion; } } public IItem[] GetItems(ItemType itemType) { if(items.ContainsKey(itemType) == false) { return null; } return items[itemType].ToArray(); } public IItem GetNearestItem(ItemType itemType, Vector3 position) { if(items.ContainsKey(itemType) == false) { return null; } var sortedItems = items[itemType].OrderBy((item) => (item.transform.position - position).magnitude); if (sortedItems.Count() > 0) { return sortedItems.First(); } return null; } }
using System; namespace State { class Program { static void Main(string[] args) { Vehiculo v = new Vehiculo(20); v.Acelerar(); v.Contacto(); v.Acelerar(); v.Acelerar(); v.Acelerar(); v.Frenar(); v.Frenar(); v.Frenar(); v.Frenar(); } } }
 namespace MFW.LALLib { public enum TranscoderResolutionEnum { PLCM_MFW_RESOLUTION_CIF4, // 704x576 PLCM_MFW_RESOLUTION_VGA, // 640x480 PLCM_MFW_RESOLUTION_VGA_DIV4, // 320x240 PLCM_MFW_RESOLUTION_SVGA, // 800x600 PLCM_MFW_RESOLUTION_HHRVGA, // 320x480 PLCM_MFW_RESOLUTION_1280x720P, // 1280x720 PLCM_MFW_RESOLUTION_480x360, NULL } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Http; using System.Web.Http; using Newtonsoft.Json; namespace PlayTennis.WebApi.Controllers { public class TestController : ApiController { // GET: api/Test public IEnumerable<string> Get() { throw new ArgumentNullException(); return new string[] { "value1", "value2" }; } // GET: api/Test/5 public string Get(int id) { return "value"; } // POST: api/Test public void Post([FromBody]string value) { MemoryStream stream = new MemoryStream(); Request.Content.CopyToAsync(stream); StreamReader reader = new StreamReader(stream); string text = reader.ReadToEnd(); } // PUT: api/Test/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Test/5 public void Delete(int id) { } } }
using AutoMapper; using Ninject.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webcorp.Controller; using Webcorp.Model; namespace Webcorp.Business { public class BusinessIoc : NinjectModule { public override void Load() { Bind(typeof(IBusinessHelper<>)).To(typeof(BusinessHelper<>)).InSingletonScope(); Bind(typeof(IArticleBusinessHelper<>)).To(typeof(ArticleBusinessHelper<>)).InSingletonScope(); Bind(typeof(ICommandeBusinessHelper<>)).To(typeof(CommandeBusinessHelper<>)).InSingletonScope(); Bind(typeof(IUtilisateurBusinessHelper<>)).To(typeof(UtilisateurBusinessHelper<>)).InSingletonScope(); Bind(typeof(IParametreBusinessHelper<>)).To(typeof(ParametreBusinessHelper<>)).InSingletonScope(); Bind(typeof(IAuthenticationService)).To(typeof(AuthenticationService)).InSingletonScope(); Bind(typeof(IBusinessController<>)).To(typeof(ArticleBusinessController<>)).InSingletonScope().Named("ArticleController"); Bind(typeof(IBusinessController<>)).To(typeof(CommandeBusinessController<>)).InSingletonScope().Named("CommandeController"); Bind(typeof(IBusinessController<>)).To(typeof(UtilisateurBusinessController<>)).InSingletonScope().Named("UtilisateurController"); Bind(typeof(IBusinessController<>)).To(typeof(ParametreBusinessController<>)).InSingletonScope().Named("ParametreController"); Mapper.CreateMap<Article, ArticleCommande>(); ArticleBusinessExtensions.Kernel = Kernel; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities; using ShareTradingModel; namespace Entities.Test { public class AccountTest:EntityTest<Account> { } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace d07_iterator { class MonitorCatalog : IEnumerable<Monitor> { Dictionary<string, Monitor> ds = new Dictionary<string, Monitor>(); public void add() { Monitor m = new Monitor(); Console.Write("nhap id: "); m.pID = Console.ReadLine().Trim(); if (ds.ContainsKey(m.pID)) { Console.WriteLine("Ma so da ton tai. Tu choi them moi !"); return; } Console.Write("nhap ten san pham: "); m.pName = Console.ReadLine().Trim(); Console.Write("nhap don gia: "); m.pPrice = int.Parse(Console.ReadLine().Trim()); Console.Write("nhap trang thai ton kho (yes/no): "); m.pStock = Console.ReadLine().Trim().ToLower().Equals("yes"); //luu vo ds ds.Add(m.pID, m); Console.WriteLine("Da them san pham moi thanh cong"); } public IEnumerator<Monitor> GetEnumerator() { if (ds.Count == 0) { Console.WriteLine(" >> HT chua co du lieu !!!"); yield break; } foreach (var item in ds.Values) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { if (ds.Count == 0) { Console.WriteLine(" >> HT chua co du lieu !!!"); yield break; } foreach (var item in ds.Values) { yield return item; } } } }
using System; using System.Collections.Generic; using CommonCore.State; namespace CommonCore.Dialogue { internal class DialogueScene { public Dictionary<string, Frame> Frames { get; private set; } public string Default; public string Music; public DialogueScene(Dictionary<string, Frame> frames, string defaultFrame, string music) { Frames = frames; Default = defaultFrame; Music = music; } } internal enum FrameType { ChoiceFrame, TextFrame } internal class ChoiceNode { public readonly string Text; public readonly string Next; public readonly MicroscriptNode[] NextMicroscript; public readonly ConditionNode[] NextConditional; public readonly Conditional ShowCondition; public readonly Conditional HideCondition; public ChoiceNode(string next, string text) { Text = text; Next = next; } public ChoiceNode(string next, string text, Conditional showCondition, Conditional hideCondition, MicroscriptNode[] nextMicroscript, ConditionNode[] nextConditional) : this(next, text) { ShowCondition = showCondition; HideCondition = hideCondition; NextMicroscript = nextMicroscript; NextConditional = nextConditional; } public string EvaluateConditional() { for (int i = NextConditional.Length - 1; i >= 0; i--) { var nc = NextConditional[i]; bool ncResult = false; try { ncResult = nc.Evaluate(); } catch(Exception e) { UnityEngine.Debug.LogException(e); } if (ncResult) return nc.Next; } return null; } public void EvaluateMicroscript() { if (NextMicroscript == null || NextMicroscript.Length < 1) return; foreach (MicroscriptNode mn in NextMicroscript) { try { mn.Execute(); } catch(Exception e) { UnityEngine.Debug.LogException(e); } } } } internal class Frame { public readonly string Background; public readonly string Image; public readonly string Next; public readonly string Music; public readonly string NameText; public readonly string Text; public readonly ConditionNode[] NextConditional; public readonly MicroscriptNode[] NextMicroscript; public Frame(string background, string image, string next, string music, string nameText, string text, ConditionNode[] nextConditional, MicroscriptNode[] nextMicroscript) { Background = background; Image = image; Next = next; Music = music; NameText = nameText; Text = text; if (nextConditional != null && nextConditional.Length > 0) NextConditional = (ConditionNode[])nextConditional.Clone(); if (nextMicroscript != null && nextMicroscript.Length > 0) NextMicroscript = (MicroscriptNode[])nextMicroscript.Clone(); } public string EvaluateConditional() { for(int i = NextConditional.Length-1; i >= 0; i--) { var nc = NextConditional[i]; if (nc.Evaluate()) return nc.Next; } return null; } public void EvaluateMicroscript() { if (NextMicroscript == null || NextMicroscript.Length < 1) return; foreach (MicroscriptNode mn in NextMicroscript) { mn.Execute(); } } } internal class TextFrame : Frame { public TextFrame(string background, string image, string next, string music, string nameText, string text, ConditionNode[] nextConditional, MicroscriptNode[] nextMicroscript) : base(background, image, next, music, nameText, text, nextConditional, nextMicroscript) { } } internal class ChoiceFrame: Frame { public readonly ChoiceNode[] Choices; public ChoiceFrame(string background, string image, string next, string music, string nameText, string text, ChoiceNode[] choices, ConditionNode[] nextConditional, MicroscriptNode[] nextMicroscript) : base(background, image, next, music, nameText, text, nextConditional, nextMicroscript) { Choices = (ChoiceNode[])choices.Clone(); } } internal class ConditionNode { public readonly string Next; public readonly Conditional[] Conditions; public ConditionNode(string next, Conditional[] conditions) { Next = next; Conditions = conditions; } public bool Evaluate() { if (Conditions == null || Conditions.Length == 0) //odd, but in the spec return true; foreach(Conditional c in Conditions) { if (!c.Evaluate()) return false; } return true; } } }
namespace SGDE.Domain.Helpers { #region Using using System.Globalization; #endregion public static class ExtensionsMethods { public static string ToFormatSpain(this double value) { var result = value.ToString("N", CultureInfo.CreateSpecificCulture("es-ES")); //var find = result.IndexOf(",00"); //if (find > 0) // result = result.Substring(0, find); return result; } } }
using SFML.Graphics; using SFML.Window; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LD30 { class MessageLog : GameObject { public Vector2f Position; public int MessageLimit = 6; public float MessageLifetime = 5f; public int MessageSize = 32; List<LogMessage> Messages = new List<LogMessage>(); public MessageLog(Game game) : base(game) { } public void AddMessage(string msg) { Messages.Insert(0, new LogMessage() { Message = msg }); while (Messages.Count > MessageLimit) Messages.RemoveAt(Messages.Count - 1); } public override void Update(float dt) { foreach (var msg in Messages) { msg.TimeAlive += dt; } Messages.RemoveAll(msg => msg.TimeAlive > MessageLifetime); } public override void Draw(SFML.Graphics.RenderTarget target) { var view = new View(target.GetView()); target.SetView(target.DefaultView); float nextY = Position.Y; foreach (var msg in Messages) { var text = new Text(msg.Message, ResourceManager.GetResource<Font>("font"), (uint)MessageSize); text.Color = new Color(0, 0, 0, (byte)(int)((MessageLifetime - msg.TimeAlive) / MessageLifetime * 255f)); text.Position = new Vector2f(Position.X, nextY); nextY += MessageSize; target.Draw(text); } target.SetView(view); } } class LogMessage { public string Message = ""; public float TimeAlive = 0f; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OefeningGarage { class Wagenpark { public List<Garage> GraragesInParken { get; set; } public Wagenpark() { GraragesInParken = new List<Garage>(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Models { public class tb_pertypeinfo { public tb_pertypeinfo() { } #region Model private int _id; private string _name; private string _info; /// <summary> /// /// </summary> public int id { set { _id = value; } get { return _id; } } /// <summary> /// /// </summary> public string name { set { _name = value; } get { return _name; } } /// <summary> /// /// </summary> public string info { set { _info = value; } get { return _info; } } #endregion Model } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Assets.Scripts.Core.Scenarios { public class MoveToTransformItem : IScenarioItem { private readonly Transform follower; private readonly Transform target; private readonly float speed; private readonly float sqrMinRange; private bool isPaused; private IEnumerator followCoroutine; public bool IsComplete { get; private set; } public MoveToTransformItem(Transform follower, Transform target, float speed, float minRange = 1f) { this.follower = follower; this.target = target; this.speed = speed; sqrMinRange = minRange * minRange; } public IScenarioItem Play() { isPaused = false; if (followCoroutine == null) { followCoroutine = getFollowCoroutine(); ScenariosRoot.Instance.StartCoroutine(followCoroutine); } return this; } public void Stop() { if (followCoroutine != null && ScenariosRoot.Instance != null) { ScenariosRoot.Instance.StopCoroutine(followCoroutine); followCoroutine = null; } IsComplete = true; } public void Pause() { isPaused = true; } private IEnumerator getFollowCoroutine() { while (true) { Vector3 delta = target.position - follower.position; if (delta.sqrMagnitude < sqrMinRange) { Stop(); yield break; } follower.rotation = Quaternion.LookRotation(-delta); follower.position += delta.normalized * speed; do { yield return null; } while (isPaused); } } } }
using ETravel.Coffee.DataAccess.Entities; using FluentNHibernate.Mapping; namespace ETravel.Coffee.DataAccess.Mappings { public sealed class OrderItemMap : ClassMap<OrderItem> { public OrderItemMap() { Table("OrderItems"); Id(x => x.Id).GeneratedBy.Assigned(); Map(x => x.OrderId); Map(x => x.Quantity); Map(x => x.Owner); Map(x => x.Description); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; #endregion namespace DotNetNuke.Collections.Internal { internal class MonitorLock : IDisposable, ISharedCollectionLock { private ExclusiveLockStrategy _lockStrategy; public MonitorLock(ExclusiveLockStrategy lockStrategy) { _lockStrategy = lockStrategy; } #region "IDisposable Support" // To detect redundant calls private bool _isDisposed; public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _lockStrategy.Exit(); _lockStrategy = null; } } _isDisposed = true; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SFP.SIT.SERV.Model.ADM { public class SIT_ADM_AREA { public DateTime arafeccreacion { set; get; } public int araclave { set; get; } public SIT_ADM_AREA () {} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Animatiocontrol : MonoBehaviour { public Animator playeranime; private Movecontrol move; private Collision coll; [HideInInspector] public SpriteRenderer sr; // Start is called before the first frame update void Start() { playeranime = GetComponent<Animator>(); coll = GetComponentInParent<Collision>(); move = GetComponentInParent<Movecontrol>(); sr = GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update() { playeranime.SetBool("onGround", coll.onGround); playeranime.SetBool("onWall", coll.onWall); playeranime.SetBool("onRightWall", coll.onRightWall); playeranime.SetBool("wallGrab", move.iswallGrab); playeranime.SetBool("wallSlide", move.iswallSlide); playeranime.SetBool("isdash", move.isdash); playeranime.SetBool("ishurt", move.ishurt); playeranime.SetBool("isattack", move.isattack); playeranime.SetBool("isairjump", move.isairjump); } // public void SetHorizontalMovement(float x, float y, float yVel) // { // playeranime.SetFloat("Horizontal", x); // playeranime.SetFloat("Vertical", y); // playeranime.SetFloat("VerticalVelocity", yVel); // } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IncreaseMana : MonoBehaviour { private void OnTriggerEnter2D(Collider2D c) { if (c.GetComponent<Collider2D>().tag == "Player") { GameObject.Find("Player").GetComponent<advSpecial>().SpecialBarMax = GameObject.Find("Player").GetComponent<advSpecial>().SpecialBarMax + 50; GameObject.Find("Player").GetComponent<advSpecial>().SpecialBarCurr = GameObject.Find("Player").GetComponent<advSpecial>().SpecialBarMax; Destroy(gameObject); } } }
using System; using BasketTest.Discounts.Items; using FluentAssertions; using NUnit.Framework; namespace BasketTest.Discount.UnitTests.Items { [TestFixture] public class OfferVoucherSpec { [Test] public void GiftVoucher_RejectsNegativeValue() { Action act = () => { var sut = new OfferVoucher(-10m, 10m); }; act.ShouldThrow<ArgumentException>() .WithMessage("Value cannot be negative."); } [Test] public void GiftVoucher_AcceptsPositiveValue() { Action act = () => { var sut = new OfferVoucher(10m, 10m); }; act.ShouldNotThrow(); } [Test] public void GiftVoucher_RejectsNegativeThreshold() { Action act = () => { var sut = new OfferVoucher(10m, -10m); }; act.ShouldThrow<ArgumentException>() .WithMessage("Value cannot be negative."); } } }
using System; using System.Collections.Concurrent; using System.Web.Mvc; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Persistence; using Umbraco.Core.Composing; using Umbraco.Core.Services; using Umbraco.Web.Security; using Umbraco.Web.WebApi; namespace Umbraco.Web.Mvc { /// <summary> /// Provides a base class for plugin controllers. /// </summary> public abstract class PluginController : Controller, IDiscoverable { private static readonly ConcurrentDictionary<Type, PluginControllerMetadata> MetadataStorage = new ConcurrentDictionary<Type, PluginControllerMetadata>(); private UmbracoHelper _umbracoHelper; // for debugging purposes internal Guid InstanceId { get; } = Guid.NewGuid(); // note // properties marked as [Inject] below will be property-injected (vs constructor-injected) in // order to keep the constuctor as light as possible, so that ppl implementing eg a SurfaceController // don't need to implement complex constructors + need to refactor them each time we change ours. // this means that these properties have a setter. // what can go wrong? /// <summary> /// Gets or sets the Umbraco context. /// </summary> public virtual UmbracoContext UmbracoContext { get; } /// <summary> /// Gets or sets the database context. /// </summary> public IUmbracoDatabaseFactory DatabaseFactory { get; } /// <summary> /// Gets or sets the services context. /// </summary> public ServiceContext Services { get; } /// <summary> /// Gets or sets the application cache. /// </summary> public CacheHelper ApplicationCache { get; } /// <summary> /// Gets or sets the logger. /// </summary> public ILogger Logger { get; } /// <summary> /// Gets or sets the profiling logger. /// </summary> public IProfilingLogger ProfilingLogger { get; } /// <summary> /// Gets the membership helper. /// </summary> public MembershipHelper Members => Umbraco.MembershipHelper; /// <summary> /// Gets the Umbraco helper. /// </summary> public UmbracoHelper Umbraco { get { return _umbracoHelper ?? (_umbracoHelper = new UmbracoHelper(UmbracoContext, Services)); } internal set // tests { _umbracoHelper = value; } } /// <summary> /// Gets metadata for this instance. /// </summary> internal PluginControllerMetadata Metadata => GetMetadata(GetType()); protected PluginController() : this( Current.Factory.GetInstance<UmbracoContext>(), Current.Factory.GetInstance<IUmbracoDatabaseFactory>(), Current.Factory.GetInstance<ServiceContext>(), Current.Factory.GetInstance<CacheHelper>(), Current.Factory.GetInstance<ILogger>(), Current.Factory.GetInstance<IProfilingLogger>() ) { } protected PluginController(UmbracoContext umbracoContext, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, CacheHelper applicationCache, ILogger logger, IProfilingLogger profilingLogger) { UmbracoContext = umbracoContext; DatabaseFactory = databaseFactory; Services = services; ApplicationCache = applicationCache; Logger = logger; ProfilingLogger = profilingLogger; } /// <summary> /// Gets metadata for a controller type. /// </summary> /// <param name="controllerType">The controller type.</param> /// <returns>Metadata for the controller type.</returns> internal static PluginControllerMetadata GetMetadata(Type controllerType) { return MetadataStorage.GetOrAdd(controllerType, type => { // plugin controller? back-office controller? var pluginAttribute = controllerType.GetCustomAttribute<PluginControllerAttribute>(false); var backOfficeAttribute = controllerType.GetCustomAttribute<IsBackOfficeAttribute>(true); return new PluginControllerMetadata { AreaName = pluginAttribute?.AreaName, ControllerName = ControllerExtensions.GetControllerName(controllerType), ControllerNamespace = controllerType.Namespace, ControllerType = controllerType, IsBackOffice = backOfficeAttribute != null }; }); } } }
namespace CarDealer.Services.Implementations { using Data; using Data.Models; using Interfaces; using Models.Cars; using Models.Parts; using System.Collections.Generic; using System.Linq; public class CarServices : ICarServices { private readonly CarDealerDbContext db; public CarServices(CarDealerDbContext db) { this.db = db; } public ICollection<CarByMake> AllCarsByMakes(string makes) => this.db .Cars .Where(c => c.Make.ToLower() == makes.ToLower()) .OrderBy(c => c.Model) .ThenByDescending(c => c.TravelledDistance) .Select(c => new CarByMake { Make = c.Make, Model = c.Model, TravelledDistance = c.TravelledDistance }) .ToList(); public ICollection<CarByMake> All() => this.db .Cars .OrderByDescending(c => c.Id) .ThenByDescending(c => c.TravelledDistance) .Select(c => new CarByMake { Make = c.Make, Model = c.Model, TravelledDistance = c.TravelledDistance }) .ToList(); public void Create(string make, string model, long travelledDistance, IEnumerable<int> parts) { var existingsPartIds = this.db .Parts .Where(p => parts.Contains(p.Id)) .Select(p => p.Id) .ToList(); var car = new Car { Make = make, Model = model, TravelledDistance = travelledDistance }; foreach (var partId in existingsPartIds) { car.Parts.Add(new PartCar { PartId = partId }); } this.db.Cars.Add(car); this.db.SaveChanges(); } public ICollection<CarsWithPartsModel> CarWithParts(string id) => this.db .Cars .Where(c => c.Id.ToString() == id) .Select(c => new CarsWithPartsModel { Make = c.Make, Model = c.Model, Parts = c.Parts.Select(p => new PartsModel { Name = p.Part.Name, Price = p.Part.Price }) }) .ToList(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Pitstop { public class PlayerControllerIso : MonoBehaviour { //GameManager SceneLoader sceneLoader; InputManager inputManager; [Header("My components")] [SerializeField] Rigidbody2D myRb = default; [SerializeField] Animator myAnim = default; [SerializeField] Image dashCdFb = default; //Public public bool canMove = true; [HideInInspector] public bool playerCanMove = true; public bool isMoving = false; public bool isBeingRepulsed = false; public float moveSpeed = 3; public float isometricRatio = 2; //Serializable public static int savingPointIndex = 0; [SerializeField] Transform[] sceneStartingPoint; [SerializeField] float dashSpeed = 5; [SerializeField] float dashLength = 0.5f; [SerializeField] float dashCooldown = 1; [SerializeField] float repulseTime = 0.5f; [SerializeField] float repulseTimeDash = 0.5f; //Private [HideInInspector] public Vector2 moveInput; [HideInInspector] public Vector2 lastMove; float initialMoveSpeed = 0; float dashRate = 0; /* [Header("Sounds")] [SerializeField] AudioSource footStepSound = default; */ void Start() { sceneLoader = GameManager.Instance.sceneLoader; inputManager = GameManager.Instance.inputManager; Spawn(); } private void Spawn() { //Orientations of the player on start of scene switch (sceneLoader.activeScene) { case "1_TEMPLE": lastMove = new Vector2(1, 0); break; case "2_FOREST": lastMove = new Vector2(1, 1); break; case "2_MINIBOSS": lastMove = new Vector2(1, 0); break; case "3_VILLAGE": lastMove = new Vector2(0, 1); break; case "4_DUNGEON": lastMove = new Vector2(1, 1); break; } myAnim.SetFloat("LastMoveX", lastMove.x); myAnim.SetFloat("LastMoveY", lastMove.y); transform.position = sceneStartingPoint[savingPointIndex].position; canMove = true; } void Update() { isMoving = false; //DEBUG WITH LIANA ! Debug.DrawLine(transform.position, new Vector2(transform.position.x + moveInput.x, transform.position.y + moveInput.y), Color.blue); if (Time.time < dashRate) { dashCdFb.fillAmount = (dashRate - Time.time) / dashCooldown; } else if (inputManager.dashKey) { Dash(); } else if (!isBeingRepulsed) { StopCoroutine(ComeOnAndDash()); StopCoroutine(RepulsionOnDash()); } if (!canMove) { myRb.velocity = Vector2.zero; myAnim.SetBool("IsMoving", isMoving); return; } if (playerCanMove) { moveInput = new Vector2(inputManager.horizontalInput, inputManager.verticalInput / isometricRatio).normalized; } if (moveInput != Vector2.zero) { myRb.velocity = new Vector2(moveInput.x * moveSpeed, moveInput.y * moveSpeed); isMoving = true; lastMove = moveInput; } else { myRb.velocity = Vector2.zero; } //Infos to animator myAnim.SetBool("IsMoving", isMoving); myAnim.SetFloat("LastMoveX", lastMove.x); myAnim.SetFloat("LastMoveY", lastMove.y); myAnim.SetFloat("MoveX", moveInput.x); myAnim.SetFloat("MoveY", moveInput.y); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "ObjectApple" && !isBeingRepulsed) { if (collision.gameObject.GetComponentInParent<IMP_Apple>().hasExploded) { Debug.Log("Apple touched !"); StartCoroutine(ComeOnAndFly()); } } } private void Dash() { dashRate = Time.time + dashCooldown; initialMoveSpeed = moveSpeed; moveSpeed = dashSpeed; isBeingRepulsed = true; StartCoroutine(ComeOnAndDash()); StartCoroutine(RepulsionOnDash()); } public void IncrementSavingPoint(int associatedIndex) { savingPointIndex = associatedIndex; } public void ResetSavingPoint() { savingPointIndex = 0; } IEnumerator ComeOnAndDash() { yield return new WaitForSeconds(dashLength); moveSpeed = initialMoveSpeed; } IEnumerator RepulsionOnDash() { yield return new WaitForSeconds(repulseTimeDash); isBeingRepulsed = false; } IEnumerator ComeOnAndFly() { isBeingRepulsed = true; yield return new WaitForSeconds(repulseTime); myRb.velocity = Vector2.zero; isBeingRepulsed = false; StopCoroutine(ComeOnAndFly()); } } }
using RO; using System; using System.Collections.Generic; using UnityEngine; [CustomLuaClass] public class DiskFileManager : Singleton<DiskFileManager> { private int m_ider; private string m_filesUsedRecordRootPath; private Dictionary<int, FilesUsedDetail> m_dictFilesUsedDetail; private Dictionary<int, LRUSandBox> m_dictDirectoryLRU; private List<int> m_listInitializedDirectory; public static DiskFileManager Instance { get { return Singleton<DiskFileManager>.ins; } } public DiskFileManager() { this.m_ider = this.GetIDer(); this.m_filesUsedRecordRootPath = "FilesUsedRecord"; FileDirectoryHandler.CreateDirectory(this.m_filesUsedRecordRootPath); this.m_dictFilesUsedDetail = new Dictionary<int, FilesUsedDetail>(); this.m_dictDirectoryLRU = new Dictionary<int, LRUSandBox>(); this.m_listInitializedDirectory = new List<int>(); } public void InitializeLRUDirectory(string path, int capacity, int server_time, bool parent_is_lru, bool lru_file_or_directory) { int iD = this.GetID(path); if (iD > 0) { if (this.DirectoryIsInitialized(iD)) { return; } string directoryNameFromPath = FileDirectoryHandler.GetDirectoryNameFromPath(path); LRUSandBox lRUSandBox = new LRUSandBox(capacity, lru_file_or_directory); bool flag = FileDirectoryHandler.ExistDirectory(path); if (flag) { string fileSystemUsedRecordPath = this.GetFileSystemUsedRecordPath(iD, directoryNameFromPath); bool flag2 = false; if (FileDirectoryHandler.ExistFile(fileSystemUsedRecordPath)) { FilesUsedDetail filesUsedDetail = MyXmlSerializer.Deserialize<FilesUsedDetail>(fileSystemUsedRecordPath); if (filesUsedDetail != null) { this.m_dictFilesUsedDetail.Add(iD, filesUsedDetail); filesUsedDetail.Clean(); filesUsedDetail.Sort(); FilesUsedDetail.FileUsedDetail[] details = filesUsedDetail.Details; for (int i = 0; i < details.Length; i++) { FilesUsedDetail.FileUsedDetail fileUsedDetail = details[i]; lRUSandBox.Add(fileUsedDetail.id, fileUsedDetail.path); } flag2 = true; } else { LoggerUnused.LogWarning("Files Used record deserialize from .xml fail, path is" + path); } } else { LoggerUnused.LogWarning("Files used record .xml file not exists, path is " + path); } if (!flag2) { string[] childrenPath = FileDirectoryHandler.GetChildrenPath(path); List<FilesUsedDetail.FileUsedDetail> list = new List<FilesUsedDetail.FileUsedDetail>(); for (int j = 0; j < childrenPath.Length; j++) { string path2 = childrenPath[j]; int iD2 = this.GetID(path2); DateTime used_time = (server_time >= 0) ? DiskFileManager.ToDateTime(server_time) : DateTime.get_Now(); FilesUsedDetail.FileUsedDetail fileUsedDetail2 = new FilesUsedDetail.FileUsedDetail(iD2, path2, used_time); list.Add(fileUsedDetail2); lRUSandBox.Add(iD2, path2); } FilesUsedDetail filesUsedDetail2 = new FilesUsedDetail(path, list.ToArray()); this.m_dictFilesUsedDetail.Add(iD, filesUsedDetail2); } } else { FileDirectoryHandler.CreateDirectory(path); FilesUsedDetail filesUsedDetail3 = new FilesUsedDetail(path); this.m_dictFilesUsedDetail.Add(iD, filesUsedDetail3); } this.m_dictDirectoryLRU.Add(iD, lRUSandBox); if (parent_is_lru) { this.LRUParent(path, server_time); } this.m_listInitializedDirectory.Add(iD); } } public void InitializeDirectory(string path, int server_time, bool parent_is_lru) { int iD = this.GetID(path); if (this.DirectoryIsInitialized(iD)) { return; } if (!FileDirectoryHandler.ExistDirectory(path)) { FileDirectoryHandler.CreateDirectory(path); } if (parent_is_lru) { this.LRUParent(path, server_time); } this.m_listInitializedDirectory.Add(iD); } private void SaveIDer() { PlayerPrefs.SetInt("FILE_DIRECTORY_ID", this.m_ider); } private int GetIDer() { return PlayerPrefs.GetInt("FILE_DIRECTORY_ID"); } private int GetID(string path) { if (string.IsNullOrEmpty(path)) { return 0; } int num = PlayerPrefs.GetInt(path, 0); if (num > 0) { return num; } num = ++this.m_ider; this.SaveIDer(); PlayerPrefs.SetInt(path, num); return num; } private void SaveFileSystemUsedTime() { if (this.m_dictFilesUsedDetail != null && this.m_dictFilesUsedDetail.get_Count() > 0) { using (Dictionary<int, FilesUsedDetail>.Enumerator enumerator = this.m_dictFilesUsedDetail.GetEnumerator()) { while (enumerator.MoveNext()) { KeyValuePair<int, FilesUsedDetail> current = enumerator.get_Current(); int key = current.get_Key(); FilesUsedDetail value = current.get_Value(); string path = value.Path; string directoryNameFromPath = FileDirectoryHandler.GetDirectoryNameFromPath(path); string fileSystemUsedRecordPath = this.GetFileSystemUsedRecordPath(key, directoryNameFromPath); MyXmlSerializer.Serialize<FilesUsedDetail>(value, fileSystemUsedRecordPath); } } } } private string GetFileSystemUsedRecordPath(int id, string directory_name) { return string.Concat(new object[] { this.m_filesUsedRecordRootPath, "/", id, "_", directory_name, ".xml" }); } public bool SaveFile(string path, byte[] bytes, int server_time) { bool[] array = FileDirectoryHandler.WriteFile(path, bytes); if (array != null && array.Length > 0) { bool flag = array[0]; bool flag2 = array[1]; if (flag2) { this.LRUParent(path, server_time); } return flag2; } return false; } public void SaveFile(string path, byte[] bytes, int server_time, Action<bool> on_complete) { FileDirectoryHandler.WriteFile(path, bytes, delegate(bool x, bool y) { if (y) { this.LRUParent(path, server_time); } if (on_complete != null) { on_complete.Invoke(y); } }); } public byte[] LoadFile(string path, int server_time) { byte[] array = FileDirectoryHandler.LoadFile(path); if (array != null) { this.LRUParent(path, server_time); } return array; } public void LRUParent(string path, int server_time) { string parentDirectoryPath = FileDirectoryHandler.GetParentDirectoryPath(path); if (!string.IsNullOrEmpty(parentDirectoryPath)) { int iD = this.GetID(parentDirectoryPath); if (iD > 0) { int iD2 = this.GetID(path); if (this.m_dictFilesUsedDetail.ContainsKey(iD)) { FilesUsedDetail filesUsedDetail = this.m_dictFilesUsedDetail.get_Item(iD); DateTime used_time = (server_time >= 0) ? DiskFileManager.ToDateTime(server_time) : DateTime.get_Now(); FilesUsedDetail.FileUsedDetail file_used_detail = new FilesUsedDetail.FileUsedDetail(iD2, path, used_time); if (!filesUsedDetail.ExistDetail(iD2)) { filesUsedDetail.AddDetail(file_used_detail); } else { filesUsedDetail.UpdateDetail(iD2, file_used_detail); } this.SaveFileSystemUsedTime(); } if (this.m_dictDirectoryLRU.ContainsKey(iD)) { LRUSandBox lRUSandBox = this.m_dictDirectoryLRU.get_Item(iD); if (lRUSandBox.Exist(iD2)) { lRUSandBox.MakeActive(iD2); } else { lRUSandBox.Add(iD2, path); } } } } } public static DateTime ToDateTime(int to_greenwich_seconds) { DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0); dateTime = TimeZone.get_CurrentTimeZone().ToLocalTime(dateTime); return dateTime.AddSeconds((double)to_greenwich_seconds); } private bool DirectoryIsInitialized(int id) { return this.m_listInitializedDirectory.Contains(id); } public void Reset() { if (this.m_dictDirectoryLRU != null) { this.m_dictDirectoryLRU.Clear(); } if (this.m_dictFilesUsedDetail != null) { this.m_dictFilesUsedDetail.Clear(); } if (this.m_listInitializedDirectory != null) { this.m_listInitializedDirectory.Clear(); } } }
using BookShelf.Models; using BookShelf.Models.AuthorViewModels; namespace BookShelf.Infrastructure.Factories { public class AuthorViewModelFactory { public static AuthorViewModel CreateAuthorViewModel(Author author) { return new AuthorViewModel { Id = author.Id, Name = author.Name }; } } }
using Microsoft.AspNetCore.Authorization; namespace DynamicPermission.AspNetCore.Configurations.Identity.PermissionManager { public class PermissionRequirement : IAuthorizationRequirement { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using frameWork.command.cmdInterface; namespace frameWork.command { class SuperCommand : ICommand { public virtual void excute(INotification note) { } public void notify(String typeStr, Object data = null) { BaseNotification notification = new BaseNotification(); notification.data = data; AppNotification note = new AppNotification(typeStr, notification); note.dispatch(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mojio { /// <summary> /// /// </summary> public class Address { /// <summary> /// address line 1 /// </summary> [Display(Name = "Address 1")] [Required(ErrorMessage = "Required")] public string Address1 { get; set; } /// <summary> /// address line 2 /// </summary> [Display(Name = "Address 2")] public string Address2 { get; set; } /// <summary> /// city /// </summary> [Display(Name = "City")] [Required(ErrorMessage = "Required")] public string City { get; set; } /// <summary> /// state or province /// </summary> [Display(Name = "State/Province")] [Required(ErrorMessage = "Required")] public string State { get; set; } /// <summary> /// zip or postal code /// </summary> [Display(Name = "Zip/Postal Code")] [Required(ErrorMessage = "Required")] public string Zip { get; set; } /// <summary> /// country /// </summary> [Display(Name = "Country")] [Required(ErrorMessage = "Required")] public string Country { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VictimApplication.Core.Models { public class UserListToReturnDto { public int userId { get; set; } public string UserName { get; set; } public string Password { get; set; } public string FirstName { get; set; } public string SecondName { get; set; } public string Email {get;set;} public string UserType {get;set;} public string NameToReturn { get => $"{FirstName} {SecondName}"; } public string UserTypeToReturn { get { if(UserType == "U") { return "User"; } if (UserType == "P") { return "Police"; } return "Admin"; } } } }
using System.Text; namespace ReadyGamerOne.Utility { public static class BitUtil { public static string ToString(byte[] data, int length, int start=0) { var sb=new StringBuilder(); for(var i=start;i<length;i++) { sb.Append(data[i].ToString()); } return sb.ToString(); } } }
using Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IBll { public interface IUser_CatalogBll { List<User_Catalog> GetList(Func<User_Catalog, bool> predicate); int Create(User_Catalog model); int Edit(User_Catalog model); bool Delete(Func<User_Catalog, bool> predicate); User_Catalog Get(Func<User_Catalog, bool> predicate); bool IsExist(Func<User_Catalog, bool> predicate); } }
using Ninject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webcorp.Controller; using Webcorp.Model; using ReactiveUI; using MongoDB.Driver; using System.Reactive.Linq; using Webcorp.Dal; using System.Linq.Expressions; using System.Security.Permissions; using System.Diagnostics.Contracts; namespace Webcorp.Business { public interface IArticleBusinessHelper<T> : IBusinessHelper<T> where T : Article { Task<T> Create(string code, ArticleType type); void AddMouvementStock(T entity, DateTime date, int quantity, MouvementSens sens, string reference); void AddBesoin(T entity, DateTime now, int quantite, string reference, TypeBesoin tb); } public class ArticleBusinessHelper<T> : BusinessHelper<T>, IArticleBusinessHelper<T> where T : Article { public ArticleBusinessHelper([Named("ArticleController")]IBusinessController<T> ctrl) : base(ctrl) { } public void AddMouvementStock(T entity, DateTime date, int quantity, MouvementSens sens, string reference) { Contract.Requires(entity != null); var mvt = new MouvementStock() { Date = date, Quantite = quantity, Sens = sens, Reference = reference }; entity.MouvementsStocks.Add(mvt); entity.IsChanged = true; } public void AddBesoin(T entity, DateTime now, int quantity, string reference, TypeBesoin tb) { Contract.Requires(entity != null); var besoin = new Besoin() { Date = now, QuantiteBesoin = quantity, Reference = reference, TypeBesoin = tb }; entity.Besoins.Add(besoin); entity.IsChanged = true; } public override void Attach(T entity) { base.Attach(entity); if (entity.MouvementsStocks.IsNotNull()) { entity.ShouldDispose(entity.MouvementsStocks.CountChanged.Subscribe(_ => { entity.IsChanged = true; })); entity.ShouldDispose(entity.MouvementsStocks.ItemChanged.Subscribe(_ => entity.IsChanged = true)); entity.ShouldDispose(entity.MouvementsStocks.ItemsAdded.Subscribe(_ => { entity.StockPhysique = entity.MouvementsStocks.StockPhysique; })); entity.ShouldDispose(entity.MouvementsStocks.ItemsRemoved.Subscribe(_ => { entity.StockPhysique = entity.MouvementsStocks.StockPhysique; })); } if (entity.Nomenclatures.IsNotNull()) { entity.ShouldDispose(entity.ObservableForProperty(x => x.NomenclatureVersion).Subscribe(_ => UpdateCout(entity))); entity.ShouldDispose(entity.Nomenclatures.CountChanged.Subscribe(_ => { entity.IsChanged = true; UpdateCout(entity); })); entity.ShouldDispose(entity.Nomenclatures.ItemChanged.Subscribe(_ => { entity.IsChanged = true; UpdateCout(entity); })); } /* entity.Changed.Where(x => x.PropertyName == "Source").Subscribe(_ => { SourceChanged(_.Sender as T); });*/ } private void UpdateCout(T entity) { Contract.Requires(entity != null); entity.CoutMP = new unite.Currency(0); foreach (var nome in entity.Nomenclatures.Where(v => v.Version == entity.NomenclatureVersion)) { } } [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] public async Task<T> Create(string code, ArticleType type) { Contract.Requires(code != null); Contract.Requires(code.Trim().Length > 0); T result = await base.CreateAsync(); result.Code = code; result.TypeArticle = type; result.Societe = AuthService.Utilisateur.Societe; if (result.IsMakeable() && result.Nomenclatures.IsNull()) { result.Nomenclatures = new Nomenclatures(); result.GererEnstock = true; result.ArticleFantome = false; result.AutoriseStockNegatif = true; result.GestionParLot = false; result.StockMini = 0; result.StockMaxi = 0; result.QuantiteMiniReappro = 0; if (result.GererEnstock ?? false) { result.StockPhysique = 0; result.StockReservee = 0; result.StockAttendu = 0; } result.CoutPreparation = new unite.Currency(0); result.CoutMP = new unite.Currency(0); result.CoutMO = new unite.Currency(0); result.CoutST = new unite.Currency(0); result.CoutFG = new unite.Currency(0); } if (result.IsMakeable() && result.Productions.IsNull()) result.Productions = new Productions(); if (result.IsStockable() && result.MouvementsStocks.IsNull()) result.MouvementsStocks = new MouvementsStocks(); Attach(result); return result; } public override async Task<T> GetById(string id) { T result = await base.GetById(id); result.ShouldDispose(result.Nomenclatures.ItemRequested.Subscribe(async x => { x.Article = await this.Controller.Repository.GetById(x.ArticleId); })); return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(NoteDetector))] public class NoteLock : MonoBehaviour { public NoteDoor[] door; public bool isSwitch; public GameObject particleOnHit; public Material diffuseFlash; public AudioClip onHit; public bool shake; public float amplitude; private SpriteRenderer spriteRend; private NoteDetector detector; private AudioManager aux; private bool used = false; private void Awake() { detector = GetComponent<NoteDetector>(); spriteRend = GetComponent<SpriteRenderer>(); aux = AudioManager.instance; } private void OnEnable() { detector.DetectedNote += SwitchDoor; } private void OnDisable() { detector.DetectedNote -= SwitchDoor; } private void Start() { if (diffuseFlash != null) { spriteRend.material = new Material(diffuseFlash); } } private void SwitchDoor() { for (int i = 0; i < door.Length; i++) { if (isSwitch) { door[i].SwitchDoor(); } else if (!used) { door[i].SwitchDoor(); } } used = true; aux.PlaySound(onHit, true); StartCoroutine(IFlashWhite(0.3f)); Instantiate(particleOnHit, GetComponent<Collider2D>().bounds.center, Quaternion.identity); ShakeCamera(); } private void ShakeCamera() { if (shake) { CameraShake camShake = Camera.main.GetComponent<CameraShake>(); if (camShake != null) { camShake.ShakeCamera(amplitude); } } } private IEnumerator IFlashWhite(float time) { float timer = time; while (timer > 0) { timer -= Time.deltaTime; float flashAmount = Mathf.Clamp01(Mathf.Sin((timer / time) * Mathf.PI) * 0.8f); spriteRend.material.SetFloat("_FlashAmount", flashAmount); yield return null; } } private void OnDrawGizmos() { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(GetComponent<Collider2D>().bounds.center, 10f); } private void OnDrawGizmosSelected() { Gizmos.color = Color.blue; for (int i = 0; i < door.Length; i++) { if (door[i] != null) { Gizmos.DrawLine(GetComponent<Collider2D>().bounds.center, door[i].transform.position); } } } }
using AutoMapper; using AutoMapper.QueryableExtensions; using ZooApp.Application.Common.Interfaces; using ZooApp.Application.Common.Mappings; using ZooApp.Application.Common.Models; using MediatR; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace ZooApp.Application.Animal.Queries.GetAnimalWithPagination { public class GetAnimalWithPaginationQuery : IRequest<PaginatedList<AnimalDto>> { public int PageNumber { get; set; } = 1; public int PageSize { get; set; } = 10; } public class GetAnimalWithPaginationQueryHandler : IRequestHandler<GetAnimalWithPaginationQuery, PaginatedList<AnimalDto>> { private readonly IApplicationDbContext _context; private readonly IMapper _mapper; public GetAnimalWithPaginationQueryHandler(IApplicationDbContext context, IMapper mapper) { _context = context; _mapper = mapper; } public async Task<PaginatedList<AnimalDto>> Handle(GetAnimalWithPaginationQuery request, CancellationToken cancellationToken) { return await _context.Animals .OrderBy(x => x.Nombre) .ProjectTo<AnimalDto>(_mapper.ConfigurationProvider) .PaginatedListAsync(request.PageNumber, request.PageSize); ; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Media.Media3D; namespace WpfApplicationFinally { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var ModelsGroup = new Model3DGroup(); ModelsGroup.Children.Add(this.AddLine(new Point3D(0, 0, 100), new Point3D(0, 100, 100), "line 1)")); ModelsGroup.Children.Add(new AmbientLight(Colors.White)); Model.Content = ModelsGroup; } private Model3D AddLine(Point3D startPoint, Point3D EndPoint, string name) { SolidColorBrush brush = new SolidColorBrush(Colors.Black); var material = new DiffuseMaterial(brush); var mesh = new MeshGeometry3D(); mesh.Positions.Add(startPoint); mesh.Positions.Add(EndPoint); mesh.Positions.Add(new Point3D(100, 0, 100)); mesh.TriangleIndices.Add(0); mesh.TriangleIndices.Add(1); mesh.TriangleIndices.Add(0); return new GeometryModel3D(mesh, material); } } }
// Copyright (C) Microsoft Corporation. All rights reserved. using System; using System.Runtime.CompilerServices; namespace BitConverter { /// <summary> /// A BitConverter with a specific endianness that converts base data types to an array of bytes, and an array of bytes /// to base data types, regardless of /// machine architecture. Access the little-endian and big-endian converters with their respective properties. /// </summary> /// <remarks> /// The EndianBitConverter implementations provide the same interface as <see cref="System.BitConverter" />, but /// exclude those methods which perform the /// same on both big-endian and little-endian machines (such as <see cref="BitConverter.ToString(byte[])" />). However, /// <see cref="GetBytes(bool)" /> is /// included for consistency. /// </remarks> public abstract class EndianBitConverter { /// <summary> /// Get an instance of a <see cref="LittleEndianBitConverter" />, a BitConverter which performs all conversions in /// little-endian format regardless of /// machine architecture. /// </summary> public static EndianBitConverter LittleEndian { get; } = new LittleEndianBitConverter(); /// <summary> /// Get an instance of a <see cref="BigEndianBitConverter" />, a BitConverter which performs all conversions in /// big-endian format regardless of /// machine architecture. /// </summary> public static EndianBitConverter BigEndian { get; } = new BigEndianBitConverter(); /// <summary> /// Indicates the byte order ("endianness") in which data should be converted. /// </summary> public abstract bool IsLittleEndian { get; } /// <summary> /// Returns the specified Boolean value as a byte array. /// </summary> /// <param name="value">A Boolean value.</param> /// <returns>A byte array with length 1.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Boolean" /> value by calling the /// <see cref="ToBoolean(byte[], int)" /> method. /// </remarks> public byte[] GetBytes(bool value) { return new[] { value ? (byte)1 : (byte)0 }; } /// <summary> /// Returns the specified Unicode character value as an array of bytes. /// </summary> /// <param name="value">A character to convert.</param> /// <returns>An array of bytes with length 2.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Char" /> value by calling the /// <see cref="ToChar(byte[], int)" /> method. /// </remarks> public byte[] GetBytes(char value) { return GetBytes((short)value); } /// <summary> /// Returns the specified double-precision floating point value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 8.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Double" /> value by calling the /// <see cref="ToDouble(byte[], int)" /> method. /// </remarks> public byte[] GetBytes(double value) { var val = System.BitConverter.DoubleToInt64Bits(value); return GetBytes(val); } /// <summary> /// Returns the specified 16-bit signed integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 2.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Int16" /> value by calling the /// <see cref="ToInt16(byte[], int)" /> method. /// </remarks> public abstract byte[] GetBytes(short value); /// <summary> /// Returns the specified 32-bit signed integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 4.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Int32" /> value by calling the /// <see cref="ToInt32(byte[], int)" /> method. /// </remarks> public abstract byte[] GetBytes(int value); /// <summary> /// Returns the specified 64-bit signed integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 8.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Int64" /> value by calling the /// <see cref="ToInt64(byte[], int)" /> method. /// </remarks> public abstract byte[] GetBytes(long value); /// <summary> /// Returns the specified single-precision floating point value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 4.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="Single" /> value by calling the /// <see cref="ToSingle(byte[], int)" /> method. /// </remarks> public byte[] GetBytes(float value) { var val = new SingleConverter(value).GetIntValue(); return GetBytes(val); } /// <summary> /// Returns the specified 16-bit unsigned integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert. </param> /// <returns>An array of bytes with length 2.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="UInt16" /> value by calling the /// <see cref="ToUInt16(byte[], int)" /> method. /// </remarks> [CLSCompliant(false)] public byte[] GetBytes(ushort value) { return GetBytes((short)value); } /// <summary> /// Returns the specified 32-bit unsigned integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 4.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="UInt32" /> value by calling the /// <see cref="ToUInt32(byte[], int)" /> method. /// </remarks> [CLSCompliant(false)] public byte[] GetBytes(uint value) { return GetBytes((int)value); } /// <summary> /// Returns the specified 64-bit unsigned integer value as an array of bytes. /// </summary> /// <param name="value">The number to convert.</param> /// <returns>An array of bytes with length 8.</returns> /// <remarks> /// You can convert a byte array back to a <see cref="UInt64" /> value by calling the /// <see cref="ToUInt64(byte[], int)" /> method. /// </remarks> [CLSCompliant(false)] public byte[] GetBytes(ulong value) { return GetBytes((long)value); } /// <summary> /// Returns a Boolean value converted from the byte at a specified position in a byte array. /// </summary> /// <param name="value">A byte array.</param> /// <param name="startIndex">The index of the byte within <paramref name="value" />.</param> /// <returns> /// true if the byte at <paramref name="startIndex" /> in <paramref name="value" /> is nonzero; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 1. /// </exception> public bool ToBoolean(byte[] value, int startIndex) { CheckArguments(value, startIndex, 1); return value[startIndex] != 0; } /// <summary> /// Returns a Unicode character converted from two bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array.</param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A character formed by two bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToChar method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> + /// 1 to a <see cref="Char" /> value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 2. /// </exception> public char ToChar(byte[] value, int startIndex) { return (char)ToInt16(value, startIndex); } /// <summary> /// Returns a double-precision floating point number converted from eight bytes at a specified position in a byte /// array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A double precision floating point number formed by eight bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToDouble method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> /// + 7 to a <see cref="Double" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 8. /// </exception> public double ToDouble(byte[] value, int startIndex) { var val = ToInt64(value, startIndex); return System.BitConverter.Int64BitsToDouble(val); } /// <summary> /// Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A 16-bit signed integer formed by two bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToInt16 method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> + /// 1 to an <see cref="Int16" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 2. /// </exception> public abstract short ToInt16(byte[] value, int startIndex); /// <summary> /// Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes. </param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A 32-bit signed integer formed by four bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToInt32 method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> + /// 3 to an <see cref="Int32" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 4. /// </exception> public abstract int ToInt32(byte[] value, int startIndex); /// <summary> /// Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A 64-bit signed integer formed by eight bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToInt64 method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> + /// 7 to an <see cref="Int64" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 8. /// </exception> public abstract long ToInt64(byte[] value, int startIndex); /// <summary> /// Returns a single-precision floating point number converted from four bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes.</param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A single-precision floating point number formed by four bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToSingle method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> /// + 3 to a <see cref="Single" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 4. /// </exception> public float ToSingle(byte[] value, int startIndex) { var val = ToInt32(value, startIndex); return new SingleConverter(val).GetFloatValue(); } /// <summary> /// Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array. /// </summary> /// <param name="value"></param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A 16-bit unsigned integer formed by two bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToUInt16 method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> /// + 1 to a <see cref="UInt16" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 2. /// </exception> [CLSCompliant(false)] public ushort ToUInt16(byte[] value, int startIndex) { return (ushort)ToInt16(value, startIndex); } /// <summary> /// Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes. </param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A 32-bit unsigned integer formed by four bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToUInt32 method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> /// + 3 to a <see cref="UInt32" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 4. /// </exception> [CLSCompliant(false)] public uint ToUInt32(byte[] value, int startIndex) { return (uint)ToInt32(value, startIndex); } /// <summary> /// Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array. /// </summary> /// <param name="value">An array of bytes. </param> /// <param name="startIndex">The starting position within <paramref name="value" />.</param> /// <returns>A 64-bit unsigned integer formed by the eight bytes beginning at <paramref name="startIndex" />.</returns> /// <remarks> /// The ToUInt64 method converts the bytes from index <paramref name="startIndex" /> to <paramref name="startIndex" /> /// + 7 to a <see cref="UInt64" /> /// value. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="value" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="startIndex" /> is less than zero or greater than the length of <paramref name="value" /> minus 8. /// </exception> [CLSCompliant(false)] public ulong ToUInt64(byte[] value, int startIndex) { return (ulong)ToInt64(value, startIndex); } // Testing showed that this method wasn't automatically being inlined, and doing so offers a significant performance improvement. #if !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif internal void CheckArguments(byte[] value, int startIndex, int byteLength) { if (value == null) throw new ArgumentNullException(nameof(value)); // confirms startIndex is not negative or too far along the byte array if ((uint)startIndex > value.Length - byteLength) throw new ArgumentOutOfRangeException(nameof(value)); } } }
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace RFI.TimeTracker.WindowsViews { [ValueConversion(typeof(DateTime), typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return string.Empty; } var date = (DateTime)value; return date.ToString("d.M.yyyy HH:mm"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var strValue = value as string; DateTime resultDateTime; if (DateTime.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return DependencyProperty.UnsetValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebsiteBanHang.ViewModels { public class AddressListViewModel { public int AddressId { get; set; } public string FullName { get; set; } public string PhoneNumber { get; set; } public string Street { get; set; } public bool IsDefault { get; set; } public Location Location { get; set; } } public class Location { public string Ward { get; set; } public string District { get; set; } public string Province { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace BitmapLSB { public partial class FormApp : Form { String stPath, ndPath, decPath; public FormApp() { InitializeComponent(); } private void FixPicture(Image picImage, PictureBox picBox) { picBox.Image = picImage; if (picImage.Width < 512 && picImage.Height < 512) { picBox.Location = new Point((picBox.Parent.ClientSize.Width / 2) - (picImage.Width / 2), (picBox.Parent.ClientSize.Height / 2) - (picImage.Height / 2)); picBox.SizeMode = PictureBoxSizeMode.Normal; } else { picBox.Location = new Point(0, 25); picBox.SizeMode = PictureBoxSizeMode.Zoom; } } private void btnChoose_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Title = "Chọn ảnh để giấu tin"; openFile.Filter = "Bitmap Image(*.bmp)|*.bmp"; if (openFile.ShowDialog() == DialogResult.OK) { stPath = openFile.FileName; Bitmap bitmap = new Bitmap(stPath); FixPicture(bitmap, pictureBefore); pictureBefore.Image = bitmap; txtStPath.Text = stPath; txtMessage.Focus(); } } private void btnSave_Click(object sender, EventArgs e) { if (txtStPath.Text == "") MessageBox.Show("Vui lòng chọn ảnh để giấu tin!", "Thông báo"); else { if (txtMessage.Text != "") { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Title = "Chọn nơi lưu ảnh"; saveDialog.Filter = "Bitmap (*.bmp)|*.bmp"; if (saveDialog.ShowDialog() == DialogResult.OK) { ndPath = saveDialog.FileName; if (ndPath == stPath) MessageBox.Show("Không thể ghi đè lên hình ảnh đã chọn!", "Lỗi hệ thống"); else { CreateFile(stPath, ndPath, txtMessage.Text); Bitmap bitmap = new Bitmap(ndPath); FixPicture(bitmap, pictureAfter); pictureAfter.Image = bitmap; saveDialog.Dispose(); MessageBox.Show("Đã giấu tin thành công!", "Thông báo"); } } } else { MessageBox.Show("Vui lòng nhập tin nhắn!", "Thông báo"); } } } private byte[] AddMessage(byte[] message) { int mes = message.Length; byte[] byteMes = BitConverter.GetBytes(mes); byte[] newMes = new byte[mes + byteMes.Length]; for (int i = 0; i < byteMes.Length; i++) newMes[i] = byteMes[i]; for (int i = 0; i < mes; i++) newMes[i + byteMes.Length] = message[i]; return newMes; } public void CreateFile(string stPath, string ndPath, string message) { FileStream inStream = new FileStream(stPath, FileMode.Open, FileAccess.Read); int offset = 54; inStream.Seek(0, 0); byte[] header = new byte[offset]; inStream.Read(header, 0, offset); FileStream outStream = new FileStream(ndPath, FileMode.Create, FileAccess.Write); outStream.Write(header, 0, offset); UnicodeEncoding unicode = new UnicodeEncoding(); byte[] newMessageByte = AddMessage(unicode.GetBytes(message)); inStream.Seek(offset, 0); LSB.Encode(inStream, newMessageByte, outStream); inStream.Close(); outStream.Close(); } private void btnChooseDec_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Title = "Chọn ảnh để giải mã"; openFile.Filter = "Bitmap (*.bmp)|*.bmp"; if (openFile.ShowDialog() == DialogResult.OK) { decPath = openFile.FileName; Bitmap bitmap = new Bitmap(decPath); FixPicture(bitmap, pictureBoxDec); txtPath.Text = decPath; txtResult.Text = ""; } } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); } private void btnDecode_Click(object sender, EventArgs e) { if (txtPath.Text != "") { FileStream inStream = new FileStream(decPath, FileMode.Open, FileAccess.Read); int offset = 54; inStream.Seek(offset, 0); byte[] byteLength = new byte[4]; byteLength = LSB.Decode(inStream, 4); int length = BitConverter.ToInt32(byteLength, 0); inStream.Seek(offset + 4 * 8, 0); byte[] buffer = new byte[length]; while (true) { try { buffer = LSB.Decode(inStream, length); } catch { MessageBox.Show("Ảnh này không chứa thông tin!", "Thông báo"); break; } byte[] hidenMessage = new byte[4 + buffer.Length]; hidenMessage = ByteArray(byteLength, buffer); byte[] byteMessage = new byte[length]; for (int i = 0; i < length; i++) byteMessage[i] = hidenMessage[i + 4]; UnicodeEncoding unicode = new UnicodeEncoding(); string result = unicode.GetString(byteMessage); txtResult.Text = result; MessageBox.Show("Giải mã thành công!", "Thông báo"); break; } inStream.Close(); } else { MessageBox.Show("Vui lòng chọn ảnh để giải mã!", "Thông báo"); } } private byte[] ByteArray(byte[] stArr, byte[] ndArr) { byte[] resultArr = new byte[stArr.Length + ndArr.Length]; for (int i = 0; i < stArr.Length; i++) resultArr[i] = stArr[i]; for (int i = 0; i < ndArr.Length; i++) resultArr[i + stArr.Length] = ndArr[i]; return resultArr; } } }
using API.Models; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace API.Banco { public class BancoLeitura { private Conexao ObjBanco; public BancoLeitura() { ObjBanco = new Conexao(); } ~BancoLeitura() { ObjBanco = null; } public Conexao Conexao { get => default(Conexao); set { } } public DataTable Carregar_Leitura(int maquina) { try { List<SqlParameter> LstParametros = new List<SqlParameter>(); DataTable dt = ObjBanco.ExecuteQuery("select * from leitura where idLeitura=(select max(idleitura) from leitura where Maquina_Uso ="+maquina+")", LstParametros); return dt; } catch (Exception) { return null; } } public int Salva_Leitura(Leitura l) { try { List<SqlParameter> LstParametros = new List<SqlParameter>(); DataTable dt = ObjBanco.ExecuteQuery("insert into Leitura(Hd,Mram,Cpu,Data,Maquina_Uso) values("+l.Hd+","+l.Mram+","+l.Cpu+",'"+l.Data+"'," + l.Maquina_Uso+")", LstParametros); dt = ObjBanco.ExecuteQuery("select max(idLeitura) as idLeitura from Leitura", LstParametros); if (dt != null) { return int.Parse(dt.Rows[0][0].ToString()); } return 0; } catch (Exception e) { throw e; } } } }
using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Text; using liteCMS.Data; using liteCMS.Entity.Extranet; namespace liteCMS.Logic { /// <summary> /// Descripción breve de Sistema. /// </summary> public class lExtranet : Exceptions { #region Cliente public static List<eCliente> Cliente_listar(string criterio) { return ext_Cliente.GetList(criterio); } public static eCliente Cliente_item(string codigoCliente) { return ext_Cliente.GetItem(codigoCliente); } #endregion #region Contacto public static eContacto Contacto_login(string email) { return ext_Contacto.GetItem_Login(email); } public static eContacto Contacto_item(string codigoCliente, string codigoContacto) { return ext_Contacto.GetItem(codigoCliente, codigoContacto); } public static eContacto ContactoPrincipal_item(string codigoCliente) { return ext_Contacto.GetItem_Principal(codigoCliente); } public static List<eContacto> Contacto_list(string codigoCliente) { return ext_Contacto.GetList(codigoCliente); } #endregion #region Vendedor public static eVendedor Vendedor_item(string codigoCliente, string codigoContacto) { return ext_Vendedor.GetItem(codigoCliente, codigoContacto); } public static eVendedor Vendedor_login(string email) { return ext_Vendedor.GetItem_Login(email); } public static List<eVendedor> Vendedor_list(string codigoCliente) { return ext_Vendedor.GetList(codigoCliente); } public static List<eCliente> Vendedor_search(string codigoVendedor, string filtro, string criterio) { return ext_Vendedor.GetList_Search(codigoVendedor, filtro, criterio); } #endregion #region Direccion public static List<eDireccion> Direccion_listar(string codigoCliente, string criterio) { return ext_Direccion.GetList(codigoCliente, criterio); } public static List<eDireccion> Direccion_listar(string codigoCliente) { return ext_Direccion.GetList(codigoCliente, ""); } #endregion #region ServicioCAT public static List<eServicioCAT> ServicioCAT_listar(string servicio, string codigoCliente) { return ext_ServicioCAT.GetList(servicio, codigoCliente); } public static eServicioCAT ServicioCAT_item(string servicio, string codigoCliente, string codigoContacto) { return ext_ServicioCAT.GetItem(servicio, codigoCliente, codigoContacto); } public static bool ServicioCAT_add(eServicioCAT oRegistro) { oRegistro.fechaRegistro = DateTime.Now; IdException = ext_ServicioCAT.Insert(oRegistro); return (IdException == 0); } public static bool ServicioCAT_edit(eServicioCAT oRegistro) { oRegistro.fechaEdicion = DateTime.Now; IdException = ext_ServicioCAT.Update(oRegistro); return (IdException == 0); } #endregion #region Disclaimer public static List<eDisclaimer> Disclaimer_listar(string criterio) { return ext_Disclaimer.GetList(criterio); } public static eDisclaimer Disclaimer_item(string codigoCliente, string codigoContacto) { return ext_Disclaimer.GetItem(codigoCliente, codigoContacto); } public static bool Disclaimer_add(eDisclaimer oDisclaimer) { IdException = ext_Disclaimer.Insert(oDisclaimer); return (IdException == 0); } public static bool Disclaimer_edit(eDisclaimer oDisclaimer) { IdException = ext_Disclaimer.Update(oDisclaimer); return (IdException == 0); } #endregion #region Proceso public static List<eProceso> Proceso_listar() { return ext_Proceso.GetList(); } public static eProceso ProcesoCommand_item(string Command) { return ext_Proceso.GetItem_Command(Command); } #endregion #region RegistroLog public static List<eRegistroLog> RegistroLog_listar(DateTime FechaIni, DateTime FechaFin) { return ext_RegistroLog.GetList(FechaIni, FechaFin); } public static List<eRegistroLog> RegistroLog_listar(string codigoCliente) { return ext_RegistroLog.GetList(codigoCliente); } public static eRegistroLog RegistroLog_item(long IdRegistroLog) { return ext_RegistroLog.GetItem(IdRegistroLog); } public static bool RegistroLog_add(eRegistroLog oRegistroLog) { oRegistroLog.FechaRegistro = DateTime.Now; IdException = ext_RegistroLog.Insert(oRegistroLog); return (IdException == 0); } public static bool RegistroLogUsuario_delete(string codigoCliente, string codigoContacto) { IdException = ext_RegistroLog.DeleteUsuarioLog(codigoCliente, codigoContacto); return (IdException == 0); } #endregion #region Methods public static List<eRegistroLog> RegistroLog_Sort(List<eRegistroLog> lRegistroLog, string OrderBy) { string[] order = OrderBy.Split(' '); switch (order[0]) { case "IdRegistroLog": lRegistroLog.Sort((order[1] == "DESC") ? eRegistroLog.IdRegistroLogComparison_Desc : eRegistroLog.IdRegistroLogComparison); break; case "FechaRegistro": lRegistroLog.Sort((order[1] == "DESC") ? eRegistroLog.FechaRegistroComparison_Desc : eRegistroLog.FechaRegistroComparison); break; case "NombreCliente": lRegistroLog.Sort((order[1] == "DESC") ? eRegistroLog.NombreClienteComparison_Desc : eRegistroLog.NombreClienteComparison); break; case "NombreProceso": lRegistroLog.Sort((order[1] == "DESC") ? eRegistroLog.NombreProcesoComparison_Desc : eRegistroLog.NombreProcesoComparison); break; case "NombreContacto": lRegistroLog.Sort((order[1] == "DESC") ? eRegistroLog.NombreContactoComparison_Desc : eRegistroLog.NombreContactoComparison); break; } return lRegistroLog; } public static List<eDisclaimer> Disclaimer_Sort(List<eDisclaimer> lDisclaimer, string OrderBy) { string[] order = OrderBy.Split(' '); switch (order[0]) { case "fechaRegistro": lDisclaimer.Sort((order[1] == "DESC") ? eDisclaimer.fechaRegistroComparison_Desc : eDisclaimer.fechaRegistroComparison); break; case "nombreContacto": lDisclaimer.Sort((order[1] == "DESC") ? eDisclaimer.nombreContactoComparison_Desc : eDisclaimer.nombreContactoComparison); break; case "nombreCliente": lDisclaimer.Sort((order[1] == "DESC") ? eDisclaimer.nombreClienteComparison_Desc : eDisclaimer.nombreClienteComparison); break; } return lDisclaimer; } public static List<eCliente> Cliente_Sort(List<eCliente> lCliente, string OrderBy) { string[] order = OrderBy.Split(' '); switch (order[0]) { case "codigoCliente": lCliente.Sort((order[1] == "DESC") ? eCliente.codigoClienteComparison_Desc : eCliente.codigoClienteComparison); break; case "tipoPersona": lCliente.Sort((order[1] == "DESC") ? eCliente.tipoPersonaComparison_Desc : eCliente.tipoPersonaComparison); break; case "razonSocial": lCliente.Sort((order[1] == "DESC") ? eCliente.razonSocialComparison_Desc : eCliente.razonSocialComparison); break; case "RUC": lCliente.Sort((order[1] == "DESC") ? eCliente.rucComparison_Desc : eCliente.rucComparison); break; case "nombreComercial": lCliente.Sort((order[1] == "DESC") ? eCliente.nombreComercialComparison_Desc : eCliente.nombreComercialComparison); break; } return lCliente; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task3 { public class Course { public string CourseName { get; set; } public List<Member> Members{ get; private set; } public Course(string name) { CourseName = name; Members=new List<Member>(); } public void AddStudent(string name, int group) { Members.Add(new Member(name,group)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using InterfaceTutorial.HumanLibrary; /* Naming conventions * Properties, Methods, Classes - PascalCase * InstanceVariable - Variables declared in a method - camelCase * Parameters - camelCase */ namespace InterfaceTutorial.HumanLibrary { public class HumanCreatorWoman : IHuman { public static string[] args(List<IHuman> humanType) { List<IHuman> listOfWomen = new List<IHuman>(); listOfWomen.Add(InitialiseWoman()); listOfWomen.Add(InitialiseWoman()); listOfWomen.Add(InitialiseWoman()); listOfWomen.Add(InitialiseWoman()); for (int i = 0; i < 4; i++) { listOfWomen[i].Crouch("Huddle", i); } foreach (IHuman woman in listOfWomen) { woman.Crouch("Huddle", 5); } int mancounter = 0; int womancounter = 0; do { listOfWomen[womancounter].Protect("Shield", womancounter + 1); mancounter++; womancounter++; } while (mancounter != 4 && womancounter != 4); } public static InterfaceTutorial.HumanLibrary.IHuman InitialiseWoman() { IHuman woman = HumanFactory.CreateHuman("Woman"); woman.Head = "Head with combed up hair"; woman.Arms = "Strong protective arms"; woman.Hands = "Perfectly manicured hands"; woman.Legs = "Shapely legs"; woman.Feet = "Small dainty feet"; ////method utilisation woman.Analyse("Requirements", 30); woman.Protect("Shelter", 45); woman.Crouch("Duck", 10); woman.Clothe("Socks", 2); return woman; } public string Head { get; set; } public string Arms { get; set; } public string Hands { get; set; } public string Legs { get; set; } public string Feet { get; set; } public void Analyse(string analysisType, int analysisTime) { Console.WriteLine(string.Format("The analysis {0} is being conducted by the head {1}.\nThe analysis lasted for {2} minutes.", analysisType, Head, analysisTime)); } //homework starts here public void Protect(string protectionType, int protectionTime) { Console.WriteLine(string.Format("The protection type {0} was provided to the child by the arms {1} for a duration of {2} hours.", protectionType, Arms, protectionTime)); } public void Crouch(string crouchType, int crouchDuration) { Console.WriteLine(string.Format("The crouch type {0} was conducted by the legs {1} for a duration of {2} minutes.", crouchType, Legs, crouchDuration)); } public void Clothe(string clothesType, int timeToClothe) { Console.WriteLine(string.Format("The garment {0} was put on the feet {1}.\nTo clothe took a total time of {2} minutes.", clothesType, Feet, timeToClothe)); } public void Dream(string dreamType, int lengthOfDream) { Console.WriteLine(string.Format("The dreamtype {0} is being dreamt by the head {1}.\nThe dream has lasted for a duration of {2} minutes.", dreamType, Head, lengthOfDream)); } public void Carry(string objectToCarry, int distanceToCarry) { Console.WriteLine(string.Format("The object to Carry {0} was carried by the arms {1} for a carry distance of {2} metres.", objectToCarry, Arms, distanceToCarry)); } public void Run(string runningSpeed, int durationOfRun) { Console.WriteLine(string.Format("The running speed {0} was achieved by the legs {1} for a duration of {2} minutes.", runningSpeed, Legs, durationOfRun)); } public void Kick(string kickingObject, int distanceKicked) { Console.WriteLine(string.Format("The kicking object {0} was kicked by the feet {1} over a kicking distance of {2} metres.", kickingObject, Feet, distanceKicked)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StackTraceException { class Program { static void Main(string[] args) { try { //this one should've been the best way to write as it's the most robust & clean one, but in practice it doesn't //as this one lost the vital stack trace during the catch throw process SampleLogic.LogicA(); } catch (Exception e) { } try { //this one is only just an acceptable way to write as it's not even clean way to write, but in practice it actually is the best way to write //as this one is capable of preserve the vital stack trace during the catch throw process SampleLogic.LogicB(); } catch (Exception e) { } try { //this one should've been the worst way to write as it's so ugly way of exception handling, but in practice it actually is on par with LogicB in result //as this one is capable of preserve the vital stack trace during the catch throw process SampleLogic.LogicC(); } catch (Exception e) { } try { //this one does not handle any exception at all, although crude but this one is capable of preserve the vital stack trace during the catch throw process //and might've been the best way to go for release build as catching and rethrow is helpful in debugging but are completely useless in production environment SampleLogic.LogicD(); } catch (Exception e) { } try { //An example of LogicB style in practice Demo.work(); } catch (Exception e) { } } } class SampleLogic { /// <summary> /// Robust & Clean Code with explicitly stated 'catch (Exception e)' and 'throw e' /// </summary> public static void LogicA() { try { InternalLogic(); } catch (Exception e) { throw e; } } /// <summary> /// Lazy Code with explicitly stated 'catch (Exception e)' and ambiguously stated 'throw' /// </summary> public static void LogicB() { try { InternalLogic(); } catch (Exception e) { throw; } } /// <summary> /// Extremely Lazy Code with ambiguously stated 'catch' and 'throw' /// </summary> public static void LogicC() { try { InternalLogic(); } catch { throw; } } /// <summary> /// No catch and throw at all /// </summary> public static void LogicD() { InternalLogic(); } static void InternalLogic() { int a = 0; int b = 10 / a; } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace CatalogBooks { /// <summary> /// Структура для хранения дополнительной информации /// </summary> public struct AdditionalInfo { public string Authors { get; set; } public string Keywords { get; set; } } public partial class FormBooksDetected : Form { /// <summary> /// Объект для хранения обнаруженных файлов /// </summary> private List<Book> ListBooks { get; set; } /// <summary> /// Объект для хранения подазрительных книг /// </summary> private Dictionary<int, string> WarningBooks { get; set; } /// <summary> /// Объект для хранения дополнительной инфорамации об обнаруженных файлов /// </summary> private Dictionary<string, AdditionalInfo> DictAuthor { get; set; } /// <summary> /// Объект для работы с базой данных /// </summary> private readonly BaseContext _db; /// <summary> /// Объект для хранинения отображаемой информации о файлах /// </summary> private readonly DataTable _dt; /// <summary> /// Объект для сканирования папок /// </summary> private readonly CheckFiles _checkFiles; /// <summary> /// Конструктор класса /// </summary> public FormBooksDetected() { InitializeComponent(); _db = new BaseContext(); _db.Books.Load(); _db.Authors.Load(); DictAuthor = new Dictionary<string, AdditionalInfo>(); _dt = new DataTable("Books"); _checkFiles = new CheckFiles(".pdf|.djvu|.fb2"); ListBooks = new List<Book>(); WarningBooks = new Dictionary<int, string>(); LoadData(); } /// <summary> /// Загрузка данных в DataTable /// </summary> private void LoadData() { _dt.Columns.Add("Добавить", typeof(Boolean)); _dt.Columns.Add("Название", typeof(String)); _dt.Columns.Add("Год издания", typeof(Int32)); _dt.Columns.Add("Путь", typeof(String)); dataGridViewMain.DataSource = _dt; dataGridViewMain.Columns["Путь"].ReadOnly = true; } /// <summary> /// Добавление элемента в таблицу /// </summary> /// <param name="book">Книга</param> private void AddItem(Book book) { ListBooks.Add(book); string name = Path.GetFileNameWithoutExtension(book.Path); _dt.Rows.Add(true, name, 2000, book.Path); DictAuthor[book.Path] = new AdditionalInfo() { Authors = "", Keywords = "" }; } /// <summary> /// Проверка на вхождение в базу данных /// </summary> /// <param name="book"></param> /// <returns>Входимость</returns> private void CheckBook(Book book) { bool bookExist = _db.Books.Any(item => item.MD5 == book.MD5); if (bookExist) { Book dbBook = _db.Books.First(item => item.MD5 == book.MD5); if (dbBook.Path != book.Path) WarningBooks.Add(dbBook.BookId, book.Path); } if (!bookExist) AddItem(book); } private void RepairBooks() { foreach (int bookId in WarningBooks.Keys) _db.Books.Find(bookId).Path = WarningBooks[bookId]; _db.SaveChanges(); } /// <summary> /// Сохранение изменений а базе данных /// </summary> private void SaveData() { for (int i = 0; i < ListBooks.Count; i++) { ListBooks[i].Name = _dt.Rows[i].ItemArray[1].ToString(); ListBooks[i].Year = (int) _dt.Rows[i].ItemArray[2]; } for (int i = 0; i < ListBooks.Count; i++) if ((bool) _dt.Rows[i].ItemArray[0]) { ListBooks[i].KeyWords = DictAuthor[ListBooks[i].Path].Keywords; _db.Books.Add(ListBooks[i]); string authors = DictAuthor[ListBooks[i].Path].Authors; if (authors == "") authors = "noname noname"; foreach (string authorInfo in authors.Split(';')) { string firstName = authorInfo.Substring(authorInfo.IndexOf(' ') + 1); string lastName = authorInfo.Substring(0, authorInfo.IndexOf(' ')); if (!_db.Authors.Any(x => x.FirstName == firstName && x.LastName == lastName)) _db.Authors.Add(new Author() { FirstName = firstName, LastName = lastName, Books = new List<Book>() {ListBooks[i]} }); else { Author author = _db.Authors.First(x => x.FirstName == firstName && x.LastName == lastName); author.Books.Add(ListBooks[i]); } } _db.SaveChanges(); } } /// <summary> /// Снимает/утанавливает флажки во всей таблице /// </summary> /// <param name="check">Устанавлиаемое значение</param> private void CheckedItems(bool check) { foreach (DataGridViewRow row in dataGridViewMain.Rows) row.Cells["Добавить"].Value = check; } /// <summary> /// Выполняет сканирование папок /// </summary> private async Task CheckDirectoryAsync() { Stopwatch sw = new Stopwatch(); sw.Start(); string[] folders = Properties.Settings.Default.PathsScan.Split(';').Where(x => !String.IsNullOrEmpty(x)).ToArray(); _checkFiles.NewBook.Subscribe ( onNext: x => { toolStripStatusLabelInfo.Text = String.Format("Проверка файла: {0}", x.Path); CheckBook(x); }, onCompleted: () => { sw.Stop(); if (ListBooks.Count == 0) toolStripStatusLabelInfo.Text = "Сканирование не дало результатов. "; else toolStripStatusLabelInfo.Text = String.Format("Было обнаружено: {0} файлов.", ListBooks.Count); toolStripStatusLabelInfo.Text += String.Format("Время: {0:F2} сек.", sw.Elapsed.TotalSeconds); if (WarningBooks.Count > 0 && MessageBox.Show(String.Format("Количество книг имеющих неверный путь: {0}. Исправить?", WarningBooks.Count), "Предупреждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) RepairBooks(); } ); await _checkFiles.CheckForldersAsync(folders); } private async void FormBooksDetected_Load(object sender, EventArgs e) { await CheckDirectoryAsync(); } private void dataGridViewMain_CellLeave(object sender, DataGridViewCellEventArgs e) { DictAuthor[dataGridViewMain.Rows[e.RowIndex].Cells["Путь"].Value.ToString()] = new AdditionalInfo() { Authors = textBoxAuthors.Text, Keywords = textBoxKeywords.Text }; } private void buttonAccept_Click(object sender, EventArgs e) { SaveData(); Close(); } private void dataGridViewMain_CellClick(object sender, DataGridViewCellEventArgs e) { string fileName = dataGridViewMain.Rows[e.RowIndex].Cells["Путь"].Value.ToString(); AdditionalInfo additionalInfo = DictAuthor[fileName]; buttonOpen.Tag = fileName; textBoxAuthors.Text = additionalInfo.Authors; textBoxKeywords.Text = additionalInfo.Keywords; } private void buttonClose_Click(object sender, EventArgs e) { Close(); } private void buttonSelect_Click(object sender, EventArgs e) { CheckedItems(true); } private void buttonUnselect_Click(object sender, EventArgs e) { CheckedItems(false); } private void buttonOpen_Click(object sender, EventArgs e) { string fileName = (sender as Control).Tag.ToString(); if (File.Exists(fileName)) Process.Start(fileName); else MessageBox.Show(String.Format("Файл '{0}'", fileName)); } } }
using System; using System.Net.Http; namespace XUnitMoqSampleWeb.Helpers { /// <summary> /// This provides interfaces to the <see cref="HttpClientHelper"/> class. /// </summary> public interface IHttpClientHelper : IDisposable { /// <summary> /// Creates the <see cref="HttpClient"/> instance. /// </summary> /// <param name="handler"><see cref="HttpMessageHandler"/> instance.</param> /// <returns>Returns the <see cref="HttpClient"/> instance created.</returns> HttpClient CreateInstance(HttpMessageHandler handler = null); } }
using System; using Toppler.Core; namespace Toppler.Api { public class RankingOptions { /// <summary> /// Filter TopN result. /// </summary> public long TopN { get; set; } /// <summary> /// Keep /// This is not a client cache but a redis cache. Result of ZUNIONSTORE has an expiration of this cacheduration. /// </summary> public TimeSpan? CacheDuration { get; set; } public IWeightFunction weightFunc { get; set; } public RankingOptions(TimeSpan? cacheDuration=null, long topN = -1, IWeightFunction weightFunc = null) { this.CacheDuration = cacheDuration; this.TopN = topN; this.weightFunc = weightFunc != null ? weightFunc : WeightFunction.Empty; } /// <summary> /// Internal Default Constuctor. /// </summary> internal RankingOptions() { this.CacheDuration = TimeSpan.Zero; this.TopN = 25; this.weightFunc = WeightFunction.Empty; } } }
using UnityEngine; using System.Collections; public class PauseMenu : MonoBehaviour { private MusicController musicController; private string buttonText; private bool isPaused = false; void Start() { buttonText = "PAUSE"; musicController = GameObject.Find("Main Camera").GetComponent<MusicController>(); } void OnGUI() { if(GUI.Button(new Rect(100,10,70,40), buttonText)) { if (!isPaused) { Time.timeScale = 0; musicController.pauseMusic(); buttonText = "RESUME"; } else { Time.timeScale = 1; musicController.playMusic(); buttonText = "PAUSE"; } isPaused = !isPaused; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ClassLibrary; using ClassLibrary1; namespace ConsoleApp { /// <summary> /// /// </summary> class Program { /// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { int[] Arr = new int[10]; Arr = LogicLayer.AddArr(); for (int i = 0; i < Arr.GetLength(0); i++) { Console.WriteLine(Arr[i]); } Console.WriteLine($"Sum:{LogicLayer.SumAll(Arr)}"); Console.WriteLine($"Sum negative:{LogicLayer.SumNeg(Arr)}"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace OOP4 { public class DetailBase { private Queue<IDetail> details; private Type type; public DetailBase(Type type, int maxnumber) { this.type = type; details = new Queue<IDetail>(); for (int i = 0; i < maxnumber; i++) { ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); object detail = constructor.Invoke(null); details.Enqueue((IDetail) detail); } } public Type Type { set => type = value; } public IDetail DequeueDetail() { ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); object detail = constructor.Invoke(null); details.Enqueue((IDetail)detail); return details.Dequeue(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CraneMonitor { /// <summary> /// TitleBar.xaml の相互作用ロジック /// </summary> public partial class TitleBar : UserControl { public TitleBar() { InitializeComponent(); } public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(object), typeof(TitleBar), new UIPropertyMetadata("Label")); [System.ComponentModel.BindableAttribute(true)] public object Label { get { return (object)GetValue(LabelProperty); } set { SetValue(LabelProperty, value); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IMovement { void GetInput(Inputs.Directions dir); void TurnPlayer(Inputs.Directions dir, float sensitivity); void LookPlayer(Inputs.Directions dir, float sensitivity); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BindingOriented.SyncLinq.Debugging.Model.Events; namespace BindingOriented.SyncLinq.Debugging.Model.Nodes { internal interface IQueryNode : IDumpable { Type Type { get; } IEnumerable<IQueryNode> ChildNodes { get; } IEnumerable<IQueryNodeEvent> Events { get; } } }
using MinimalExtended; using Sandbox; namespace AddonLogger { [Library( "logger-info" )] public class AddonInfo : BaseAddonInfo { public override string Name => "Logger"; public override string Description => "Addon-designed console logging utility"; public override string Author => "Alex"; public override double Version => 1.0; } public class LoggerAddon : AddonClass<AddonInfo> { } }
using FilmShow.Models; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace FilmShow.DAL { public class FilmShowContext : IdentityDbContext<ApplicationUser> { public FilmShowContext() : base("FilmShowContext") { } public virtual DbSet<Show> Shows { get; set; } public virtual DbSet<Movie> Movies { get; set; } public virtual DbSet<Series> Series { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); // Form Many to Many relationship for favorite user movies modelBuilder.Entity<ApplicationUser>() .HasMany<Movie>(u => u.Movie) .WithMany(m => m.ApplicationUser) .Map(um => { um.MapLeftKey("ApplicationUserRefId"); um.MapRightKey("MovieRefId"); um.ToTable("UserMovie"); }); } public static FilmShowContext Create() { return new FilmShowContext(); } } }
using Microsoft.AspNetCore.Mvc.ModelBinding; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ShadowAPI.Models { public class Info : BaseEntity { public string RealName { get; set; } public List<Alias> Aliases { get; set; } // Maybe viruals public Metatype Metatype { get; set; } public string Sex { get; set; } public string Ethnicity { get; set; } public string Description { get; set; } public string Background { get; set; } public string ImageURL { get; set; } //Optional //public Awakened Awakened{ get; set; } [BindNever] public Runner Runner { get; set; } } }
using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.QnA; using System.Threading; using System.Threading.Tasks; namespace JIoffe.BIAD.Bots { public class QnAMakerBot : IBot { //Step 4) Allow the bot to query QnA Maker on each turn //TODO - Add a private member of type QnAMaker and initialize it via Dependency Injection public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { //Ignore activities that are not messages if (turnContext.Activity.Type != "message") return; //TODO - Invoke GetAnswersAsync on the QnAMaker instance; save the response to a variable //TODO - If the response is null or empty send a failure notice to the user //TODO - Otherwise, send the answer of the first response to the user } } }
using System; namespace BIADTemplate.Model { [Serializable] public class RichQnaButton { public string Label { get; set; } public string Url { get; set; } } }
using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Meziantou.Analyzer; internal static class ContextExtensions { private static Diagnostic CreateDiagnostic(DiagnosticDescriptor descriptor, Location location, ImmutableDictionary<string, string?>? properties, params string?[] messageArgs) { return Diagnostic.Create(descriptor, location, properties, messageArgs); } public static void ReportDiagnostic(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxToken syntaxToken, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, syntaxToken, messageArgs); } public static void ReportDiagnostic(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, SyntaxToken syntaxToken, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, syntaxToken.GetLocation(), properties, messageArgs)); } public static void ReportDiagnostic(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxNode syntaxNode, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, syntaxNode, messageArgs); } public static void ReportDiagnostic(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, SyntaxNode syntaxNode, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, syntaxNode.GetLocation(), properties, messageArgs)); } public static void ReportDiagnostic(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, ISymbol symbol, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, symbol, messageArgs); } public static void ReportDiagnostic(this SyntaxNodeAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, ISymbol symbol, params string?[] messageArgs) { foreach (var location in symbol.Locations) { context.ReportDiagnostic(CreateDiagnostic(descriptor, location, properties, messageArgs)); } } public static void ReportDiagnostic(this SymbolAnalysisContext context, DiagnosticDescriptor descriptor, ISymbol symbol, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, symbol, messageArgs); } public static void ReportDiagnostic(this SymbolAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, ISymbol symbol, params string?[] messageArgs) { foreach (var location in symbol.Locations) { ReportDiagnostic(context, descriptor, properties, location, messageArgs); } } public static void ReportDiagnostic(this SymbolAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxReference syntaxReference, params string?[] messageArgs) { var syntaxNode = syntaxReference.GetSyntax(context.CancellationToken); context.ReportDiagnostic(Diagnostic.Create(descriptor, syntaxNode.GetLocation(), ImmutableDictionary<string, string?>.Empty, messageArgs)); } public static void ReportDiagnostic(this SymbolAnalysisContext context, DiagnosticDescriptor descriptor, Location location, params string?[] messageArgs) { context.ReportDiagnostic(Diagnostic.Create(descriptor, location, ImmutableDictionary<string, string?>.Empty, messageArgs)); } public static void ReportDiagnostic(this SymbolAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, Location location, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, location, properties, messageArgs)); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxToken token, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, token, messageArgs); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, SyntaxToken token, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, token.GetLocation(), properties, messageArgs)); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxNode node, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, node, messageArgs); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, SyntaxNode node, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, node.GetLocation(), properties, messageArgs)); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, IOperation operation, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, operation, messageArgs); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, IOperation operation, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, operation.Syntax.GetLocation(), properties, messageArgs)); } public static void ReportDiagnostic(this OperationAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, IInvocationOperation operation, DiagnosticReportOptions options, params string?[] messageArgs) { if (options.HasFlag(DiagnosticReportOptions.ReportOnMethodName) && operation.Syntax.ChildNodes().FirstOrDefault() is MemberAccessExpressionSyntax memberAccessExpression) { context.ReportDiagnostic(Diagnostic.Create(descriptor, memberAccessExpression.Name.GetLocation(), properties, messageArgs)); return; } context.ReportDiagnostic(descriptor, properties, operation, messageArgs); } public static void ReportDiagnostic(this CompilationAnalysisContext context, DiagnosticDescriptor descriptor, ISymbol symbol, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, symbol, messageArgs); } public static void ReportDiagnostic(this CompilationAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, ISymbol symbol, params string?[] messageArgs) { foreach (var location in symbol.Locations) { context.ReportDiagnostic(CreateDiagnostic(descriptor, location, properties, messageArgs)); } } public static void ReportDiagnostic(this OperationBlockAnalysisContext context, DiagnosticDescriptor descriptor, ISymbol symbol, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, symbol, messageArgs); } public static void ReportDiagnostic(this OperationBlockAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, ISymbol symbol, params string?[] messageArgs) { foreach (var location in symbol.Locations) { ReportDiagnostic(context, descriptor, properties, location, messageArgs); } } public static void ReportDiagnostic(this OperationBlockAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxNode syntax, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, syntax.GetLocation(), messageArgs); } public static void ReportDiagnostic(this OperationBlockAnalysisContext context, DiagnosticDescriptor descriptor, SyntaxToken token, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, ImmutableDictionary<string, string?>.Empty, token.GetLocation(), messageArgs); } public static void ReportDiagnostic(this OperationBlockAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, SyntaxNode syntax, params string?[] messageArgs) { ReportDiagnostic(context, descriptor, properties, syntax.GetLocation(), messageArgs); } public static void ReportDiagnostic(this OperationBlockAnalysisContext context, DiagnosticDescriptor descriptor, ImmutableDictionary<string, string?>? properties, Location location, params string?[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(descriptor, location, properties, messageArgs)); } }
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class UserShowInfo : System.Web.UI.Page { string uId = ""; PDTech.OA.BLL.USER_INFO ubll = new PDTech.OA.BLL.USER_INFO(); protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["uId"] == null || string.IsNullOrEmpty(Request.QueryString["uId"].ToString())) { this.Page.ClientScript.RegisterStartupScript(GetType(), "showDiv", "<script>alert('非法参数!');window.parent.layer.closeAll();</script>"); return; } else { uId = Request.QueryString["uId"].ToString(); if(!IsPostBack) BindData(); } } public void BindData() { PDTech.OA.Model.USER_INFO where = new PDTech.OA.Model.USER_INFO(); where = ubll.GetUserInfo(Decimal.Parse(uId)); txtFullName.Text = where.FULL_NAME; txtLoginName.Text = where.LOGIN_NAME; txtMobile.Text = where.MOBILE; txtPhone.Text = where.PHONE; txtDutyInfo.Text = where.DUTY_INFO; txtPublicName.Text = where.PUBLIC_NAME; txtEMaile.Text = where.E_MAILE; txtRemark.Text = where.REMARK; txtSort.Text = where.SORT_NUMBER.ToString(); lblDeptName.Text = where.DEPARTMENT_NAME; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RenderGameObject : MonoBehaviour { public Text objectName; private GameObject c1; private GameObject c2; private GameObject c3; string character = null; // Use this for initialization void Start () { c1 = GameObject.Find("Charmander"); c2 = GameObject.Find("Charmeleon"); c3 = GameObject.Find("Charizard"); } // Update is called once per frame void Update () { character = objectName.text; if(character == "Charmander") { c1.SetActive(false); c2.SetActive(true); c3.SetActive(false); } else if(character == "Charmeleon") { c1.SetActive(false); c2.SetActive(false); c3.SetActive(true); } else if(character == "Charizard") { c1.SetActive(true); c2.SetActive(false); c3.SetActive(false); } } }
using System; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace App1 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Splash : ContentPage { public Splash() { InitializeComponent(); if (XamarinAppSettings.BackgroundImage == "" || XamarinAppSettings.BackgroundImage == "music.png") splash.Source = ImageSource.FromFile("music.png"); else splash.Source = ImageSource.FromFile(XamarinAppSettings.BackgroundImage); } async protected override void OnAppearing() { splash.Opacity = 0.0; await splash.FadeTo(1.0, 2500, Easing.SinIn); await Task.Delay(TimeSpan.FromSeconds(1)); App.Current.MainPage = new MainPage(); } protected override bool OnBackButtonPressed() { return true; } } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_RenderQByUI : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int TestExcute(IntPtr l) { int result; try { RenderQByUI renderQByUI = (RenderQByUI)LuaObject.checkSelf(l); renderQByUI.TestExcute(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddChild(IntPtr l) { int result; try { RenderQByUI renderQByUI = (RenderQByUI)LuaObject.checkSelf(l); GameObject c; LuaObject.checkType<GameObject>(l, 2, out c); renderQByUI.AddChild(c); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_excute(IntPtr l) { int result; try { RenderQByUI renderQByUI = (RenderQByUI)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, renderQByUI.excute); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_excute(IntPtr l) { int result; try { RenderQByUI renderQByUI = (RenderQByUI)LuaObject.checkSelf(l); bool excute; LuaObject.checkType(l, 2, out excute); renderQByUI.excute = excute; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_RenderQ(IntPtr l) { int result; try { RenderQByUI renderQByUI = (RenderQByUI)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, renderQByUI.RenderQ); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_RenderQ(IntPtr l) { int result; try { RenderQByUI renderQByUI = (RenderQByUI)LuaObject.checkSelf(l); int renderQ; LuaObject.checkType(l, 2, out renderQ); renderQByUI.RenderQ = renderQ; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.RenderQByUI"); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_RenderQByUI.TestExcute)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_RenderQByUI.AddChild)); LuaObject.addMember(l, "excute", new LuaCSFunction(Lua_RO_RenderQByUI.get_excute), new LuaCSFunction(Lua_RO_RenderQByUI.set_excute), true); LuaObject.addMember(l, "RenderQ", new LuaCSFunction(Lua_RO_RenderQByUI.get_RenderQ), new LuaCSFunction(Lua_RO_RenderQByUI.set_RenderQ), true); LuaObject.createTypeMetatable(l, null, typeof(RenderQByUI), typeof(MonoBehaviour)); } }
using Prism.Commands; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; namespace LogUrFace.ReportingModule.ViewModels { public class DTRViewModel : BindableBase { public DTRViewModel() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DissolveManager : MonoBehaviour { public GameObject wall1; public GameObject wall2; public GameObject wall3; public bool banish = false; public float threshold = 0; private Renderer mat1; private Renderer mat2; private Renderer mat3; private Collider col1; private Collider col2; private Collider col3; // Start is called before the first frame update void Start() { mat1 = wall1.GetComponent<Renderer>(); mat2 = wall2.GetComponent<Renderer>(); mat3 = wall3.GetComponent<Renderer>(); col1 = wall1.GetComponent<MeshCollider>(); col2 = wall2.GetComponent<MeshCollider>(); col3 = wall3.GetComponent<MeshCollider>(); } // Update is called once per frame void Update() { if(banish) { col1.isTrigger = true; col2.isTrigger = true; col3.isTrigger = true; mat1.material.SetFloat("_Threshold",threshold); mat2.material.SetFloat("_Threshold",threshold); mat3.material.SetFloat("_Threshold",threshold); threshold += 1f * Time.deltaTime; if(threshold > 0.99)this.gameObject.SetActive(false); } } }
using BPiaoBao.DomesticTicket.Domain.Models.Orders; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; namespace BPiaoBao.DomesticTicket.EFRepository.OrdersMap { public class TicketSumMap:EntityTypeConfiguration<TicketSum> { public TicketSumMap() { this.HasKey(t => t.ID); this.Property(t => t.OrderID).HasMaxLength(20); this.Property(t => t.PNR).HasMaxLength(10); this.Property(t => t.PassengerName).HasMaxLength(50); this.Property(t => t.FlightNum).HasMaxLength(50); this.Property(t => t.Voyage).HasMaxLength(50); this.Property(t => t.Seat).HasMaxLength(10); this.Property(t => t.TicketState).HasMaxLength(10); this.Property(t => t.PayMethod).HasMaxLength(10); this.Property(t => t.TrvalNum).HasMaxLength(50); } } }
using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webcorp.unite; namespace Webcorp.Model.Quotation { public class CalculTranche<T,U> : ICalculTranche<T,U> where T : Unit<T> where U:Unit<U> { List<Tranche<T,U>> list=new List<Tranche<T, U>>(); public bool Complexe { get; private set; } public U Montant { get; private set; } public Currency MontantForfait { get; private set; } public bool Simple { get; private set; } public void Add(U montant, Currency montantForfait) { Complexe.ThrowIf<ArgumentException>("You cannot add simple tranche when working on complexe tranche"); Simple = true; this.Montant = montant; this.MontantForfait = montantForfait; } public void Add( T maxi, U montant,bool forfait=false) { Complexe = true; Simple.ThrowIf<ArgumentException>("You cannot add a tranche when working on simple tranche"); list.Add(new Tranche<T, U>() { Maxi = maxi, Montant = montant, Forfait = forfait }); } public Tranche<T,U> Find(T unite) { Tranche<T, U> result = null; foreach (var item in list) { if (item.Maxi > unite && result != null && result?.Maxi < unite) result = item; else if (result == null) result = item; } return result ?? FindForfait() ; } public Tranche<T,U> FindForfait()=> list.Where(t => t.Forfait).FirstOrDefault(); } public class Tranche<T,U>: IComparable<Tranche<T, U>>,IComparer<Tranche<T, U>> where T : Unit<T> where U :Unit<U> { public T Maxi { get; set; } public bool Forfait { get; set; } public U Montant { get; set; } public Currency MontantForfait { get; set; } [BsonIgnore] public bool Simple => MontantForfait != null; [BsonIgnore ] public bool Complex => !Simple; public int CompareTo(Tranche<T, U> other) { return Maxi.CompareTo(other.Maxi); } public int Compare(Tranche<T, U> x, Tranche<T, U> y) { var res= y.Maxi.Value - x.Maxi.Value; if (res == 0) return 0; return res < 0 ? -1 : 1; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StopLightStrategy.Classes { public class RuleBook { public string GetTrafficRule(SignalReaction reaction) { StringBuilder trafficRule = new StringBuilder(); trafficRule.AppendLine(string.Format("The light is {0}", reaction.LightColor)); trafficRule.AppendLine(string.Format("You should {0}", reaction.Reaction)); return trafficRule.ToString(); } } }
using Android.Views; using Kit.Services.Interfaces; using Plugin.CurrentActivity; using Kit.Droid.Services; using Xamarin.Forms; [assembly: Dependency(typeof(BrightnessService))] namespace Kit.Droid.Services { public class BrightnessService : IBrightnessService { public void SetBrightness(float brightness) { Window? window = CrossCurrentActivity.Current.Activity.Window; WindowManagerLayoutParams attributesWindow = new WindowManagerLayoutParams(); attributesWindow.CopyFrom(window.Attributes); attributesWindow.ScreenBrightness = brightness; window.Attributes = attributesWindow; } public float GetBrightness() { Window? window = CrossCurrentActivity.Current.Activity.Window; WindowManagerLayoutParams attributesWindow = new WindowManagerLayoutParams(); attributesWindow.CopyFrom(window.Attributes); return attributesWindow.ScreenBrightness; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; namespace Squidex.Infrastructure.Caching { public interface IPubSub { void Publish(object message); void Subscribe(Action<object> handler); } }
using UnityEngine; using System.Collections; public class Salir : MonoBehaviour { // Update is called once per frame void Update () { if(Input.GetKeyDown(KeyCode.Space)) { Application.LoadLevel("Menu0.1"); } else if(Input.GetKeyDown(KeyCode.Escape)) { GameMaster.Cerrar(); } } void OnGUI(){ if(GUI.Button(new Rect((Screen.width/2)-250,20,500,20),"Pulsa la barra espaciadora para volver al menu principal")) { Application.LoadLevel("Menu0.1"); } else if(GUI.Button(new Rect((Screen.width/2)-250,50,500,20),"Pulsa escape para salir")) { GameMaster.Cerrar(); } GUILayout.TextField("Muertes: "+GameMaster.muertes); GUILayout.TextField("Vida: "+GameMaster.vida); GUILayout.TextField("Litros de gasolina: "+(int)GameMaster.combustible); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ApplicationSeeder.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using CGI.Reflex.Core.Entities; using CGI.Reflex.Core.Queries; using NHibernate; namespace CGI.Reflex.Core.Seed { public class ApplicationSeeder : BaseSeeder { public override int Priority { get { return 20; } } protected override void SeedImpl() { var aurora = new Application { Name = "Aurora", Code = "TST1234", ApplicationType = Get(DomainValueCategory.ApplicationType, "Application maison"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "1"), Status = Get(DomainValueCategory.ApplicationStatus, "En production"), Description = "Description de l'application Aurora", MaintenanceWindow = "Lundi de 12h à 13h", Notes = "Notes d'aurora" } }; aurora.AddTechnologyLinks(GetTechnos("Microsoft Internet Explorer 6.0", "Microsoft .Net 2.0", "Microsoft Visual Basic 6.0")); Session.Save(aurora); var gerico = new Application { Name = "Gerico", Code = "TEST2487", ApplicationType = Get(DomainValueCategory.ApplicationType, "COTS"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "2"), Status = Get(DomainValueCategory.ApplicationStatus, "En production"), Description = "Description de l'application Gerico", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes gerico" } }; gerico.AddTechnologyLinks(GetTechnos("Microsoft Internet Explorer 6.0", "Microsoft Visual Basic 6.0")); Session.Save(gerico); var adn = new Application { Name = "@DN", Code = "TEST2455", ApplicationType = Get(DomainValueCategory.ApplicationType, "Application maison"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "2"), Status = Get(DomainValueCategory.ApplicationStatus, "En production"), Description = "Description de l'application @DN", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes @DN" } }; adn.AddTechnologyLinks(GetTechnos("Oracle 8i")); Session.Save(adn); var cosmos = new Application { Name = "cosmos", Code = "TEST2486", ApplicationType = Get(DomainValueCategory.ApplicationType, "COTS"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "3"), Status = Get(DomainValueCategory.ApplicationStatus, "En production"), Description = "Description de l'application cosmos", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes cosmos" } }; Session.Save(cosmos); var makeup = new Application { Name = "Makeup", Code = "WHKDG521", ApplicationType = Get(DomainValueCategory.ApplicationType, "Saas"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "1"), Status = Get(DomainValueCategory.ApplicationStatus, "Potentiel"), Description = "Description de l'application makeup", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes makeup" } }; makeup.AddTechnologyLinks(GetTechnos("Open Source Firefox")); Session.Save(makeup); var cpo = new Application { Name = "CPO", Code = "45456674", ApplicationType = Get(DomainValueCategory.ApplicationType, "Saas"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "1"), Status = Get(DomainValueCategory.ApplicationStatus, "Retiré"), Description = "Description de l'application cpo", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes cpo" } }; Session.Save(cpo); var costumeinventory = new Application { Name = "Costume Inventory", Code = "4543", ApplicationType = Get(DomainValueCategory.ApplicationType, "Application maison"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "2"), Status = Get(DomainValueCategory.ApplicationStatus, "En production"), Description = "Description de l'application costumeinventory", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes costumeinventory" } }; Session.Save(costumeinventory); var lucioles = new Application { Name = "Lucioles", Code = "454354", ApplicationType = Get(DomainValueCategory.ApplicationType, "Application maison"), AppInfo = { Criticity = Get(DomainValueCategory.ApplicationCriticity, "3"), Status = Get(DomainValueCategory.ApplicationStatus, "En production"), Description = "Description de l'application lucioles", MaintenanceWindow = "Lundi de 18h à 23h", Notes = "Notes lucioles" } }; Session.Save(lucioles); } } }
using System; namespace OCP.User.Backend { /** * @since 14.0.0 */ public interface ISetPasswordBackend { /** * @since 14.0.0 * * @param string uid The username * @param string password The new password * @return bool */ bool setPassword(string uid, string password); } }
using UnityEngine; public class FollowFlyingState : FollowState { public FollowFlyingState(GameObject enemy, StateType state) : base(enemy, state) { } public override void OnStateEnter() { enemyBehavior = enemy.GetComponent<Enemy>(); masks = playerLayer | enemiesLayer | wallsLayer; destination = null; } public override void UpdateState() { if (GameManager.instance.enemiesActive) { //Si el jugador está en el rango de ataque del enemigo y nada se interpone entre ellos, se pasa al estado de ataque if (enemyBehavior.NeedChangeState(enemyBehavior.attackRange, masks)) enemyBehavior.fsm.EnterNextState(); CheckGiveUp(); //Si no está en el rango de ataque, el enemigo debe acercarse al jugador if (destination.HasValue == false || Vector2.Distance(enemy.transform.position, destination.Value) <= 0.1f) { SetUpFollowRays(); if (!hit && !hit1 && !hit2 && !rightHit && !leftHit && !topHit && !bottomHit) { direction = enemyBehavior.playerDirection; } else //algo bloquea el camino más corto hacia el jugador { direction = Vector2.zero; float enemyPosX = enemy.transform.position.x; float enemyPosY = enemy.transform.position.y; float targetPosX = enemyBehavior.target.position.x; float targetPosY = enemyBehavior.target.position.y; if (targetPosX >= enemyPosX && !rightHit && lastMove != Move.Left) SetDirection(Vector2.right); else if (targetPosY > enemyPosY && !topHit && lastMove != Move.Down) SetDirection(Vector2.up); else if (targetPosX < enemyPosX && !leftHit && lastMove != Move.Right) SetDirection(Vector2.left); else if (targetPosY < enemyPosY && !bottomHit && lastMove != Move.Up) SetDirection(Vector2.down); if (direction == Vector2.zero) { if (!leftHit && lastMove != Move.Right) SetDirection(Vector2.left); else if (!topHit && lastMove != Move.Down) SetDirection(Vector2.up); else if (!rightHit && lastMove != Move.Left) SetDirection(Vector2.right); else if (!bottomHit && lastMove != Move.Up) SetDirection(Vector2.down); } } destination = enemy.transform.position + new Vector3(direction.x * 0.65f, direction.y * 0.65f, 0); } } } public override void FixedUpdateState() { if (!enemyBehavior.target.GetComponent<PlayerInputController>().abilityActive && GameManager.instance.enemiesActive) { enemyBehavior.SetAnimatorDirection(direction.x, direction.y); enemyBehavior.characterMovement.Move(direction, enemyBehavior.followSpeed); } } public override void OnStateExit() { destination = null; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace StringMetodos { class Program { static void Main(string[] args) { string primera = "Luz azul"; //Console.WriteLine(primera.palidromo()); //Console.WriteLine(primera.TrimAll()); //Console.WriteLine(primera.reverse()); //Console.WriteLine(primera.toTitle()); } } static class Extensio { public static string TrimAll(this string paraula) { //1r metodo //char[] Palabras = paraula.ToCharArray(); //string palabra = null; //for (int a = 0; a < Palabras.Length; a++) //{ // if (Palabras[a] == ' ') // { // for (int b = a; b < Palabras.Length; b++) // { // Palabras[a] = Palabras[a + 1]; // } // } //} //for(int c = 0; c < Palabras.Length; c++) //{ // palabra = palabra + Palabras[c]; //} //2n metodo //string segona = ""; //foreach (char letra in paraula) //{ // if (letra != ' ') // { // segona = segona + letra; // } //}; //3r metodo return paraula.Replace(" ", ""); } public static string reverse(this string paraula) { char[] paraules = paraula.ToCharArray(); int max = paraules.Length; string paraula1 = null; for(int a = max - 1; a >= 0 ; a--) { paraula1 = paraula1 + paraules[a]; } return paraula1; } public static bool palidromo(this string paraula) { paraula = paraula.TrimAll().ToLower(); string paraula1 = paraula.reverse(); return paraula.Equals(paraula1); } public static string toTitle(this string paraula) { TextInfo ti = CultureInfo.CurrentCulture.TextInfo; ti.Clone(); return ti.ToTitleCase(paraula); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExitScript : MonoBehaviour { public void quitTheGame() { //Quits game if (Application.platform == RuntimePlatform.WebGLPlayer) { Screen.fullScreen = false; } else { Application.Quit(); Debug.Log("Would of quit if built"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Xml.Serialization; using ObjectDataTypes; namespace PirateWars { /// <summary> /// Spawns the a Player_Brig and an Enemy_Brig in the center of the screen. The enemy does nothing and takes no damage. Basic game to check for collisions, and make sure that movement is working correctly. /// </summary> class TestGame : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; //Mouse and Keyboard MouseState oldMouseState; KeyboardState oldKeyState; TimeSpan oldKeyPress; //Textures Texture2D playerBrigTexture; Texture2D enemyBrigTexture; Texture2D playerCBTexture; Texture2D enemyCBTexture; Player player; Enemy enemy; public TestGame() { /*set graphics properties*/ graphics = new GraphicsDeviceManager(this); graphics.IsFullScreen = false; //Changes the settings that you just applied graphics.ApplyChanges(); Content.RootDirectory = "Content"; IsMouseVisible = true; } protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); spriteBatch = new SpriteBatch(GraphicsDevice); oldKeyState = Keyboard.GetState(); oldMouseState = Mouse.GetState(); } protected override void LoadContent() { base.LoadContent(); graphics.PreferredBackBufferHeight = (graphics.GraphicsDevice.DisplayMode.Height - (graphics.GraphicsDevice.DisplayMode.Height / 9)); graphics.PreferredBackBufferWidth = graphics.GraphicsDevice.DisplayMode.Width - (graphics.GraphicsDevice.DisplayMode.Width / 7); graphics.ApplyChanges(); playerBrigTexture = Content.Load<Texture2D>("PlayerImages/Brig2_1"); enemyBrigTexture = Content.Load<Texture2D>("EnemyImages/Brig2_1 - Enemy"); enemyCBTexture = Content.Load<Texture2D>("CannonBall_Enemy"); playerCBTexture = Content.Load<Texture2D>("CannonBall"); player = new Player_Brig(Content.Load<PlayerData>("ObjectDataFiles/Player_Brig_TestData"), playerBrigTexture, playerCBTexture); player.setPosition(new Vector2(290, 537)); enemy = new Enemy_Brig(Content.Load<EnemyData>("ObjectDataFiles/Enemy_Brig_TestData"), enemyBrigTexture, enemyCBTexture); enemy.setPosition(new Vector2(graphics.PreferredBackBufferWidth / 2 - enemyBrigTexture.Width / 2, graphics.PreferredBackBufferHeight / 2 - enemyBrigTexture.Height / 2)); } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here Content.Unload(); base.UnloadContent(); } protected override void Update(GameTime gameTime) { base.Update(gameTime); UpdateKeyboardInput(gameTime); player.Update(gameTime.TotalGameTime); enemy.Update(gameTime.TotalGameTime); CollisionDetection(player, enemy, 0); } private void UpdateKeyboardInput(GameTime time) { KeyboardState newState = Keyboard.GetState(); Vector2 newP = player.getPosition(); float angle = player.getAngle(); TimeSpan newKeyPress = time.TotalGameTime; /* * WAD are the movement keys, but only W and S will actually move the ship * W: move ship forward in the direction that the ship is pointing * A: rotate the ship to the left (-radians) * D: rotate the ship to the right (+radians) */ if (newState.IsKeyDown(Keys.Tab)) { if (player.getShipState() == Player.ShipState.AbilityCharged) { } } if (newState.IsKeyDown(Keys.A) || newState.IsKeyDown(Keys.Left)) { angle = player.getAngle() - player.getTurnSpeed(); /*make sure that it does not move too far off the left screen*/ } if (newState.IsKeyDown(Keys.D) || newState.IsKeyDown(Keys.Right)) { angle = player.getAngle() + player.getTurnSpeed(); } if (newState.IsKeyDown(Keys.W) || newState.IsKeyDown(Keys.Up)) { Vector2 direction = new Vector2((float)(Math.Cos(player.getAngle())), (float)(Math.Sin(player.getAngle()))); direction.Normalize(); newP += direction * player.getSpeed(); }//end move FORWARD //check to make sure it stays within bounds, and then update position and angle OutOfBounds(ref newP, player.getTexture(), 0, graphics.PreferredBackBufferWidth, 0, graphics.PreferredBackBufferHeight); player.setPosition(newP); player.setAngle(angle); // get the time between the last firing and this firing. If the delay has been more than 200 miliseconds, fire again double delay = newKeyPress.TotalMilliseconds - oldKeyPress.TotalMilliseconds; if (newState.IsKeyDown(Keys.Space) && delay > player.getROF()) { player.Fire(); //reset the value of oldkeypress oldKeyPress = newKeyPress; } //Update keyPress state oldKeyState = newState; } private void OutOfBounds(ref Vector2 v, Texture2D t, float lowerXBound, float upperXBound, float lowerYBound, float upperYBound) { //out of bounds top if (v.Y - (t.Height / 2) < lowerYBound) { v.Y = lowerYBound + t.Height / 2; } //out of bounds bottom else if (v.Y + (t.Height / 2) > upperYBound) { v.Y = upperYBound - (t.Height / 2); } //out of bounds left else if (v.X - (t.Width / 2) < lowerXBound) { v.X = lowerXBound + t.Width / 2; } //out of bounds right else if (v.X + (t.Width / 2) > upperXBound) { v.X = upperXBound - (t.Width / 2); } else { return; } } private bool OutOfBounds(CannonBall c) { if (c.getPosition().X < 0 || c.getPosition().X > graphics.PreferredBackBufferWidth) return true; else if (c.getPosition().Y < 0 || c.getPosition().Y > graphics.PreferredBackBufferHeight) return true; else return false; }//outof bounds cannon private void CollisionDetection(Ship s, Ship e, int index) { //check cannon balls for (int j = s.getCBA().Count - 1; j >= 0; j--) { CannonBall cB = s.getCBA().ElementAt(j); if (cB.BoundingBox.Intersects(e.BoundingBox)) { Console.WriteLine("\nCOLLISION CB "+ j + ": \n" + cB.BoundingBox.Print() + "\nAGAINST: \n" + e.BoundingBox.Print()+"\n"); //deal damage to enemy e.takeDamage(cB.getDamage()); //remove cannon ball //if the ship is not a player frigate, remove the cannon ball upon contact if (s.GetType() != typeof(Player_Frigate)) s.getCBA().Remove(cB); //if it is a player frigate, check to see if it's ability is activated, if not, then remove the cannon ball upon contact. Else, leave the cannon balls alone else { if (((Player)(s)).getShipState() != Ship.ShipState.AbilityActivated) s.getCBA().Remove(cB); } }//end if collision //check if the ship should be sunk }//end for j //if s is the player, then check if it is a brig and has its ability activated if (s == player) { if (player.GetType() == typeof(Player_Brig) && player.getShipState() == Ship.ShipState.AbilityActivated) if (s.BoundingBox.Intersects(e.BoundingBox)) { e.takeDamage(s.getDamage()); } } //check if the ship should be sunk if (e.getHealth() <= 0) { if (e.GetType() == typeof(Player_Brig) || e.GetType() == typeof(Player_Frigate) || e.GetType() == typeof(Player_ManOfWar)) { UnloadContent(); EndRun(); } } } protected override void Draw(GameTime gameTime) { //base.Draw(gameTime); spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); GraphicsDevice.Clear(new Color(28, 107, 160)); //draw player spriteBatch.Draw(enemyCBTexture, player.getPosition(), Color.White); spriteBatch.Draw(player.getTexture(), player.getPosition(), null, Color.White, player.getAngle(), player.getOrigin(), 1.0f, SpriteEffects.None, 0.0f); //draw Enemy spriteBatch.Draw(enemy.getTexture(), enemy.getPosition(), null, Color.White, enemy.getAngle(), enemy.getOrigin(), 1.0f, SpriteEffects.None, 0.0f); for (int i = player.getCBA().Count - 1; i >= 0; i--) { CannonBall c = player.getCBA().ElementAt(i); /*if the cannon ball has gone out of bounds, remove it and do not draw, else draw it*/ if (OutOfBounds(player.getCBA().ElementAt(i))) { player.getCBA().RemoveAt(i); } else { spriteBatch.Draw(playerCBTexture, c.getPosition(), null, Color.White, c.getAngle(), c.getOrigin(), 1.0f, SpriteEffects.None, 0.0f); } } /*draw enemy cannon balls*/ for (int i = enemy.getCBA().Count - 1; i >= 0; i--) { CannonBall c = enemy.getCBA().ElementAt(i); if (OutOfBounds(c)) { enemy.getCBA().RemoveAt(i); } else spriteBatch.Draw(enemyCBTexture, c.getPosition(), null, Color.White, c.getAngle(), c.getOrigin(), 1.0f, SpriteEffects.None, 0.0f); } spriteBatch.End(); base.Draw(gameTime); } } }
using System; namespace Factorials.Classes { public class FactorialMethods { public int FactorialAnswer(int inputFromUser) { if(inputFromUser == 1 || inputFromUser == 0) { return 1; } else { return inputFromUser * FactorialAnswer(inputFromUser - 1); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Training_Onion { class Program { public static void Write(string text, ConsoleColor color = ConsoleColor.White, bool backToDefault = false, ConsoleColor backColor = ConsoleColor.Black) { Console.ForegroundColor = color; Console.BackgroundColor = backColor; Console.WriteLine(text); if (backToDefault) { Console.ForegroundColor = ConsoleColor.White; } } static void Main(string[] args) { Start(false, true, true,false); Console.ReadKey(); } public static void Start(bool isEnableOnionInStorage, bool isItRotten, bool isItDirty,bool breakThem) { Write("Now i go check if a have onion in my storage"); if (isEnableOnionInStorage) { Write("Oh yeah i have onion in storage"); Write("Now i must check if is rotten"); if (isItRotten) { Write("Oh no all onion is rotten"); BuyOnion(); } else { Write("It is clean or dirty"); if (isItDirty) { Write("Oh its look as ***"); CleanOnion(); } else { Write("ehmm break them?"); if (breakThem) { Write("Ehmm yeah i have to"); BreakOnion(); } else { Write("Now i will cut the onions"); CutOnion(); } } } } else { Write("Oh no i must buy some Onion"); BuyOnion(); } } public static void BuyOnion() { Start(true, false, true,false); } public static void CleanOnion() { Start(true, false, false,false); } public static void BreakOnion() { Start(true, true, false, true); } public static void CutOnion() { Write("I do it :D"); } } }
using eRecruiterRestClient.Deserialize; using eRecruiterRestClient.Interfaces; using Newtonsoft.Json; using RestSharp; using System; namespace eRecruiterRestClient { class ErecruiterAction : IErecruiterAction { private readonly IAuthToken _authToken; private readonly IRestResponse _response; private readonly RestClient _restClient; private readonly RestRequest _restRequest; private readonly int companyId; private static string url = "https://api.erecruiter.pl"; public ErecruiterAction(IAuthToken authToken) { _restRequest = new RestRequest(); _restClient = new RestClient(url); _authToken = authToken; companyId = GetCompanyId(); } public CompanyDeserialize GetCompanyInfo() { var responseValue = ResponseValue("/v1.0/Account/Companies", Method.GET); CompanyDeserialize cd = JsonConvert.DeserializeObject<CompanyDeserialize>(responseValue); return cd; } public string GetAllCandidate() { return ResponseValue("/v1.0/Candidates", Method.GET); } private string ResponseValue(String resouce, Method method) { _restRequest.Resource = resouce; _restRequest.Method = method; _restRequest.AddParameter("companyId", companyId); _restRequest.AddHeader("Authorization", AuthHeader()); IRestResponse response = _restClient.Execute(_restRequest); var content = response.Content; return content; } private int GetCompanyId() { CompanyDeserialize cd = new CompanyDeserialize(); return cd.companyId; } private string AuthHeader() { return "Bearer " + _authToken.GetToken(); } } }
using Athena.Data.Series; using Athena.EventManagers; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Athena.Windows { /// <summary> /// Logika interakcji dla klasy AddSeriesWindow.xaml /// </summary> public partial class AddSeriesWindow { public AddSeriesWindow() { InitializeComponent(); } private void Save_Executed(object sender, ExecutedRoutedEventArgs e) { if (!ApplicationDbContext.Instance.Series.Any(s => s.SeriesName.ToLower() == SeriesNameTextBox.Text.ToLower())) { var series = new Series {SeriesName = SeriesNameTextBox.Text, Id = Guid.NewGuid()}; ApplicationDbContext.Instance .Entry(new Series {SeriesName = SeriesNameTextBox.Text, Id = Guid.NewGuid()}).State = EntityState.Added; ApplicationDbContext.Instance.SaveChanges(); SeriesAdded?.Invoke(this, new EntityEventArgs<Series> {Entity = series}); this.Close(); } else { SeriesExistsTextBlock.Visibility = Visibility.Visible; } } private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = !Validation.GetHasError(SeriesNameTextBox); } public event EventHandler<EntityEventArgs<Series>> SeriesAdded; } }
using System; using System.ComponentModel; using System.Windows.Input; using System.Windows.Threading; using Caliburn.Micro; using Frontend.Core.Model.Interfaces; using Action = System.Action; namespace Frontend.Core.Commands { /// <summary> /// Implementation of <c>ICommand</c> that allows for asynchronous operation. /// <remarks> /// Much of this was copied from http://kendoll.net/async_wpf_command /// </remarks> /// </summary> public class OldAsyncCommandBase : DispatcherObject, ICommand, IDisposable { private BackgroundWorker worker; /// <summary> /// Initializes a new instance of the <see cref="OldAsyncCommandBase" /> class. /// </summary> /// <param name="eventAggregator"></param> /// <param name="options"></param> protected OldAsyncCommandBase(IEventAggregator eventAggregator, IConverterOptions options) { Options = options; worker = new BackgroundWorker(); EventAggregator = eventAggregator; } protected IConverterOptions Options { get; private set; } protected IEventAggregator EventAggregator { get; private set; } /// <summary> /// Let us use command manager for thread safety /// </summary> public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } /// <summary> /// When overridden in a derived class, defines the method that determines whether the command can execute in its /// current state. /// </summary> /// <param name="parameter"> /// Data used by the command. If the command does not require data to be passed, /// this object can be set to null. /// </param> /// <returns>True if this command can be executed; otherwise, false.</returns> public bool CanExecute(object parameter) { if (worker.IsBusy) { return false; } return OnCanExecute(parameter); } /// <summary> /// Runs the command method in a background thread. /// </summary> /// <param name="parameter"> /// Data used by the command. If the command does not require data to be passed, /// this object can be set to null. /// </param> public void Execute(object parameter) { worker.Dispose(); worker = new BackgroundWorker(); BeforeExecute(parameter); worker.DoWork += (s, e) => { CommandManager.InvalidateRequerySuggested(); OnExecute(parameter); }; worker.RunWorkerCompleted += (s, e) => { AfterExecute(parameter, e.Error); CommandManager.InvalidateRequerySuggested(); }; worker.RunWorkerAsync(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { if (isDisposing) { worker.Dispose(); } } /// <summary> /// When overridden in a derived class, performs operations in the UI thread /// before beginning the background operation. /// </summary> /// <param name="parameter">The parameter passed to the <c>Execute</c> method of the command.</param> protected virtual void BeforeExecute(object parameter) { } /// <summary> /// When overridden in a derived class, performs operations in a background /// thread when the <c>Execute</c> method is invoked. /// </summary> /// <param name="parameter">The paramter passed to the <c>Execute</c> method of the command.</param> protected virtual void OnExecute(object parameter) { } /// <summary> /// When overridden in a derived class, performs operations when the /// background execution has completed. /// </summary> /// <param name="parameter">The parameter passed to the <c>Execute</c> method of the command.</param> /// <param name="error">The error object that was thrown during the background operation, or null if no error was thrown.</param> protected virtual void AfterExecute(object parameter, Exception error) { } protected virtual bool OnCanExecute(object parameter) { return true; } /// <summary> /// Marshalls the method. /// </summary> /// <param name="action">The action.</param> /// <param name="priority">The priority.</param> protected void MarshallMethod(Action action, DispatcherPriority priority) { if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke(action, priority); return; } action(); } } }
using System; namespace Logbog.Model { public class Chauffør { private int _chID; private string _fNavn; private string _eNavn; private DateTime _opretdato; public int Ch_ID // property { get { return _chID; } // get method set { _chID = value; } // set method } public string ForNavn // property { get { return _fNavn; } // get method set { _fNavn = value; } // set method } public string EfterNavn // property { get { return _eNavn; } // get method set { _eNavn = value; } // set method } public DateTime OpretDato // property { get { return _opretdato; } // get method set { _opretdato = value; } // set method } } }
using LuaInterface; using RO; using SLua; using System; public class Lua_RO_ByteArray : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 1) { ByteArray o = new ByteArray(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (num == 3) { byte[] data; LuaObject.checkArray<byte>(l, 2, out data); int maxSize; LuaObject.checkType(l, 3, out maxSize); ByteArray o = new ByteArray(data, maxSize); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else { result = LuaObject.error(l, "New object failed."); } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetSplitLength(IntPtr l) { int result; try { ByteArray byteArray = (ByteArray)LuaObject.checkSelf(l); int splitLength = byteArray.GetSplitLength(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, splitLength); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetSplitArrayByIndex(IntPtr l) { int result; try { ByteArray byteArray = (ByteArray)LuaObject.checkSelf(l); int index; LuaObject.checkType(l, 2, out index); byte[] splitArrayByIndex = byteArray.GetSplitArrayByIndex(index); LuaObject.pushValue(l, true); LuaObject.pushValue(l, splitArrayByIndex); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int AddMergeByte(IntPtr l) { int result; try { ByteArray byteArray = (ByteArray)LuaObject.checkSelf(l); byte[] data; LuaObject.checkArray<byte>(l, 2, out data); byteArray.AddMergeByte(data); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int MergeByte(IntPtr l) { int result; try { ByteArray byteArray = (ByteArray)LuaObject.checkSelf(l); byte[] o = byteArray.MergeByte(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.ByteArray"); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ByteArray.GetSplitLength)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ByteArray.GetSplitArrayByIndex)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ByteArray.AddMergeByte)); LuaObject.addMember(l, new LuaCSFunction(Lua_RO_ByteArray.MergeByte)); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_ByteArray.constructor), typeof(ByteArray)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _06.TrafficJam { class TrafficJam { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); Queue<string> cars = new Queue<string>(); string input = Console.ReadLine(); int carsPassed = 0; while (input != "end") { if (input == "green") { carsPassed += n; } else { cars.Enqueue(input); } input = Console.ReadLine(); } if (cars.Count >= carsPassed) { for (int i = 0; i < carsPassed; i++) { Console.WriteLine($"{cars.Dequeue()} passed!"); } } else { carsPassed = cars.Count; for (int i = 0; i < carsPassed; i++) { Console.WriteLine($"{cars.Dequeue()} passed!"); } } Console.WriteLine($"{carsPassed} cars passed the crossroads."); } } }
using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Linq; using System.Data; using CakeShop.Data; using Microsoft.Win32; namespace CakeShop.Views { /// <summary> /// Interaction logic for AddNewOrder.xaml /// </summary> /// #region /// Model for AddNewOrder.xmal /// public class CakeInCart { public string Name { get; set; } public long Quantity { get; set; } public long TotalCost { get; set; } public long No { get; set; } public long CakeID { get; set; } public long InventoryNumber; } #endregion #region /// ViewModel for AddNewOrder /// public class AddNewOrderViewModel { CakeShopDAO dao; public AddNewOrderViewModel() { dao = new CakeShopDAO(); } public List<CATEGORY> GetCATEGORies() { return dao.CategoryList(); } public List<CAKE> GetCAKEs() { return dao.CakeList(); } public List<CAKE> GetCAKEs(long CatID) { return dao.CakeList(CatID); } public List<STATUS> GetSTATUs() { List<STATUS> result = new List<STATUS>(); result.Add(dao.GetStatusByID("OBM01"));//mua hàng trực tiếp result.Add(dao.GetStatusByID("OBM02"));//mua hàng online return result; } public long GetORDERsCount() { return dao.OrderCount(); } public bool UpdateInvetoryCake(long CakeID, long InventoryNumber) { bool check = dao.UpdateInvetoryCake(CakeID, InventoryNumber); return check; } } #endregion public partial class NewOrder : Page { CakeShopDAO dao; List<CATEGORY> CATEGORies; List<CAKE> CAKEs; List<STATUS> STATUs; List<CakeInCart> cakeInCarts; AddNewOrderViewModel _mainvm; long No_;//Số thứ tự bánh trong giỏ hàng hiện tại; long TotalBill;// Tổng giá trị giỏ hàng int isOrderAdded; public NewOrder() { InitializeComponent(); Prepare(); } private void Page_Loaded(object sender, RoutedEventArgs e) { } private void Prepare() { //Set local variable - DAO, ViewModel dao = new CakeShopDAO(); _mainvm = new AddNewOrderViewModel(); //Set local variable STATUs = _mainvm.GetSTATUs(); CAKEs = _mainvm.GetCAKEs(); cakeInCarts = new List<CakeInCart>(); No_ = 0; TotalBill = 0; isOrderAdded = 0; //Set CATEGORies CATEGORies = _mainvm.GetCATEGORies(); CATEGORies.Reverse(); CATEGORies.Add(new CATEGORY { ID = 0, Name = "Tất cả", }); CATEGORies.Reverse(); //Update UI StatusComboBox.ItemsSource = STATUs; CakeListView.ItemsSource = CAKEs; CategoryComboBox.ItemsSource = CATEGORies; CartDataGrid.ItemsSource = cakeInCarts; CartCost.Text = "0" + " VNĐ"; CreatedDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); moneyCalculationFrame.Visibility = Visibility.Hidden; //Set selected index CategoryComboBox.SelectedIndex = 0; } private void SaveOrder_Click(object sender, RoutedEventArgs e) { bool check = CheckDataInputError(); if (check == true) { try { StoreDataInput(); RefreshDataInput(); Prepare(); isOrderAdded++; } catch (Exception ex) { MessageBox.Show("Lưu đơn hàng bị lỗi", "Thông báo", MessageBoxButton.OK); } } } private void Refresh_Click(object sender, RoutedEventArgs e) { RefreshDataInput(); Prepare(); } private void AddCurrentCake_Click(object sender, RoutedEventArgs e) { int index = CakeListView.SelectedIndex; if (index != -1) { CAKE curCake = CAKEs[index]; try { long quantity = long.Parse(cakeQuantity.Text); //Check dữ liệu if (quantity < 1) throw new Exception("1"); if (CAKEs[index].InventoryNum - quantity < 0) throw new Exception("2"); //Khởi tạo curCakeInCart CakeInCart curCakeInCart = new CakeInCart { CakeID = curCake.ID, Name = curCake.Name, Quantity = quantity, TotalCost = (long)(curCake.SellPrice * quantity), No = ++No_, InventoryNumber =(long)( CAKEs[index].InventoryNum - quantity), }; //Update CartDataGrid cakeInCarts.Add(curCakeInCart); CartDataGrid.ItemsSource = null; CartDataGrid.ItemsSource = cakeInCarts; //Update InvetoryNumber inventoryNumber.Text = (curCakeInCart.InventoryNumber == 0) ? "Hết hàng" : curCakeInCart.InventoryNumber.ToString(); CAKEs[index].InventoryNum -= quantity; //Update TotalCost UpdateTotalCost(); } catch (Exception ex) { if (ex.Message == "1"){ MessageBox.Show("Số lượng bánh phải lớn hơn 0", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } else if (ex.Message=="2"){ MessageBox.Show("Số lượng phải nhỏ hơn hoặc bằng lượng tồn kho", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } else{ MessageBox.Show("Số lượng bánh phải là chuỗi số", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } } } } private void StoreDataInput() { bool check = CheckDataInputError(); if (check == true) { OurCakeShopEntities database = new OurCakeShopEntities(); try { long orderId = _mainvm.GetORDERsCount(); //insert order ORDER curOrder = new ORDER { ID = orderId + 1, Status = "OS11", DateCompleted = DateTime.Now, TotalBill = this.TotalBill, BuyingMethod = STATUs[StatusComboBox.SelectedIndex].ID, CustomerName = customerName.Text, CustomerAddress = customerAddress.Text, CustomerPhone = customerPhoneNumber.Text, }; database.ORDERs.Add(curOrder); database.SaveChanges(); foreach (var detail in cakeInCarts) { ORDER_DETAIL cur = new ORDER_DETAIL { OrderID = orderId + 1, No_ = detail.No, ProductNum = detail.Quantity, ProductID = detail.CakeID, Price = detail.TotalCost, }; database.ORDER_DETAIL.Add(cur); _mainvm.UpdateInvetoryCake(detail.CakeID, detail.InventoryNumber); } database.SaveChanges(); MessageBox.Show("Tạo đơn hàng thành công", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { MessageBox.Show("Tạo đơn hàng không thành công\n Vui lòng thử lại", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } } } private void RefreshDataInput() { //Refresh customer frame customerName.Text = ""; customerAddress.Text = ""; customerPhoneNumber.Text = ""; StatusComboBox.SelectedIndex = -1; //Refresh cart frame cakeName.Text = ""; cakeQuantity.Text = ""; CartCost.Text = "0 VNĐ"; CartDataGrid.ItemsSource = null; inventoryNumber.Text = null; //Refresh cakeList frame CategoryComboBox.ItemsSource = null; CakeListView.ItemsSource = null; } private bool CheckDataInputError() { bool result = true; // - Check Cart Info // + Check số lượng bánh trong đơn hàng ko rỗng if (cakeInCarts.Count() == 0) { result = false; MessageBox.Show("Bạn chưa chọn bánh cho đơn hàng hiện tại", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } // - Check Customer Info // + Check nhập đủ thông tin hay không else if (customerName.Text == "") { result = false; MessageBox.Show("Bạn chưa nhập tên khách hàng", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } else if (StatusComboBox.SelectedIndex == -1) { result = false; MessageBox.Show("Bạn chưa chọn hình thức giao hàng", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); } return result; } private void CategoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { int index = CategoryComboBox.SelectedIndex; if (index != 0 && index != -1)// không phải lựa chọn tất cả { long id = CATEGORies[index].ID; CAKEs = _mainvm.GetCAKEs(id); CakeListView.ItemsSource = CAKEs; } else if (index == 0 && index != -1) { CAKEs = _mainvm.GetCAKEs(); CakeListView.ItemsSource = CAKEs; } } private void CakeListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { int index = CakeListView.SelectedIndex; if (index != -1) { cakeName.Text = CAKEs[index].Name; int num = 1; cakeQuantity.Text = num.ToString(); inventoryNumber.Text = CAKEs[index].InventoryNum.ToString(); } } private void UpQuantity_Click(object sender, RoutedEventArgs e) { bool check = true; long quantity; try { quantity = long.Parse(cakeQuantity.Text.ToString()); if (quantity < 0) throw new Exception("error"); } catch (Exception ex) { check = false; quantity = 1; } if (check == true) { quantity++; } cakeQuantity.Text = quantity.ToString(); } private void ReceivedMoney_SelectionChanged(object sender, RoutedEventArgs e) { CalculateMoney(); } private void ShippingFee_SelectionChanged(object sender, RoutedEventArgs e) { CalculateMoney(); } private void StatusComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (StatusComboBox.SelectedIndex != -1) { STATUS cur = StatusComboBox.SelectedItem as STATUS; if (cur.ID == "OBM01")//mua hàng trực tiếp { moneyCalculationFrame.Visibility = Visibility.Visible; ShippingFee.Visibility = Visibility.Collapsed; } if (cur.ID == "OBM02")//mua hàng online { moneyCalculationFrame.Visibility = Visibility.Visible; ShippingFee.Visibility = Visibility.Visible; } } } private void DownQuantity_Click(object sender, RoutedEventArgs e) { bool check = true; long quantity; try { quantity = long.Parse(cakeQuantity.Text.ToString()); if (quantity < 2) throw new Exception("error"); } catch (Exception ex) { check = false; quantity = 1; } if (check == true) { quantity--; } cakeQuantity.Text = quantity.ToString(); } private void UpdateTotalCost() { if (cakeInCarts.Count != 0) { TotalBill = 0; foreach (var i in cakeInCarts) { if (i.TotalCost > 0) TotalBill += i.TotalCost; else return; } CalculateMoney(); CartCost.Text = TotalBill.ToString() + " VNĐ"; } } public void CalculateMoney() { long receivedMoney = 0; long shippingFee = 0; try { if (ReceivedMoney.Text != "") receivedMoney = long.Parse(ReceivedMoney.Text); if (ShippingFee.Text != "") shippingFee = long.Parse(ShippingFee.Text); if (receivedMoney < 0 || shippingFee < 0) throw new Exception("1"); long refundMoney = receivedMoney + shippingFee - TotalBill; RefundMoney.Text = refundMoney.ToString(); } catch (Exception ex) { MessageBox.Show("Số tiền bạn nhập vào không hợp lệ \n Là chuỗi số và lớn hơn 0", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); RefundMoney.Text = ""; ShippingFee.Text = ""; RefundMoney.Text = ""; } } private void ComeBack_Click(object sender, RoutedEventArgs e) { try { if (isOrderAdded == 0) // Không có order nào được tạo { App.mainWindow.mainContentFrame.Content = App.ordersPage; } else { App.ordersPage = new Orders(); App.mainWindow.mainContentFrame.Content = App.ordersPage; } } catch(Exception ex) { MessageBox.Show("Lỗi hiển thị giao diện", "Thông báo", MessageBoxButton.OK); } } } }
using Contoso.Forms.Configuration; using System.Collections.Generic; namespace Contoso.XPlatform.Flow.Settings.Screen { public abstract class ScreenSettingsBase { abstract public ViewType ViewType { get; } public IEnumerable<CommandButtonDescriptor> CommandButtons { get; set; } } }
using System; using System.Collections.Generic; using System.ServiceModel; using CallCenter.Common.DataContracts; using CallCenter.Server.Helper; namespace CallCenter.ServiceContracts.Services { [ServiceContract] [ServiceKnownType("GetKnownTypes", typeof(KnownTypesHelper))] public interface IChatService { [OperationContract] IEnumerable<IOperatorChatHistoryRecord> GetChatHistory(int agentId, DateTime fromDate, int count); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace ShellNamespace { public static partial class WindowsAPI { public const Int32 FILE_ATTRIBUTE_NORMAL = 0x80; public static Guid IID_IShellFolder = new Guid("000214E6-0000-0000-C000-000000000046"); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern Int32 SendMessage(IntPtr pWnd, UInt32 uMsg, UInt32 wParam, IntPtr lParam); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern Int32 SHGetDesktopFolder(ref IShellFolder ppshf); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttribs, out SHFILEINFO psfi, uint cbFileInfo, SHGFI uFlags); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SHGetFileInfo(IntPtr pIDL, uint dwFileAttributes, out SHFILEINFO psfi, uint cbFileInfo, SHGFI uFlags); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern Int32 SHGetSpecialFolderLocation(IntPtr hwndOwner, CSIDL nFolder, ref IntPtr ppidl); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr ILCombine(IntPtr pIDLParent, IntPtr pIDLChild); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr ILClone(IntPtr pidl); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern Int32 SHGetPathFromIDList(IntPtr pIDL, StringBuilder strPath); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern int SHGetFolderLocation(IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwReserved, out IntPtr ppidl); //[DllImport("shell32.dll")] //public static extern int SHGetDataFromIDList(IShellFolder psf, ref IntPtr pidl, SHGDFIL nFormat, IntPtr pv, int cb); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern int SHGetDataFromIDList(IShellFolder psf, IntPtr pidl, SHGDFIL nFormat, out WIN32_FIND_DATA pv, int cb); [DllImport("shell32.dll", EntryPoint = "#727")] public static extern int SHGetImageList(SHIL iImageList, ref Guid riid, out IntPtr ppv); //IMAGE LIST public static Guid IID_IImageList = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950"); public static Guid IID_IImageList2 = new Guid("192B9D83-50FC-457B-90A0-2B82A8B5DAE1"); [Flags] public enum SHIL { SHIL_JUMBO = 0x0004, SHIL_EXTRALARGE = 0x0002 } /* [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern uint SHGetDataFromIDList(IShellFolder psf, IntPtr pidl, SHGDFIL nFormat, out WIN32_FIND_DATA pv, int cb); */ /* public struct ITEMIDLIST { public SHITEMID mkid; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct SHITEMID { public ushort cb; // The size of identifier, in bytes, including cb itself. //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] [MarshalAs(UnmanagedType.LPStr)] public byte[] abID; // A variable-length item identifier. } */ [Flags()] public enum SHGDFIL : int { SHGDFIL_FINDDATA = 1, SHGDFIL_NETRESOURCE = 2, SHGDFIL_DESCRIPTIONID = 3 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct WIN32_FIND_DATA { public uint dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [Flags] public enum SHGDN : uint { SHGDN_NORMAL = 0x0000, // Default (display purpose) SHGDN_INFOLDER = 0x0001, // Displayed under a folder (relative) SHGDN_FOREDITING = 0x1000, // For in-place editing SHGDN_FORADDRESSBAR = 0x4000, // UI friendly parsing name (remove ugly stuff) SHGDN_FORPARSING = 0x8000, // Parsing name for ParseDisplayName() } [Flags] public enum SHCONTF : uint { SHCONTF_CHECKING_FOR_CHILDREN = 0x0010, SHCONTF_FOLDERS = 0x0020, // Only want folders enumerated (SFGAO_FOLDER) SHCONTF_NONFOLDERS = 0x0040, // Include non folders SHCONTF_INCLUDEHIDDEN = 0x0080, // Show items normally hidden SHCONTF_INIT_ON_FIRST_NEXT = 0x0100, // Allow EnumObject() to return before validating enum SHCONTF_NETPRINTERSRCH = 0x0200, // Hint that client is looking for printers SHCONTF_SHAREABLE = 0x0400, // Hint that client is looking sharable resources (remote shares) SHCONTF_STORAGE = 0x0800, // Include all items with accessible storage and their ancestors SHCONTF_NAVIGATION_ENUM = 0x01000, SHCONTF_FASTITEMS = 0x02000, SHCONTF_FLATLIST = 0x04000, SHCONTF_ENABLE_ASYNC = 0x08000, SHCONTF_INCLUDESUPERHIDDEN = 0x10000, } [Flags] public enum SFGAOF : uint { SFGAO_CANCOPY = 0x1, // Objects can be copied (DROPEFFECT_COPY) SFGAO_CANMOVE = 0x2, // Objects can be moved (DROPEFFECT_MOVE) SFGAO_CANLINK = 0x4, // Objects can be linked (DROPEFFECT_LINK) SFGAO_STORAGE = 0x00000008, // Supports BindToObject(IID_IStorage) SFGAO_CANRENAME = 0x00000010, // Objects can be renamed SFGAO_CANDELETE = 0x00000020, // Objects can be deleted SFGAO_HASPROPSHEET = 0x00000040, // Objects have property sheets SFGAO_DROPTARGET = 0x00000100, // Objects are drop target SFGAO_CAPABILITYMASK = 0x00000177, SFGAO_SYSTEM = 0x00001000, SFGAO_ENCRYPTED = 0x00002000, // Object is encrypted (use alt color) SFGAO_ISSLOW = 0x00004000, // 'Slow' object SFGAO_GHOSTED = 0x00008000, // Ghosted icon SFGAO_LINK = 0x00010000, // Shortcut (link) SFGAO_SHARE = 0x00020000, // Shared SFGAO_READONLY = 0x00040000, // Read-only SFGAO_HIDDEN = 0x00080000, // Hidden object SFGAO_DISPLAYATTRMASK = 0x000FC000, SFGAO_FILESYSANCESTOR = 0x10000000, // May contain children with SFGAO_FILESYSTEM SFGAO_FOLDER = 0x20000000, // Support BindToObject(IID_IShellFolder) SFGAO_FILESYSTEM = 0x40000000, // Is a win32 file system object (file/folder/root) SFGAO_HASSUBFOLDER = 0x80000000, // May contain children with SFGAO_FOLDER SFGAO_CONTENTSMASK = 0x80000000, SFGAO_VALIDATE = 0x01000000, // Invalidate cached information SFGAO_REMOVABLE = 0x02000000, // Is this removeable media? SFGAO_COMPRESSED = 0x04000000, // Object is compressed (use alt color) SFGAO_BROWSABLE = 0x08000000, // Supports IShellFolder, but only implements CreateViewObject() (non-folder view) SFGAO_NONENUMERATED = 0x00100000, // Is a non-enumerated object SFGAO_NEWCONTENT = 0x00200000, // Should show bold in explorer tree SFGAO_CANMONIKER = 0x00400000, // Defunct SFGAO_HASSTORAGE = 0x00400000, // Defunct SFGAO_STREAM = 0x00400000, // Supports BindToObject(IID_IStream) SFGAO_STORAGEANCESTOR = 0x00800000, // May contain children with SFGAO_STORAGE or SFGAO_STREAM SFGAO_STORAGECAPMASK = 0x70C50008, // For determining storage capabilities, ie for open/save semantics } [Flags] public enum STRRET : uint { STRRET_WSTR = 0, STRRET_OFFSET = 0x1, STRRET_CSTR = 0x2, } [Flags] public enum SHGFI { SHGFI_ICON = 0x000000100, SHGFI_DISPLAYNAME = 0x000000200, SHGFI_TYPENAME = 0x000000400, SHGFI_ATTRIBUTES = 0x000000800, SHGFI_ICONLOCATION = 0x000001000, SHGFI_EXETYPE = 0x000002000, SHGFI_SYSICONINDEX = 0x000004000, SHGFI_LINKOVERLAY = 0x000008000, SHGFI_SELECTED = 0x000010000, SHGFI_ATTR_SPECIFIED = 0x000020000, SHGFI_LARGEICON = 0x000000000, SHGFI_SMALLICON = 0x000000001, SHGFI_OPENICON = 0x000000002, SHGFI_SHELLICONSIZE = 0x000000004, SHGFI_PIDL = 0x000000008, SHGFI_USEFILEATTRIBUTES = 0x000000010, SHGFI_ADDOVERLAYS = 0x000000020, SHGFI_OVERLAYINDEX = 0x000000040 } /* [Flags] public enum SHGDNF : uint { SHGDN_NORMAL = 0, SHGDN_INFOLDER = 0x1, SHGDN_FOREDITING = 0x1000, SHGDN_FORADDRESSBAR = 0x4000, SHGDN_FORPARSING = 0x8000 } */ [Flags] public enum CSIDL : uint { CSIDL_DESKTOP = 0x0000, // <desktop> CSIDL_INTERNET = 0x0001, // Internet Explorer (icon on desktop) CSIDL_PROGRAMS = 0x0002, // Start Menu\Programs CSIDL_CONTROLS = 0x0003, // My Computer\Control Panel CSIDL_PRINTERS = 0x0004, // My Computer\Printers CSIDL_PERSONAL = 0x0005, // My Documents CSIDL_FAVORITES = 0x0006, // <user name>\Favorites CSIDL_STARTUP = 0x0007, // Start Menu\Programs\Startup CSIDL_RECENT = 0x0008, // <user name>\Recent CSIDL_SENDTO = 0x0009, // <user name>\SendTo CSIDL_BITBUCKET = 0x000a, // <desktop>\Recycle Bin CSIDL_STARTMENU = 0x000b, // <user name>\Start Menu CSIDL_MYDOCUMENTS = 0x000c, // logical "My Documents" desktop icon CSIDL_MYMUSIC = 0x000d, // "My Music" folder CSIDL_MYVIDEO = 0x000e, // "My Videos" folder CSIDL_DESKTOPDIRECTORY = 0x0010, // <user name>\Desktop CSIDL_DRIVES = 0x0011, // My Computer CSIDL_NETWORK = 0x0012, // Network Neighborhood (My Network Places) CSIDL_NETHOOD = 0x0013, // <user name>\nethood CSIDL_FONTS = 0x0014, // windows\fonts CSIDL_TEMPLATES = 0x0015, CSIDL_COMMON_STARTMENU = 0x0016, // All Users\Start Menu CSIDL_COMMON_PROGRAMS = 0X0017, // All Users\Start Menu\Programs CSIDL_COMMON_STARTUP = 0x0018, // All Users\Startup CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019, // All Users\Desktop CSIDL_APPDATA = 0x001a, // <user name>\Application Data CSIDL_PRINTHOOD = 0x001b, // <user name>\PrintHood CSIDL_LOCAL_APPDATA = 0x001c, // <user name>\Local Settings\Applicaiton Data (non roaming) CSIDL_ALTSTARTUP = 0x001d, // non localized startup CSIDL_COMMON_ALTSTARTUP = 0x001e, // non localized common startup CSIDL_COMMON_FAVORITES = 0x001f, CSIDL_INTERNET_CACHE = 0x0020, CSIDL_COOKIES = 0x0021, CSIDL_HISTORY = 0x0022, CSIDL_COMMON_APPDATA = 0x0023, // All Users\Application Data CSIDL_WINDOWS = 0x0024, // GetWindowsDirectory() CSIDL_SYSTEM = 0x0025, // GetSystemDirectory() CSIDL_PROGRAM_FILES = 0x0026, // C:\Program Files CSIDL_MYPICTURES = 0x0027, // C:\Program Files\My Pictures CSIDL_PROFILE = 0x0028, // USERPROFILE CSIDL_SYSTEMX86 = 0x0029, // x86 system directory on RISC CSIDL_PROGRAM_FILESX86 = 0x002a, // x86 C:\Program Files on RISC CSIDL_PROGRAM_FILES_COMMON = 0x002b, // C:\Program Files\Common CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c, // x86 Program Files\Common on RISC CSIDL_COMMON_TEMPLATES = 0x002d, // All Users\Templates CSIDL_COMMON_DOCUMENTS = 0x002e, // All Users\Documents CSIDL_COMMON_ADMINTOOLS = 0x002f, // All Users\Start Menu\Programs\Administrative Tools CSIDL_ADMINTOOLS = 0x0030, // <user name>\Start Menu\Programs\Administrative Tools CSIDL_CONNECTIONS = 0x0031, // Network and Dial-up Connections CSIDL_COMMON_MUSIC = 0x0035, // All Users\My Music CSIDL_COMMON_PICTURES = 0x0036, // All Users\My Pictures CSIDL_COMMON_VIDEO = 0x0037, // All Users\My Video CSIDL_CDBURN_AREA = 0x003b // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning } /* [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; } */ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct SHFILEINFO { public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; } /// <summary> /// managed equivalent of IShellFolder interface /// Pinvoke.net / Mod by Arik Poznanski - pooya parsa /// Msdn: http://msdn.microsoft.com/en-us/library/windows/desktop/bb775075(v=vs.85).aspx /// Pinvoke: http://pinvoke.net/default.aspx/Interfaces/IShellFolder.html /// </summary> [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("000214E6-0000-0000-C000-000000000046")] public interface IShellFolder { /// <summary> /// Translates a file object's or folder's display name into an item identifier list. /// Return value: error code, if any /// </summary> /// <param name="hwnd">Optional window handle</param> /// <param name="pbc">Optional bind context that controls the parsing operation. This parameter is normally set to NULL. </param> /// <param name="pszDisplayName">Null-terminated UNICODE string with the display name</param> /// <param name="pchEaten">Pointer to a ULONG value that receives the number of characters of the display name that was parsed.</param> /// <param name="ppidl"> Pointer to an ITEMIDLIST pointer that receives the item identifier list for the object.</param> /// <param name="pdwAttributes">Optional parameter that can be used to query for file attributes.this can be values from the SFGAO enum</param> //uint ParseDisplayName(IntPtr hwnd, IntPtr pbc, String pszDisplayName, out UInt32 pchEaten, out IntPtr ppidl, ref UInt32 pdwAttributes); uint ParseDisplayName(IntPtr hwnd, IntPtr pbc, String pszDisplayName, out UInt32 pchEaten, out IntPtr ppidl, ref SFGAOF pdwAttributes); /// <summary> ///Allows a client to determine the contents of a folder by creating an item identifier enumeration object and returning its IEnumIDList interface. ///Return value: error code, if any /// </summary> /// <param name="hwnd">If user input is required to perform the enumeration, this window handle should be used by the enumeration object as the parent window to take user input.</param> /// <param name="grfFlags">Flags indicating which items to include in the enumeration. For a list of possible values, see the SHCONTF enum. </param> /// <param name="ppenumIDList">Address that receives a pointer to the IEnumIDList interface of the enumeration object created by this method. </param> uint EnumObjects(IntPtr hwnd, SHCONTF grfFlags, out IEnumIDList ppenumIDList); //IEnumIDList EnumObjects(IntPtr hwnd, SHCONTF grfFlags); /// <summary> ///Retrieves an IShellFolder object for a subfolder. // Return value: error code, if any /// </summary> /// <param name="pidl">Address of an ITEMIDLIST structure (PIDL) that identifies the subfolder.</param> /// <param name="pbc">Optional address of an IBindCtx interface on a bind context object to be used during this operation.</param> /// <param name="riid">Identifier of the interface to return. </param> /// <param name="ppv">Address that receives the interface pointer.</param> uint BindToObject(IntPtr pidl, IntPtr pbc, [In]ref Guid riid, out IShellFolder ppv); /// <summary> /// Requests a pointer to an object's storage interface. /// Return value: error code, if any /// </summary> /// <param name="pidl">Address of an ITEMIDLIST structure that identifies the subfolder relative to its parent folder. </param> /// <param name="pbc">Optional address of an IBindCtx interface on a bind context object to be used during this operation.</param> /// <param name="riid">Interface identifier (IID) of the requested storage interface.</param> /// <param name="ppv"> Address that receives the interface pointer specified by riid.</param> uint BindToStorage(IntPtr pidl, IntPtr pbc, [In]ref Guid riid, out IntPtr ppv); /// <summary> /// Determines the relative order of two file objects or folders, given /// their item identifier lists. Return value: If this method is /// successful, the CODE field of the HRESULT contains one of the /// following values (the code can be retrived using the helper function /// GetHResultCode): Negative A negative return value indicates that the first item should precede the second (pidl1 < pidl2). //// ///Positive A positive return value indicates that the first item should ///follow the second (pidl1 > pidl2). Zero A return value of zero ///indicates that the two items are the same (pidl1 = pidl2). /// </summary> /// <param name="lParam">Value that specifies how the comparison should be performed. The lower Sixteen bits of lParam define the sorting rule. /// The upper sixteen bits of lParam are used for flags that modify the sorting rule. values can be from the SHCIDS enum /// </param> /// <param name="pidl1">Pointer to the first item's ITEMIDLIST structure.</param> /// <param name="pidl2"> Pointer to the second item's ITEMIDLIST structure.</param> /// <returns></returns> [PreserveSig] Int32 CompareIDs(Int32 lParam, IntPtr pidl1, IntPtr pidl2); /// <summary> /// Requests an object that can be used to obtain information from or interact /// with a folder object. /// Return value: error code, if any /// </summary> /// <param name="hwndOwner">Handle to the owner window.</param> /// <param name="riid">Identifier of the requested interface.</param> /// <param name="ppv">Address of a pointer to the requested interface. </param> uint CreateViewObject(IntPtr hwndOwner, [In] ref Guid riid, out IntPtr ppv); /// <summary> /// Retrieves the attributes of one or more file objects or subfolders. /// Return value: error code, if any /// </summary> /// <param name="cidl">Number of file objects from which to retrieve attributes. </param> /// <param name="apidl">Address of an array of pointers to ITEMIDLIST structures, each of which uniquely identifies a file object relative to the parent folder.</param> /// <param name="rgfInOut">Address of a single ULONG value that, on entry contains the attributes that the caller is /// requesting. On exit, this value contains the requested attributes that are common to all of the specified objects. this value can be from the SFGAO enum /// </param> uint GetAttributesOf(UInt32 cidl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]IntPtr[] apidl, ref SFGAOF rgfInOut); /// <summary> /// Retrieves an OLE interface that can be used to carry out actions on the /// specified file objects or folders. Return value: error code, if any /// </summary> /// <param name="hwndOwner">Handle to the owner window that the client should specify if it displays a dialog box or message box.</param> /// <param name="cidl">Number of file objects or subfolders specified in the apidl parameter. </param> /// <param name="apidl">Address of an array of pointers to ITEMIDLIST structures, each of which uniquely identifies a file object or subfolder relative to the parent folder.</param> /// <param name="riid">Identifier of the COM interface object to return.</param> /// <param name="rgfReserved"> Reserved. </param> /// <param name="ppv">Pointer to the requested interface.</param> uint GetUIObjectOf(IntPtr hwndOwner, UInt32 cidl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]IntPtr[] apidl, [In] ref Guid riid, UInt32 rgfReserved, out IntPtr ppv); /// <summary> /// Retrieves the display name for the specified file object or subfolder. /// Return value: error code, if any /// </summary> /// <param name="pidl">Address of an ITEMIDLIST structure (PIDL) that uniquely identifies the file object or subfolder relative to the parent folder. </param> /// <param name="uFlags">Flags used to request the type of display name to return. For a list of possible values. </param> /// <param name="pName"> Address of a STRRET structure in which to return the display name.</param> uint GetDisplayNameOf(IntPtr pidl, SHGDN uFlags, out STRRET pName); /// <summary> /// Sets the display name of a file object or subfolder, changing the item /// identifier in the process. /// Return value: error code, if any /// </summary> /// <param name="hwnd"> Handle to the owner window of any dialog or message boxes that the client displays.</param> /// <param name="pidl"> Pointer to an ITEMIDLIST structure that uniquely identifies the file object or subfolder relative to the parent folder. </param> /// <param name="pszName"> Pointer to a null-terminated string that specifies the new display name.</param> /// <param name="uFlags">Flags indicating the type of name specified by the lpszName parameter. For a list of possible values, see the description of the SHGNO enum.</param> /// <param name="ppidlOut"></param> uint SetNameOf(IntPtr hwnd, IntPtr pidl, String pszName, SHGDN uFlags, out IntPtr ppidlOut); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("000214F2-0000-0000-C000-000000000046")] public interface IEnumIDList { // Retrieves the specified number of item identifiers in the enumeration sequence and advances the current position by the number of items retrieved. /* [PreserveSig()] uint Next( uint celt, // Number of elements in the array pointed to by the rgelt parameter. out IntPtr rgelt, // Address of an array of ITEMIDLIST pointers that receives the item identifiers. The implementation must allocate these item identifiers using the Shell's allocator (retrieved by the SHGetMalloc function). // The calling application is responsible for freeing the item identifiers using the Shell's allocator. out Int32 pceltFetched // Address of a value that receives a count of the item identifiers actually returned in rgelt. The count can be smaller than the value specified in the celt parameter. This parameter can be NULL only if celt is one. ); */ [PreserveSig()] uint Next( uint celt, // Number of elements in the array pointed to by the rgelt parameter. [In(), Out(), MarshalAs(UnmanagedType.LPArray)] IntPtr[] rgelt, // Address of an array of ITEMIDLIST pointers that receives the item identifiers. The implementation must allocate these item identifiers using the Shell's allocator (retrieved by the SHGetMalloc function). // The calling application is responsible for freeing the item identifiers using the Shell's allocator. out Int32 pceltFetched // Address of a value that receives a count of the item identifiers actually returned in rgelt. The count can be smaller than the value specified in the celt parameter. This parameter can be NULL only if celt is one. ); // Skips over the specified number of elements in the enumeration sequence. [PreserveSig()] uint Skip( uint celt // Number of item identifiers to skip. ); // Returns to the beginning of the enumeration sequence. [PreserveSig()] uint Reset(); // Creates a new item enumeration object with the same contents and state as the current one. [PreserveSig()] uint Clone( out IEnumIDList ppenum // Address of a pointer to the new enumeration object. The calling application must eventually free the new object by calling its Release member function. ); /* [PreserveSig()] uint Next( uint celt, [In(), Out(), MarshalAs(UnmanagedType.LPArray)] IntPtr[] rgelt, out uint pceltFetched); IEnumIDList Clone(); */ } /// <summary> /// A standard OLE enumerator used by a client to determine the available search objects for a folder. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("0E700BE1-9DB6-11d1-A1CE-00C04FD75D13")] public interface IEnumExtraSearch { /// <summary> /// Used to request information on one or more search objects. /// </summary> /// <param name="celt">The number of search objects to be enumerated, starting from the current object. If celt is too large, the method should stop and return the actual number of search objects in pceltFetched.</param> /// <param name="rgelt">A pointer to an array of pceltFetched EXTRASEARCH structures containing information on the enumerated objects.</param> /// <param name="pceltFetched">The number of objects actually enumerated. This may be less than celt.</param> /// <returns>Returns S_OK if successful, or a COM-defined error code otherwise.</returns> [PreserveSig] int Next(uint celt, [MarshalAs(UnmanagedType.LPArray)] EXTRASEARCH[] rgelt, out uint pceltFetched); /// <summary> /// Skip a specified number of objects. /// </summary> /// <param name="celt">The number of objects to skip.</param> /// <returns>Returns S_OK if successful, or a COM-defined error code otherwise.</returns> [PreserveSig] int Skip(uint celt); /// <summary> /// Used to reset the enumeration index to zero. /// </summary> /// <returns>Returns S_OK if successful, or a COM-defined error code otherwise.</returns> [PreserveSig] int Reset(); /// <summary> /// Used to request a duplicate of the enumerator object to preserve its current state. /// </summary> /// <param name="ppenum">A pointer to the IEnumExtraSearch interface of a new enumerator object.</param> /// <returns>Returns S_OK if successful, or a COM-defined error code otherwise.</returns> [PreserveSig] int Clone(out IEnumExtraSearch ppenum); } /// <summary> /// Used by an IEnumExtraSearch enumerator object to return information on the search objects supported by a Shell Folder object. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct EXTRASEARCH { /// <summary> /// A search object's GUID. /// </summary> public Guid guidSearch; /// <summary> /// A Unicode string containing the search object's friendly name. It will be used to identify the search engine on the Search Assistant menu. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string wszFriendlyName; /// <summary> /// The URL that will be displayed in the search pane. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string wszUrl; } } }
/* * Copyright 2014 Technische Universitšt Darmstadt * * 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 * * http://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.Collections.Generic; using System.Linq; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Resolve; using JetBrains.ReSharper.Psi.Tree; using KaVE.Commons.Model.Naming; using KaVE.Commons.Model.Naming.CodeElements; using KaVE.Commons.Model.Naming.Types; using KaVE.Commons.Model.TypeShapes; using KaVE.Commons.Utils.Collections; using KaVE.RS.Commons.Utils.Naming; namespace KaVE.RS.Commons.Analysis { public class TypeShapeAnalysis { private ITypeElement _typeElement; public TypeShape Analyze(ITypeDeclaration typeDeclaration) { return Analyze(typeDeclaration.DeclaredElement); } public TypeShape Analyze(ITypeElement typeElement) { _typeElement = typeElement; return AnalyzeInternal(typeElement); } private TypeShape AnalyzeInternal(ITypeElement typeElement) { var typeShape = new TypeShape(); AddEventHierarchies(typeShape); AddDelegates(typeShape); AddFields(typeShape); AddMethodHierarchies(typeShape); AddNestedTypes(typeShape); AddPropertyHierarchies(typeShape); typeShape.TypeHierarchy = CreateTypeHierarchy( typeElement, EmptySubstitution.INSTANCE, Lists.NewList<ITypeName>(), false); return typeShape; } private void AddEventHierarchies(ITypeShape typeShape) { foreach (var e in FindImplementedEventsInType()) { var name = e.GetName<IEventName>(); var declaration = e.CollectDeclarationInfo<IEventName, EventHierarchy>(name); typeShape.EventHierarchies.Add(declaration); } } private void AddDelegates(ITypeShape typeShape) { var typeMembers = _typeElement.GetMembers(); var delegateTypeNames = typeMembers.OfType<IDelegate>() .Select(d => d.GetName<IDelegateTypeName>()); typeShape.Delegates.AddAll(delegateTypeNames); } private void AddFields(ITypeShape typeShape) { var typeMembers = _typeElement.GetMembers(); foreach (var typeMember in typeMembers) { var field = typeMember as IField; if (field != null) { var fieldName = field.GetName<IFieldName>(); if (field.IsEnumMember) { var shortName = field.ShortName; fieldName = Names.Field("[{0}] [{0}].{1}", fieldName.DeclaringType, shortName); } typeShape.Fields.Add(fieldName); } } } private void AddNestedTypes(ITypeShape typeShape) { foreach (var typeElement in _typeElement.NestedTypes) { if (typeElement is IDelegate) { continue; } var type = typeElement.GetName<ITypeName>(); typeShape.NestedTypes.Add(type); } } private void AddMethodHierarchies(ITypeShape typeShape) { foreach (var m in FindImplementedConstructorsInType()) { var name = m.GetName<IMethodName>(); typeShape.MethodHierarchies.Add(new MethodHierarchy {Element = name}); } foreach (var m in FindImplementedMethodsInType()) { var name = m.GetName<IMethodName>(); var declaration = m.CollectDeclarationInfo<IMethodName, MethodHierarchy>(name); typeShape.MethodHierarchies.Add(declaration); } } private void AddPropertyHierarchies(ITypeShape typeShape) { foreach (var p in FindImplementedPropertiesInType()) { var name = p.GetName<IPropertyName>(); var declaration = p.CollectDeclarationInfo<IPropertyName, PropertyHierarchy>(name); typeShape.PropertyHierarchies.Add(declaration); } } private IEnumerable<IConstructor> FindImplementedConstructorsInType() { var ctors = new HashSet<IConstructor>(); if (_typeElement != null) { foreach (var ctor in _typeElement.Constructors) { if (!ctor.IsImplicit) { ctors.Add(ctor); } } } return ctors; } private IEnumerable<IMethod> FindImplementedMethodsInType() { return _typeElement != null ? _typeElement.Methods : new HashSet<IMethod>(); } private IEnumerable<IEvent> FindImplementedEventsInType() { return _typeElement != null ? _typeElement.Events : new HashSet<IEvent>(); } private IEnumerable<IProperty> FindImplementedPropertiesInType() { return _typeElement != null ? _typeElement.Properties : new HashSet<IProperty>(); } private static TypeHierarchy CreateTypeHierarchy(ITypeElement type, ISubstitution substitution, IKaVEList<ITypeName> seenTypes, bool shouldIgnoreRootTypes) { if (shouldIgnoreRootTypes && (type == null || IsRootType(type))) { // ignore implicite extensions in type hierarchy return null; } var typeName = type.GetName<ITypeName>(substitution); seenTypes.Add(typeName); var enclosingClassHierarchy = new TypeHierarchy(typeName.Identifier); foreach (var superType in type.GetSuperTypes()) { var resolveResult = superType.Resolve(); var declElem = resolveResult.DeclaredElement; var isUnresolvedAlias = declElem is IUsingAliasDirective; // TODO NameUpdate: "isUnknownOrUnResolvedUntested" required by one analyzed solution, still untested var isUnknownOrUnResolvedUntested = superType.IsUnknown || !superType.IsResolved; if (!resolveResult.IsValid() || declElem == null || isUnresolvedAlias || isUnknownOrUnResolvedUntested) { enclosingClassHierarchy.Implements.Add(new TypeHierarchy()); continue; } var superName = declElem.GetName<ITypeName>(substitution); if (seenTypes.Contains(superName)) { continue; } var superTypeElement = superType.GetTypeElement(); var superTypeSubstitution = superType.GetSubstitution(); var superHierarchy = CreateTypeHierarchy(superTypeElement, superTypeSubstitution, seenTypes, true); if (declElem is IClass || declElem is IStruct) { enclosingClassHierarchy.Extends = superHierarchy; } else if (declElem is IInterface) { enclosingClassHierarchy.Implements.Add(superHierarchy); } } return enclosingClassHierarchy; } private static bool IsRootType(ITypeElement type) { var fn = type.GetClrName().FullName; return "System.Object".Equals(fn) || "System.ValueType".Equals(fn) || "System.Enum".Equals(fn); } } }
using AutoMapper; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Whale.DAL; using Whale.DAL.Models; using Whale.DAL.Settings; using Whale.Shared.Exceptions; using Whale.Shared.Extentions; using Whale.Shared.Models; using Whale.Shared.Models.User; using Whale.Shared.Services.Abstract; namespace Whale.Shared.Services { public class UserService : BaseService { private readonly BlobStorageSettings _blobStorageSettings; private readonly RedisService _redisService; private const string onlineUsersKey = "online"; public UserService( WhaleDbContext context, IMapper mapper, BlobStorageSettings blobStorageSettings, RedisService redisService ) : base(context, mapper) { _blobStorageSettings = blobStorageSettings; _redisService = redisService; } public async Task<IEnumerable<UserDTO>> GetAllUsersAsync() { var users = await _context.Users.ToListAsync(); await users.LoadAvatarsAsync(_blobStorageSettings); return users.Select(u => { var user = _mapper.Map<UserDTO>(u); var userData = GetConnectionData(user.Id); user.ConnectionId = userData?.ConnectionId; user.IsSpeaking = userData?.IsSpeaking ?? false; return user; }); } public async Task<UserDTO> GetUserAsync(Guid userId) { var user = await _context.Users .FirstOrDefaultAsync(c => c.Id == userId); if (user == null) throw new NotFoundException("User", userId.ToString()); await user.LoadAvatarAsync(_blobStorageSettings); var userDto = _mapper.Map<UserDTO>(user); var userData = GetConnectionData(user.Id); userDto.ConnectionId = userData?.ConnectionId; userDto.IsSpeaking = userData?.IsSpeaking ?? false; return userDto; } public async Task<UserDTO> GetUserByEmailAsync(string email) { var user = await _context.Users.FirstOrDefaultAsync(e => e.Email == email); if (user == null) throw new NotFoundException("User", email); await user.LoadAvatarAsync(_blobStorageSettings); var userDto = _mapper.Map<UserDTO>(user); var userData = GetConnectionData(user.Id); userDto.ConnectionId = userData?.ConnectionId; userDto.IsSpeaking = userData?.IsSpeaking ?? false; return userDto; } public async Task<UserDTO> CreateUserAsync(UserCreateDTO userDTO) { var entity = _mapper.Map<User>(userDTO); var user = _context.Users.FirstOrDefault(c => c.Email == userDTO.Email); if (user != null) throw new AlreadyExistsException("User", userDTO.Email); _context.Users.Add(entity); await _context.SaveChangesAsync(); var createdUser = await _context.Users .FirstAsync(c => c.Id == entity.Id); return _mapper.Map<UserDTO>(createdUser); } public async Task<UserDTO> CreateUser(UserModel user) { var checkUser = _context.Users.Where(e => e.Email == user.Email); if (checkUser.Count() > 0) throw new AlreadyExistsException("User", user.Email); var newUser = _mapper.Map<User>(user); var name = user.DisplayName .Split(' ') .Select(e => e.Trim()) .ToList(); newUser.FirstName = name[0]; newUser.SecondName = name?.Count() > 1 ? name[1] : null; await _context.Users.AddAsync(newUser); await _context.SaveChangesAsync(); return _mapper.Map<UserDTO>(newUser); } public async Task<UserDTO> UpdateUserAsync(UserDTO userDTO) { var entity = _context.Users.FirstOrDefault(c => c.Id == userDTO.Id); if (entity == null) throw new NotFoundException("User", userDTO.Id.ToString()); entity.FirstName = userDTO.FirstName; entity.SecondName = userDTO.SecondName; entity.Phone = userDTO.Phone; entity.AvatarUrl = userDTO.AvatarUrl; entity.LinkType = userDTO.LinkType; _context.Users.Update(entity); await _context.SaveChangesAsync(); return await GetUserAsync(entity.Id); } public async Task<bool> DeleteUserAsync(Guid userId, string userEmail) { var user = _context.Users.FirstOrDefault(c => c.Id == userId); if (user == null) throw new NotFoundException("User", userId.ToString()); if (user.Email != userEmail) throw new InvalidCredentialsException(); _context.Users.Remove(user); await _context.SaveChangesAsync(); return true; } private UserOnlineDTO GetConnectionData(Guid userId) { _redisService.Connect(); try { var onlineUsers = _redisService.Get<ICollection<UserOnlineDTO>>(onlineUsersKey); var userOnline = onlineUsers.FirstOrDefault(u => u.Id == userId); return userOnline; } catch (Exception) { return null; } } } }
using System; namespace filter.framework.core.Db { /// <summary> /// 主键 /// </summary> [AttributeUsage(AttributeTargets.Property)] public class PrimaryKeyAttribute : Attribute { } }