text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackusingArray { internal class Stack { static readonly int max = 1000; int top; int[] stk = new int[max]; bool IsEmpty() { return (top < 0); } public Stack() { top = -1; } internal bool Push(int data) { if(top>=max) { Console.WriteLine("Stack Overflow"); return false; } else { stk[++top] = data; return true; } } internal int Pop() { if(top<0) { Console.WriteLine("Stack Underflow"); return 0; } else { int value = stk[top--]; return value; } } internal void Peek() { if(top<0) { Console.WriteLine("Stack Underflow"); return; } else { Console.WriteLine("The topmost element of stack is :{0}", stk[top]); } } internal void PrintStack() { if(top<0) { Console.WriteLine("Stack Underflow"); return; } else { Console.WriteLine("Items in the stack are:"); for ( int i = top; i >= 0; i--) { Console.WriteLine(stk[i]); } } } } class Program { static void Main(string[] args) { Stack myStack = new Stack(); myStack.Push(10); myStack.Push(30); myStack.Push(50); myStack.Push(70); myStack.PrintStack(); myStack.Peek(); Console.WriteLine("Item popped from stack: {0}", myStack.Pop()); myStack.PrintStack(); Console.ReadLine(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace UMA { public abstract class TextureProcessBaseCoroutine : WorkerCoroutine { public abstract void Prepare(UMAData _umaData, UMAGeneratorBase _umaGenerator); } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("GamesWonSegment")] public class GamesWonSegment : MonoClass { public GamesWonSegment(IntPtr address) : this(address, "GamesWonSegment") { } public GamesWonSegment(IntPtr address, string className) : base(address, className) { } public void AnimateReward() { base.method_8("AnimateReward", Array.Empty<object>()); } public float GetWidth() { return base.method_11<float>("GetWidth", Array.Empty<object>()); } public void Hide() { base.method_8("Hide", Array.Empty<object>()); } public void Init(Reward.Type rewardType, int rewardAmount, bool hideCrown) { object[] objArray1 = new object[] { rewardType, rewardAmount, hideCrown }; base.method_8("Init", objArray1); } public GamesWonCrown m_crown { get { return base.method_3<GamesWonCrown>("m_crown"); } } public GameObject m_root { get { return base.method_3<GameObject>("m_root"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace ReadingWritingFile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\TestFile.txt"; private void btnFile_Click(object sender, EventArgs e) { if (ofd.ShowDialog() == DialogResult.OK) { string path = ofd.FileName; textBox1.Text = File.ReadAllText(path); } } private void btnWrite_Click(object sender, EventArgs e) { //check if file exists if (!File.Exists(desktop)) { File.Create(desktop).Close(); } //write data to file File.WriteAllText(desktop, textBox1.Text); } private void btnFileStream_Click(object sender, EventArgs e) { StreamWriter writer = new StreamWriter(desktop); writer.Write(textBox1.Text); writer.Close(); } private void btnReadFileStream_Click(object sender, EventArgs e) { if (File.Exists(desktop)) { StreamReader reader = new StreamReader(desktop); // while (!reader.EndOfStream) // { // textBox1.AppendText(reader.ReadLine() + "\n"); // } while (!reader.EndOfStream) { textBox1.Text = ((char)reader.Read()).ToString(); } reader.Close(); } else { MessageBox.Show("File not found"); } } private void btnWriteFileStream_Click(object sender, EventArgs e) { FileStream stream = new FileStream(desktop, FileMode.Create, FileAccess.Write); byte[] outBytes = Encoding.UTF8.GetBytes(textBox1.Text); stream.Write(outBytes, 0, outBytes.Length); stream.Close(); } private void btnReadFileStram2_Click(object sender, EventArgs e) { FileStream stream = new FileStream(desktop, FileMode.Open, FileAccess.Read); byte[] outBytes = new byte[stream.Length]; stream.Read(outBytes, 0, outBytes.Length); textBox1.Text = Encoding.UTF8.GetString(outBytes); stream.Close(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using HtmlAgilityPack; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Shared.Models; namespace Api.Client { public class RecreatievoetbalClient { //In this case we are encapsulating the HttpClient, //but it could be exposed if that is desired. private HttpClient _client; private ILogger<RecreatievoetbalClient> _logger; private static CultureInfo _dutchCulture = new CultureInfo("nl-NL"); private static CultureInfo _englishCulture = new CultureInfo("en-US"); public RecreatievoetbalClient(HttpClient client, ILogger<RecreatievoetbalClient> logger) { _client = client; _logger = logger; } public async Task<List<Team>> AddTeamsToLeague(List<League> leagues) { var html = @"https://www.recreatievoetbal.nl/teams"; var web = new HtmlWeb(); var htmlDoc = await web.LoadFromWebAsync(html); var table = htmlDoc.DocumentNode.SelectNodes(@"//table[@id='teamtable']//tr"); var teams = new List<Team>(); foreach (var tr in table.Skip(1)) { try { var teamName = tr.SelectSingleNode("td/div[@class='Team_name']").InnerText; if (teamName == "n.n.b.") { continue; } var leagueType = Enum.Parse<LeagueType>(tr .SelectSingleNode( "td/select[@class='Team_League selectblue']/option[@selected='selected']") ? .GetAttributeValue("value", "true")); var team = new Team { TeamId = int.Parse(tr.GetAttributeValue("data-team_id", "")), LeagueType = leagueType, Name = ReplaceSpecialChars(teamName), ColorShirt = tr.SelectSingleNode("td/div[@class='Team_shirtColor']").InnerText, ColorShort = tr.SelectSingleNode("td/div[@class='Team_shortsColor']").InnerText, TeamPictureUrl = tr.SelectSingleNode("td/div[@id='Team_foto1']/img") ?.GetAttributeValue("src", ""), }; teams.Add(team); } catch (Exception ex) { } } return teams; } public async Task<List<League>> GetLeagues(List<League> leagues) { var html = @"https://www.recreatievoetbal.nl"; var web = new HtmlWeb(); var htmlDoc = await web.LoadFromWebAsync(html); var table = htmlDoc.DocumentNode.SelectNodes(@"//div[@id='rzv_balls']//a"); foreach (var leagueAnchor in table) { try { var leagueCode = leagueAnchor?.GetAttributeValue("href", ""); var leagueType = leagueCode == "bekercup" ? LeagueType.Cup : Enum.Parse<LeagueType>(leagueCode?.Substring(leagueCode.Length - 1, 1)); if (leagues.Any(l => l.Type == leagueType)) { continue; } leagues.Add(new League { LogoUrl = leagueAnchor?.SelectSingleNode("img")?.GetAttributeValue("src", ""), Type = leagueType }); } catch (Exception ex) { } } leagues.Add(new League { Type = LeagueType.X }); return leagues; } private static Regex _PouleLineRegex = new Regex( @"Poule:\s(?<league>[A-Z]*).*Locatie:\s(?<location>\w*).*Datum:\s(?<date>\d{2}\s\w*\s\d{4}).*Team zaaldienst:\s(?<service>[^<]*)"); private static Regex _GameToPlayLineRegex = new Regex( @"data-match-id=""\\""(?<matchId>[\d]*).*<td>(?<time>[^<]*).*<td>(?<teamhome>.*)\s-\s(?<teamaway>[^<]*)"); private static Regex _GamePlayedLineRegex = new Regex( @"data-match-id=""\\""(?<matchId>[\d]*).*<td>(?<time>[^<]*).*\\""teamsplayed\\"""">(?<teamhome>.*)\s-\s(?<teamaway>[^<]*).*<td>(?<teamhomescore>[0-9]*)\s-\s(?<teamawayscore>[0-9]*)"); public async Task<List<Game>> GetGamesToPlay(List<League> leagues, List<Team> teams) { var client = new HttpClient(); client.BaseAddress = new Uri("https://www.recreatievoetbal.nl/programma"); var request = new HttpRequestMessage(HttpMethod.Post, "?"); var keyValues = new List<KeyValuePair<string, string>>(); keyValues.Add(new KeyValuePair<string, string>("getMatchesToPlay", "1")); request.Content = new FormUrlEncodedContent(keyValues); var response = await client.SendAsync(request); var tableString = await response.Content.ReadAsStringAsync(); var doc = new HtmlDocument(); doc.LoadHtml(tableString.Replace("{\"matchesToPlayRows\":[\"\")", "").Replace("}", "")); var tableRows = doc.DocumentNode.Descendants("tr").ToList(); var games = new List<Game>(); string location = null; DateTime? date = null; Team serviceTeam = null; League league = null; foreach (var tr in tableRows) { var match = _PouleLineRegex.Match(tr.InnerText); if (match.Groups.Count > 1) { var leagueString = match.Groups["league"].Value.Replace("BEKER", "Cup"); LeagueType leagueType; if (!Enum.TryParse<LeagueType>(leagueString, out leagueType)) { continue; } date = DateTime.ParseExact(match.Groups["date"].Value, "dd MMMM yyyy", _dutchCulture); location = match.Groups["location"].Value; var serviceTeamName = ReplaceSpecialChars(match.Groups["service"].Value); serviceTeam = teams.FirstOrDefault(t => t.Name == serviceTeamName); league = leagues.First(l => l.Type == leagueType); } else { var gameMatch = _GameToPlayLineRegex.Match(tr.OuterHtml); if (gameMatch.Groups.Count == 1) { continue; } var homeTeam = ReplaceSpecialChars(gameMatch.Groups["teamhome"].Value); var guestTeam = ReplaceSpecialChars(gameMatch.Groups["teamaway"].Value); try { var time = TimeSpan.Parse(gameMatch.Groups["time"].Value.ToString()); games.Add(new Game { MatchId = int.Parse(gameMatch.Groups["matchId"].Value), League = league, DateTime = new DateTime(date.Value.Ticks).AddHours(time.Hours).AddMinutes(time.Minutes), Location = location, HallServiceTeamId = serviceTeam.TeamId, HomeScore = null, GuestScore = null, HomeTeamTeamId = teams.FirstOrDefault(t => t.Name == homeTeam)?.TeamId, GuestTeamTeamId = teams.FirstOrDefault(t => t.Name == guestTeam)?.TeamId }); } catch (Exception ex) { _logger.LogError("Error while parsing game to play" + ex); } } } return games; } private string ReplaceSpecialChars(string value) { return value.Replace("\\u00a0", " ").Replace(Convert.ToChar(160), ' ').Replace("\\u00e9", "é") .Replace(@"\/", "/"); } public async Task<List<Game>> AddGamesPlayed(List<League> leagues, List<Team> teams) { var client = new HttpClient(); client.BaseAddress = new Uri("https://www.recreatievoetbal.nl/programma"); var request = new HttpRequestMessage(HttpMethod.Post, "?"); var keyValues = new List<KeyValuePair<string, string>>(); keyValues.Add(new KeyValuePair<string, string>("getMatchesPlayed", "1")); keyValues.Add(new KeyValuePair<string, string>("seizoen_id", "7")); request.Content = new FormUrlEncodedContent(keyValues); var response = await client.SendAsync(request); var tableString = await response.Content.ReadAsStringAsync(); var doc = new HtmlDocument(); doc.LoadHtml(tableString.Replace("{\"matchesPlayedRows\":[\"\")", "").Replace("}", "")); var tableRows = doc.DocumentNode.Descendants("tr").ToList(); var games = new List<Game>(); string location = null; DateTime? date = null; Team serviceTeam = null; League league = null; foreach (var tr in tableRows) { var match = _PouleLineRegex.Match(tr.InnerText); if (match.Groups.Count > 1) { var leagueString = match.Groups["league"].Value.Replace("BEKER", "Cup"); LeagueType leagueType; if (!Enum.TryParse<LeagueType>(leagueString, out leagueType)) { continue; } date = DateTime.ParseExact(match.Groups["date"].Value, "dd MMM yyyy", _englishCulture); location = match.Groups["location"].Value; var serviceTeamName = ReplaceSpecialChars(match.Groups["service"].Value); serviceTeam = teams.FirstOrDefault(t => t.Name == serviceTeamName); league = leagues.First(l => l.Type == leagueType); } else { var gameMatch = _GamePlayedLineRegex.Match(tr.OuterHtml); if (gameMatch.Groups.Count == 1) { continue; } var homeTeam = ReplaceSpecialChars(gameMatch.Groups["teamhome"].Value); var guestTeam = ReplaceSpecialChars(gameMatch.Groups["teamaway"].Value); try { var time = TimeSpan.Parse(gameMatch.Groups["time"].Value.ToString()); games.Add(new Game { League = league, MatchId = int.Parse(gameMatch.Groups["matchId"].Value), DateTime = new DateTime(date.Value.Ticks).AddHours(time.Hours).AddMinutes(time.Minutes), Location = location, HallServiceTeamId = serviceTeam.TeamId, HomeScore = int.Parse(gameMatch.Groups["teamhomescore"].Value), GuestScore = int.Parse(gameMatch.Groups["teamawayscore"].Value), HomeTeamTeamId = teams.First(t => t.Name == homeTeam).TeamId, GuestTeamTeamId = teams.First(t => t.Name == guestTeam).TeamId }); } catch (Exception ex) { _logger.LogError("Error while parsing game played" + ex); } } } return games; } private static Regex _JsonRegex = new Regex(@"(?<json>\{.*\})"); private static Regex _GameEventRegex = new Regex( @"data-wedstrijd_id=""(?<eventId>\d*).*<td>(?<minute>\d*).*<td><!-- Single button -->(?<typeEvent>[A-Z]{2}).*<td>(?<player>.*)\t<\/td><\/tr>"); public async Task<Game> AddGameEvents(Game game) { var client = new HttpClient {BaseAddress = new Uri("https://www.recreatievoetbal.nl/programma")}; var request = new HttpRequestMessage(HttpMethod.Post, "?"); var keyValues = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("matchID", game.MatchId.ToString()), new KeyValuePair<string, string>("getMatchPlayedDetail", "1") }; request.Content = new FormUrlEncodedContent(keyValues); var response = await client.SendAsync(request); try { var resultString = await response.Content.ReadAsStringAsync(); var json = _JsonRegex.Match(resultString.Replace(Environment.NewLine, "")).Groups["json"].Value; var match = JsonConvert.DeserializeObject<RecreatievoetbalMatch>(json); game.Referee = match.Scheidsrechter1; game.Official = match.Official1; game.EHBO1 = match.EHBO1; game.Remark = match.matchRemarks; game.DetailsLastUpdate = DateTime.Now; var scores = match.matchResults.Split('-'); game.HomeScore = int.Parse(scores[0]); game.GuestScore = int.Parse(scores[1]); foreach (var matchEventRow in match.matcheventRows) { var regexMatch = _GameEventRegex.Match(matchEventRow); if (regexMatch.Groups.Count > 1) { game.Events.Add(new GameEvent { Minute = int.Parse(regexMatch.Groups["minute"].Value), Type = ConvertToGameEventType(regexMatch.Groups["typeEvent"].Value), PlayerName = regexMatch.Groups["player"].Value }); } } } catch (Exception ex) { var x = await response.Content.ReadAsStringAsync(); Console.WriteLine(x); } return game; } private GameEvent.GameEventType ConvertToGameEventType(string value) { switch (value) { case "DP": return GameEvent.GameEventType.Goal; case "GK": return GameEvent.GameEventType.YellowCard; case "GK2": return GameEvent.GameEventType.YellowCard; case "RK": return GameEvent.GameEventType.RedCard; case "ED": return GameEvent.GameEventType.OwnGoal; case "P": return GameEvent.GameEventType.Penalty; default: throw new Exception($"Waarde {value} niet bekend"); } } } public class RecreatievoetbalMatch { public RecreatievoetbalMatch() { } public string team1Name { get; set; } public string team2Name { get; set; } public string matchResults { get; set; } public string matchRemarks { get; set; } public string Scheidsrechter1 { get; set; } public string Official1 { get; set; } public string EHBO1 { get; set; } public string ZaalDienstTeam { get; set; } public List<string> matcheventRows { get; set; } } }
using AppDuoXF.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace AppDuoXF.Interfaces { public interface ILessonService { Task<List<LessonGroup>> GetLessonsGroup(); } }
using System; using System.IO; using System.Threading.Tasks; using System.Windows.Media.Imaging; namespace Kit.WPF.Controls.CrossImage { public class CrossImageExtensions : Kit.Controls.CrossImage.CrossImageExtensions { public override Kit.Controls.CrossImage.CrossImage FromFile(FileInfo fileInfo) { Kit.WPF.Controls.CrossImage.CrossImage image = new Kit.WPF.Controls.CrossImage.CrossImage(); image.Native = new BitmapImage(new Uri(fileInfo.FullName)); return image; } public override Kit.Controls.CrossImage.CrossImage FromStream(Func<Stream> stream) { Kit.WPF.Controls.CrossImage.CrossImage image = new Kit.WPF.Controls.CrossImage.CrossImage(); //System.Windows.Controls.Image wimage = new System.Windows.Controls.Image(); using (MemoryStream mstream = (MemoryStream)stream.Invoke()) { if (mstream != null) image.Native = BitmapFrame.Create(mstream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); //wimage.Source = (BitmapFrame)image.Native; } //Window w = new Window(); //w.Content = wimage; //w.ShowDialog(); return image; } public override Task<byte[]> GetByteArray(Kit.Controls.CrossImage.CrossImage CrossImage) { throw new NotImplementedException(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: yadel_controller.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Org.Roylance.Yadel { /// <summary>Holder for reflection information generated from yadel_controller.proto</summary> public static partial class YadelControllerReflection { #region Descriptor /// <summary>File descriptor for yadel_controller.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static YadelControllerReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZ5YWRlbF9jb250cm9sbGVyLnByb3RvEhJvcmcucm95bGFuY2UueWFkZWwa", "EnlhZGVsX3JlcG9ydC5wcm90byJ6CgxDb21tb25BY3Rpb24SMwoHcmVxdWVz", "dBgBIAEoCzIiLm9yZy5yb3lsYW5jZS55YWRlbC5VSVlhZGVsUmVxdWVzdBI1", "CghyZXNwb25zZRgCIAEoCzIjLm9yZy5yb3lsYW5jZS55YWRlbC5VSVlhZGVs", "UmVzcG9uc2UitQEKEFJlcG9ydENvbnRyb2xsZXISNAoKZGVsZXRlX2RhZxgB", "IAEoCzIgLm9yZy5yb3lsYW5jZS55YWRlbC5Db21tb25BY3Rpb24SMQoHY3Vy", "cmVudBgCIAEoCzIgLm9yZy5yb3lsYW5jZS55YWRlbC5Db21tb25BY3Rpb24S", "OAoOZ2V0X2RhZ19zdGF0dXMYAyABKAsyIC5vcmcucm95bGFuY2UueWFkZWwu", "Q29tbW9uQWN0aW9uYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Org.Roylance.Yadel.YadelReportReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Org.Roylance.Yadel.CommonAction), global::Org.Roylance.Yadel.CommonAction.Parser, new[]{ "Request", "Response" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Org.Roylance.Yadel.ReportController), global::Org.Roylance.Yadel.ReportController.Parser, new[]{ "DeleteDag", "Current", "GetDagStatus" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CommonAction : pb::IMessage<CommonAction> { private static readonly pb::MessageParser<CommonAction> _parser = new pb::MessageParser<CommonAction>(() => new CommonAction()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CommonAction> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Org.Roylance.Yadel.YadelControllerReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CommonAction() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CommonAction(CommonAction other) : this() { Request = other.request_ != null ? other.Request.Clone() : null; Response = other.response_ != null ? other.Response.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CommonAction Clone() { return new CommonAction(this); } /// <summary>Field number for the "request" field.</summary> public const int RequestFieldNumber = 1; private global::Org.Roylance.Yadel.UIYadelRequest request_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Org.Roylance.Yadel.UIYadelRequest Request { get { return request_; } set { request_ = value; } } /// <summary>Field number for the "response" field.</summary> public const int ResponseFieldNumber = 2; private global::Org.Roylance.Yadel.UIYadelResponse response_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Org.Roylance.Yadel.UIYadelResponse Response { get { return response_; } set { response_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CommonAction); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CommonAction other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Request, other.Request)) return false; if (!object.Equals(Response, other.Response)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (request_ != null) hash ^= Request.GetHashCode(); if (response_ != null) hash ^= Response.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (request_ != null) { output.WriteRawTag(10); output.WriteMessage(Request); } if (response_ != null) { output.WriteRawTag(18); output.WriteMessage(Response); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (request_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Request); } if (response_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Response); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CommonAction other) { if (other == null) { return; } if (other.request_ != null) { if (request_ == null) { request_ = new global::Org.Roylance.Yadel.UIYadelRequest(); } Request.MergeFrom(other.Request); } if (other.response_ != null) { if (response_ == null) { response_ = new global::Org.Roylance.Yadel.UIYadelResponse(); } Response.MergeFrom(other.Response); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (request_ == null) { request_ = new global::Org.Roylance.Yadel.UIYadelRequest(); } input.ReadMessage(request_); break; } case 18: { if (response_ == null) { response_ = new global::Org.Roylance.Yadel.UIYadelResponse(); } input.ReadMessage(response_); break; } } } } } public sealed partial class ReportController : pb::IMessage<ReportController> { private static readonly pb::MessageParser<ReportController> _parser = new pb::MessageParser<ReportController>(() => new ReportController()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReportController> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Org.Roylance.Yadel.YadelControllerReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportController() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportController(ReportController other) : this() { DeleteDag = other.deleteDag_ != null ? other.DeleteDag.Clone() : null; Current = other.current_ != null ? other.Current.Clone() : null; GetDagStatus = other.getDagStatus_ != null ? other.GetDagStatus.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportController Clone() { return new ReportController(this); } /// <summary>Field number for the "delete_dag" field.</summary> public const int DeleteDagFieldNumber = 1; private global::Org.Roylance.Yadel.CommonAction deleteDag_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Org.Roylance.Yadel.CommonAction DeleteDag { get { return deleteDag_; } set { deleteDag_ = value; } } /// <summary>Field number for the "current" field.</summary> public const int CurrentFieldNumber = 2; private global::Org.Roylance.Yadel.CommonAction current_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Org.Roylance.Yadel.CommonAction Current { get { return current_; } set { current_ = value; } } /// <summary>Field number for the "get_dag_status" field.</summary> public const int GetDagStatusFieldNumber = 3; private global::Org.Roylance.Yadel.CommonAction getDagStatus_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Org.Roylance.Yadel.CommonAction GetDagStatus { get { return getDagStatus_; } set { getDagStatus_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReportController); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReportController other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(DeleteDag, other.DeleteDag)) return false; if (!object.Equals(Current, other.Current)) return false; if (!object.Equals(GetDagStatus, other.GetDagStatus)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (deleteDag_ != null) hash ^= DeleteDag.GetHashCode(); if (current_ != null) hash ^= Current.GetHashCode(); if (getDagStatus_ != null) hash ^= GetDagStatus.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (deleteDag_ != null) { output.WriteRawTag(10); output.WriteMessage(DeleteDag); } if (current_ != null) { output.WriteRawTag(18); output.WriteMessage(Current); } if (getDagStatus_ != null) { output.WriteRawTag(26); output.WriteMessage(GetDagStatus); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (deleteDag_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DeleteDag); } if (current_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Current); } if (getDagStatus_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GetDagStatus); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReportController other) { if (other == null) { return; } if (other.deleteDag_ != null) { if (deleteDag_ == null) { deleteDag_ = new global::Org.Roylance.Yadel.CommonAction(); } DeleteDag.MergeFrom(other.DeleteDag); } if (other.current_ != null) { if (current_ == null) { current_ = new global::Org.Roylance.Yadel.CommonAction(); } Current.MergeFrom(other.Current); } if (other.getDagStatus_ != null) { if (getDagStatus_ == null) { getDagStatus_ = new global::Org.Roylance.Yadel.CommonAction(); } GetDagStatus.MergeFrom(other.GetDagStatus); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (deleteDag_ == null) { deleteDag_ = new global::Org.Roylance.Yadel.CommonAction(); } input.ReadMessage(deleteDag_); break; } case 18: { if (current_ == null) { current_ = new global::Org.Roylance.Yadel.CommonAction(); } input.ReadMessage(current_); break; } case 26: { if (getDagStatus_ == null) { getDagStatus_ = new global::Org.Roylance.Yadel.CommonAction(); } input.ReadMessage(getDagStatus_); break; } } } } } #endregion } #endregion Designer generated code
/* * 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; using JetBrains.Application.Settings; namespace KaVE.VS.FeedbackGenerator.Settings { [SettingsKey(typeof(FeedbackSettings), "KaVE Feedback-Upload Settings")] // WARNING: Do not change classname, as it is used to identify settings public class UploadSettings { private const string DateTimeMinValue = "0001-01-01T00:00:00Z"; [SettingsEntry(DateTimeMinValue, "Timestamp of the last time the upload-reminder popup was shown to the user.")] public DateTimeOffset LastNotificationDate; [SettingsEntry(DateTimeMinValue, "Timestamp of the last time an export was done.")] public DateTimeOffset LastUploadDate; public bool IsInitialized() { var hasUninitializedField = LastNotificationDate == DateTimeOffset.MinValue || LastUploadDate == DateTimeOffset.MinValue; return !hasUninitializedField; } public void Initialize() { var now = DateTimeOffset.Now; LastUploadDate = now; LastNotificationDate = now; } } }
using System; using ObjCRuntime; namespace Twilio.IPMessagingClient { [Native] public enum TWMClientSynchronizationStrategy : ulong { All, ChannelsList } [Native] public enum TWMClientSynchronizationStatus : ulong { Started = 0, ChannelsListCompleted, Completed, Failed } [Native] public enum TWMLogLevel : ulong { Fatal = 0, Critical, Warning, Info, Debug } [Native] public enum TWMChannelSynchronizationStatus : ulong { None = 0, Identifier, Metadata, All, Failed } [Native] public enum TWMChannelStatus : ulong { Invited = 0, Joined, NotParticipating } [Native] public enum TWMChannelType : ulong { ublic = 0, rivate } [Native] public enum TWMUserInfoUpdate : ulong { FriendlyName = 0, Attributes, ReachabilityOnline, ReachabilityNotifiable } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.Xml; using System.IO; namespace PracticaXml.cs { class Program { static void Main(string[] args) { List<Persona> listaDePersonas = new List<Persona>(); Persona p1 = new Persona("Daniel", 15); Persona p2 = new Persona("Adrian", 11); Persona p3 = new Persona("Sofia", 43); Persona p4 = new Persona("Maria", 45); Persona p5 = new Persona("Nicolas", 24); listaDePersonas.Add(p1); listaDePersonas.Add(p2); listaDePersonas.Add(p3); listaDePersonas.Add(p4); listaDePersonas.Add(p5); XmlGenerica<Persona> archivo = new XmlGenerica<Persona>(); if (archivo.GuardarEnXml("PersonasGenerica.xml",listaDePersonas)) { Console.WriteLine("Se guardo con exito.."); } else { Console.WriteLine("No se pudo guardar.."); } List<Persona> nueva = new List<Persona>(); nueva= archivo.LeerEnXml("PersonasGenerica.xml"); Console.WriteLine(nueva.Count); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; ////////////////////////////////////////////////////////////////// //Created by: Daniel McCluskey //Project: CT6024 - AI //Repo: https://github.com/danielmccluskey/CT6024-AI //Script Purpose: Checks if the guard can see a player ////////////////////////////////////////////////////////////////// public class CS_GuardSeePlayerAction : CS_GOAPAction { private bool m_bRequiresInRange = false; private bool m_bSeePlayer = false; public CS_GuardSeePlayerAction() { AddEffect("seePlayer", true); m_fCost = 1.0f; } public override void ResetGA() { m_bSeePlayer = false; m_goTarget = null; } public override bool IsActionFinished() { return m_bSeePlayer; } public override bool NeedsToBeInRange() { return m_bRequiresInRange; } public override bool CheckPreCondition(GameObject a_goAIAgent) { if (GetComponent<CS_GuardSight>().m_bCanSeePlayer == true) { m_goTarget = GameObject.FindGameObjectWithTag("Player"); if (m_goTarget != null) { return true; } } return false; } public override bool PerformAction(GameObject agent) { m_bSeePlayer = true; return true; } }
 namespace KGViewer { class Category { public string Slug { get; set; } public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main() { Calculate(10, 5, 9); } static void Calculate(int a,int b, double c) { Console.WriteLine("a/5 = {0}, b/5 = {1}, c/5 = {2}", a/5, b/5, c/5 ); Console.ReadKey(); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Whale.API.Services; using Whale.DAL.Models.Email; using Whale.Shared.Models.Email; namespace Whale.API.Controllers { [ApiController] [Route("email")] public class EmailController: ControllerBase { private readonly EmailService _emailServcice; public EmailController(EmailService emailService) { _emailServcice = emailService; } [HttpPost] public async Task<OkResult> SendEmail([FromBody] MeetingInviteDTO inviteDto) { await _emailServcice.SendMeetingInvitesAsync(inviteDto); return Ok(); } [HttpPost("scheduled")] public async Task<OkResult> SendScheduledEmail([FromBody] ScheduledMeetingInvite invite) { await _emailServcice.SendMeetingInviteToHostAsync(invite); return Ok(); } } }
namespace AutoMapper.Execution { using System; public class DeferredInstantiatedResolver : IValueResolver { private readonly Func<ResolutionContext, IValueResolver> _constructor; public DeferredInstantiatedResolver(Func<ResolutionContext, IValueResolver> constructor) { _constructor = constructor; } public object Resolve(object source, ResolutionContext context) { var resolver = _constructor(context); return resolver.Resolve(source, context); } } }
using System; using UnityEngine; using Random = UnityEngine.Random; namespace BehaviorScripts.ProjectileBehaviors { public class LandmineExplosion: ProjectileScript { public Vector3 position; private float explosionDuration = 0.1f; private float explosionAge = 0; private float explosionSize = 15f; private int explosionType; protected new void Awake() { //If coming from a player, it can damage the player and enemy. If from an enemy, it can only harm the player gameObject.layer = transform.parent.GetComponent<ShooterBehavior>().IsFriendly ? LayerMask.NameToLayer("explosion") : LayerMask.NameToLayer("unfriendly_bullet"); position = transform.position; Shooter = transform.parent.GetComponent<ShooterBehavior>(); transform.localScale = new Vector3(1, 1, 1); //a 2 bit number determining how the x and y axes will scale explosionType = Random.Range(0, 3); } private void Update() { if (explosionAge < explosionDuration) { explosionAge += Time.deltaTime; var period = (explosionAge / explosionDuration); var xScale = explosionType % 2 == 0 ? Math.Cos(period) : Math.Sin(period); var yScale = (explosionType / 2) % 2 == 0 ? Math.Cos(period) : Math.Sin(period); transform.localScale = new Vector3((float)xScale * explosionSize, (float)yScale * explosionSize, 1); } else { Destroy(gameObject); } } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Obstacle")) { Destroy(gameObject); } } } }
namespace EkwExplorer.Core; public interface IBooksExplorer { Task Explore(CancellationToken cancellationToken); }
namespace Heikura.Samples.DataApp.ServiceHost.Modules.MessageHandlers { using System.Net.Http; public class LoggingMessageHandler : DelegatingHandler { public LoggingMessageHandler() { } protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { System.Diagnostics.Trace.TraceInformation("Begin Request: {0} {1}", request.Method, request.RequestUri); return base.SendAsync(request, cancellationToken); } } }
#pragma warning disable namespace AlienEngine.ASL { public abstract class TessellationControlShader : ASLShader { [In] [BuiltIn] protected readonly int gl_PatchVerticesIn; [In] [BuiltIn] protected readonly int gl_PrimitiveID; [In] [BuiltIn] protected readonly int gl_InvocationID; [Out] [BuiltIn] protected float[] gl_TessLevelOuter; [Out] [BuiltIn] protected float[] gl_TessLevelInner; } } #pragma warning restore
using System; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace Braspag.Domain.DTO { public class AdquirentesDto { [BsonRepresentation(BsonType.ObjectId)] public string _id { get; private set; } public string adquirentes { get; set; } public decimal? visa { get; set; } public decimal? master { get; set; } public decimal? elo { get; set; } } }
using APIChallenge; using System.Collections.Generic; namespace DependencyInjectionSample.Models { public interface IClienteDados { void inserirCliente(Cliente cliente); List<Cliente> obterListaClientes(); Cliente obterClientePorId(long id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BearKMPCommon { public class Network { public static int BUFFER_SIZE = 1024; public static char EOL_DELIM = '·'; public class Buffer { public byte[] data = new byte[BUFFER_SIZE]; public int readPos = 0; } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MMSdb.dbo.Tables { [Table("tbl_Physicians")] public class tbl_Physicians { [Key] public long phy_ID { get; set; } public long dmg_ID { get; set; } public String? phy_Name { get; set; } public String? phy_Specialty { get; set; } public String? phy_Address { get; set; } public String? phy_Phone { get; set; } public String? phy_Fax { get; set; } public String? phy_FirstVisit { get; set; } public String? phy_LastVisit { get; set; } public String? phy_NextVisit { get; set; } public String? phy_MedRecRequested { get; set; } public String? phy_MedRecReceived { get; set; } public String? phy_MedRecPaid { get; set; } public String? phy_Treatment { get; set; } public Boolean? deleted { get; set; } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using lianda.Component; using System.Data.SqlClient; namespace lianda.LD95 { /// <summary> /// LD955010 的摘要说明。 /// </summary> public class LD955010 : BasePage { protected System.Web.UI.WebControls.TextBox TextBox_GNDM; protected Infragistics.WebUI.UltraWebGrid.UltraWebGrid grid1; protected Infragistics.WebUI.UltraWebGrid.UltraWebGrid grid2; protected System.Web.UI.WebControls.Label Label_cdmc; protected System.Web.UI.WebControls.Label Label_hmmc; protected System.Web.UI.WebControls.Button Button_Grant; protected System.Web.UI.WebControls.Button Button_Disgrant; protected System.Web.UI.WebControls.Button Button_Query; private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 if(!this.IsPostBack) { string GNDM = this.Request.QueryString["GNDM"]; if(Tools.isEmpty(GNDM) == false){ this.TextBox_GNDM.Text = GNDM; query(); } } } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void InitializeComponent() { this.Button_Query.Click += new System.EventHandler(this.Button1_Click); this.Button_Grant.Click += new System.EventHandler(this.Button_Grant_Click); this.Button_Disgrant.Click += new System.EventHandler(this.Button_Disgrant_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Button1_Click(object sender, System.EventArgs e) { query(); } private void query() { // 未授权 string sql = @" SELECT * FROM X_XTJS WHERE DM NOT IN ( SELECT JSDM FROM X_JSQX WHERE GNDM = @GNDM ) "; SqlParameter[] paras = new SqlParameter[]{ new SqlParameter("@GNDM", this.TextBox_GNDM.Text.Trim()) }; this.grid1.Rows.Clear(); this.grid1.DataSource = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING, CommandType.Text, sql, paras); this.grid1.DataBind(); // 已授权 sql = @" SELECT * FROM X_XTJS WHERE DM IN ( SELECT JSDM FROM X_JSQX WHERE GNDM = @GNDM ) "; this.grid2.Rows.Clear(); this.grid2.DataSource = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING, CommandType.Text, sql, paras); this.grid2.DataBind(); // 功能代码信息 sql = @" SELECT TOP 1 DM, MC, MS FROM X_XTGN WHERE DM = @GNDM "; SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING, CommandType.Text, sql, paras); if(reader.Read()) { this.Label_cdmc.Text = reader["MC"] + ""; this.Label_hmmc.Text = reader["MS"] + ""; } } // 授权 private void Button_Grant_Click(object sender, System.EventArgs e) { using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING)) { cn.Open(); using(SqlTransaction trans = cn.BeginTransaction()) { try { if(Tools.isEmpty(this.TextBox_GNDM.Text)) { throw new Exception("请输入功能代码!"); } for(int i=0; i<this.grid1.Rows.Count; i++) { if(!(bool)this.grid1.Rows[i].Cells.FromKey("SELECT").Value) continue; string GNDM = this.TextBox_GNDM.Text.Trim(); string JSDM = this.grid1.Rows[i].Cells.FromKey("DM").Value + ""; string sql = @" INSERT INTO X_JSQX(GNDM, JSDM) VALUES(@GNDM, @JSDM) "; SqlParameter[] paras = new SqlParameter[]{ new SqlParameter("@GNDM", GNDM), new SqlParameter("@JSDM", JSDM), }; SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING, CommandType.Text, sql, paras); } trans.Commit(); query(); } catch(Exception ex) { trans.Rollback(); this.msgbox(ex.Message); } } cn.Close(); } } // 取消授权 private void Button_Disgrant_Click(object sender, System.EventArgs e) { using(SqlConnection cn = new SqlConnection(SqlHelper.CONN_STRING)) { cn.Open(); using(SqlTransaction trans = cn.BeginTransaction()) { try { if(Tools.isEmpty(this.TextBox_GNDM.Text)) { throw new Exception("请输入功能代码!"); } for(int i=0; i<this.grid2.Rows.Count; i++) { if(!(bool)this.grid2.Rows[i].Cells.FromKey("SELECT").Value) continue; string GNDM = this.TextBox_GNDM.Text.Trim(); string JSDM = this.grid2.Rows[i].Cells.FromKey("DM").Value + ""; string sql = @" DELETE FROM X_JSQX WHERE GNDM = @GNDM AND JSDM = @JSDM "; SqlParameter[] paras = new SqlParameter[]{ new SqlParameter("@GNDM", GNDM), new SqlParameter("@JSDM", JSDM), }; SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING, CommandType.Text, sql, paras); } trans.Commit(); query(); } catch(Exception ex) { trans.Rollback(); this.msgbox(ex.Message); } } cn.Close(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace d05_interface { public class Product : IDiscount { public string id, name; public int price; public float getDiscount() { return price * 0.1f; } public void Input() { Console.WriteLine(" nhap id: "); id = Console.ReadLine().Trim(); Console.WriteLine(" nhap ten san pham: "); name = Console.ReadLine().Trim(); while (true) { try { Console.Write(" nhap don gia: "); price = int.Parse(Console.ReadLine().Trim()); if (price >= 0) break; } catch (Exception e) { Console.WriteLine("Loi: " + e.Message); } } } public override string ToString() { return $"id = {id}, ten sp: {name}, don gia: {price}, chiet khau: {getDiscount()}, gia thuc te: {price-getDiscount()}"; } } }
//Problem 19. Dates from text in Canada //Write a program that extracts from a given text all dates that match the format DD.MM.YYYY. //Display them in the standard date format for Canada. using System; using System.Text.RegularExpressions; using System.Globalization; namespace Problem19DatesFromTextInCanada { class DatesFromTextInCanada { static public string[] ExtractDates(string str) { string RegexPattern = @"\b\d{2}.\d{2}.\d{4}\b"; // Find matches MatchCollection matches = Regex.Matches(str, RegexPattern, RegexOptions.IgnoreCase); string[] MatchList = new string[matches.Count]; // add each match int c = 0; foreach (Match match in matches) { MatchList[c] = match.ToString(); c++; } return MatchList; } static void Main() { Console.WriteLine("Enter text: "); string[] dates = ExtractDates(Console.ReadLine()); CultureInfo ci = new CultureInfo("en-CA"); foreach (string date in dates) { DateTime dt; DateTime.TryParseExact(date, "dd.mm.yyyy", CultureInfo.CreateSpecificCulture(ci.Name), DateTimeStyles.None, out dt); Console.WriteLine(dt.ToString(ci)); } } } }
using AutoMapper; using ImmedisHCM.Services.Core; using ImmedisHCM.Services.Identity; using ImmedisHCM.Services.Models.Core; using ImmedisHCM.Web.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ImmedisHCM.Web.Controllers { [Authorize(Roles = "Manager")] [Route("[controller]/[action]")] public class ManagerController : Controller { private readonly IManagerService _managerService; private readonly INomenclatureService _nomenclatureService; private readonly IAdminService _adminService; private readonly IAccountManageService _accountManageService; private readonly IMapper _mapper; public ManagerController(IManagerService managerService, IMapper mapper, IAccountManageService accountManageService, INomenclatureService nomenclatureService, IAdminService adminService) { _managerService = managerService; _mapper = mapper; _accountManageService = accountManageService; _nomenclatureService = nomenclatureService; _adminService = adminService; } [TempData] public string StatusMessage { get; set; } [HttpGet] public async Task<IActionResult> Employees() { var employees = await _managerService.GetEmployeesForManager(User.Identity.Name); var models = _mapper.Map<List<EmployeesViewModel>>(employees); return View(models); } [HttpGet] public async Task<IActionResult> Department() { var department = await _managerService.GetDepartmentForEmployeeWithEmployees(User.Identity.Name); var models = _mapper.Map<DepartmentDetailsViewModel>(department); return View(models); } [HttpGet] [Route("[controller]/Employee/[action]")] public async Task<IActionResult> Details(string email) { var employee = await _accountManageService.GetEmployeeByEmailAsync(email); if (employee != null) { //deal with nulls later } var model = _mapper.Map<EmployeeDetailsViewModel>(employee); return View(model); } [HttpGet] public async Task<IActionResult> ChangeSalary(string email) { if (!(await _managerService.IsManagerToEmployee(User.Identity.Name, email))) return RedirectToAction(nameof(AccountController.AccessDenied), "Account"); var empSalary = await _managerService.GetEmployeeSalary(email); var model = _mapper.Map<UpdateEmployeeSalaryViewModel>(empSalary); model.Currencies = _mapper.Map<List<CurrencyViewModel>>(await _nomenclatureService.GetCurrencies()); model.SalaryTypes = _mapper.Map<List<SalaryTypeViewModel>>(await _nomenclatureService.GetSalaryTypes()); model.StatusMessage = StatusMessage; return View(model); } [HttpPost] public async Task<IActionResult> ChangeSalary(UpdateEmployeeSalaryViewModel model) { if (!ModelState.IsValid) return View(model); var salId = (await _managerService.GetEmployeeSalary(model.EmployeeEmail)).Id; var updateModel = new SalaryServiceModel { Amount = model.Amount, Currency = await _nomenclatureService.GetCurrency(model.CurrencyId), SalaryType = await _nomenclatureService.GetSalaryType(model.SalaryTypeId), Employee = await _accountManageService.GetEmployeeByEmailAsync(model.EmployeeEmail), Id = salId }; await _managerService.UpdateEmployeeSalary(updateModel); StatusMessage = $"Successfuly updated salary for employee with email {model.EmployeeEmail}"; return RedirectToAction(nameof(ChangeSalary), routeValues: new { email = model.EmployeeEmail }); } [HttpGet] public async Task<IActionResult> ChangeJob(string email) { if (!(await _managerService.IsManagerToEmployee(User.Identity.Name, email))) return RedirectToAction(nameof(AccountController.AccessDenied), "Account"); var job = await _managerService.GetEmployeeJob(email); var salary = await _managerService.GetEmployeeSalary(email); var model = new UpdateEmployeeJobViewModel { Amount = salary.Amount, Currencies = _mapper.Map<List<CurrencyViewModel>>(await _nomenclatureService.GetCurrencies()), SalaryTypes = _mapper.Map<List<SalaryTypeViewModel>>(await _nomenclatureService.GetSalaryTypes()), CurrencyId = salary.Currency.Id, EmployeeEmail = email, EmployeeName = $"{salary.Employee.FirstName} {salary.Employee.LastName}", SalaryTypeId = salary.SalaryType.Id, Jobs = _mapper.Map<List<JobViewModel>>(await _adminService.GetJobs()), JobId = job.Id, StatusMessage = StatusMessage }; return View(model); } [HttpPost] public async Task<IActionResult> ChangeJob(UpdateEmployeeJobViewModel model) { if (!ModelState.IsValid) return View(model); var salId = (await _managerService.GetEmployeeSalary(model.EmployeeEmail)).Id; var salaryUpdateModel = new SalaryServiceModel { Amount = model.Amount, Currency = await _nomenclatureService.GetCurrency(model.CurrencyId), SalaryType = await _nomenclatureService.GetSalaryType(model.SalaryTypeId), Employee = await _accountManageService.GetEmployeeByEmailAsync(model.EmployeeEmail), Id = salId }; var jobModel = await _adminService.GetJobById(model.JobId); await _managerService.UpdateEmployeeJob(jobModel, salaryUpdateModel); StatusMessage = $"Successfuly updated job for employee with email {model.EmployeeEmail}"; return RedirectToAction(nameof(ChangeJob), routeValues: new { email = model.EmployeeEmail }); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Text; using DotNetty.Transport.Channels; using log4net; using Plus.Communication.Packets.Outgoing; using Plus.Communication.Packets.Outgoing.Handshake; using Plus.Communication.Packets.Outgoing.Notifications; using Plus.Core; using Plus.Database.Interfaces; using Plus.HabboHotel.Users.Messenger; namespace Plus.HabboHotel.GameClients { public class GameClientManager { private static readonly ILog Log = LogManager.GetLogger(typeof(GameClientManager)); private readonly ConcurrentDictionary<IChannelId, GameClient> _clients; private readonly ConcurrentDictionary<int, GameClient> _userIdRegister; private readonly ConcurrentDictionary<string, GameClient> _usernameRegister; private readonly Queue _timedOutConnections; private readonly Stopwatch _clientPingStopwatch; public GameClientManager() { _clients = new ConcurrentDictionary<IChannelId, GameClient>(); _userIdRegister = new ConcurrentDictionary<int, GameClient>(); _usernameRegister = new ConcurrentDictionary<string, GameClient>(); _timedOutConnections = new Queue(); _clientPingStopwatch = new Stopwatch(); _clientPingStopwatch.Start(); } public void OnCycle() { TestClientConnections(); HandleTimeouts(); } public GameClient GetClientByUserId(int userId) { if (_userIdRegister.ContainsKey(userId)) return _userIdRegister[userId]; return null; } public GameClient GetClientByUsername(string username) { if (_usernameRegister.ContainsKey(username.ToLower())) return _usernameRegister[username.ToLower()]; return null; } public bool TryGetClient(IChannelId clientId, out GameClient client) { return _clients.TryGetValue(clientId, out client); } public bool UpdateClientUsername(GameClient client, string oldUsername, string newUsername) { if (client == null || !_usernameRegister.ContainsKey(oldUsername.ToLower())) return false; _usernameRegister.TryRemove(oldUsername.ToLower(), out client); _usernameRegister.TryAdd(newUsername.ToLower(), client); return true; } public string GetNameById(int id) { GameClient client = GetClientByUserId(id); if (client != null) return client.GetHabbo().Username; string username; using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("SELECT username FROM users WHERE id = @id LIMIT 1"); dbClient.AddParameter("id", id); username = dbClient.GetString(); } return username; } public IEnumerable<GameClient> GetClientsById(Dictionary<int, MessengerBuddy>.KeyCollection users) { foreach (int id in users) { GameClient client = GetClientByUserId(id); if (client != null) yield return client; } } public void StaffAlert(MessageComposer message, int exclude = 0) { foreach (GameClient client in GetClients.ToList()) { if (client == null || client.GetHabbo() == null) continue; if (client.GetHabbo().Rank < 2 || client.GetHabbo().Id == exclude) continue; client.SendPacket(message); } } public void ModAlert(string message) { foreach (GameClient client in GetClients.ToList()) { if (client == null || client.GetHabbo() == null) continue; if (client.GetHabbo().GetPermissions().HasRight("mod_tool") && !client.GetHabbo().GetPermissions().HasRight("staff_ignore_mod_alert")) { try { client.SendWhisper(message, 5); } catch { } } } } public void DoAdvertisingReport(GameClient reporter, GameClient target) { if (reporter == null || target == null || reporter.GetHabbo() == null || target.GetHabbo() == null) return; StringBuilder builder = new(); builder.Append("New report submitted!\r\r"); builder.Append("Reporter: " + reporter.GetHabbo().Username + "\r"); builder.Append("Reported User: " + target.GetHabbo().Username + "\r\r"); builder.Append(target.GetHabbo().Username + "s last 10 messages:\r\r"); using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.SetQuery("SELECT `message` FROM `chatlogs` WHERE `user_id` = '" + target.GetHabbo().Id + "' ORDER BY `id` DESC LIMIT 10"); int number = 11; var reader = dbClient.GetTable(); foreach (DataRow row in reader.Rows) { number -= 1; builder.Append(number + ": " + row["message"] + "\r"); } } foreach (GameClient client in GetClients.ToList()) { if (client == null || client.GetHabbo() == null) continue; if (client.GetHabbo().GetPermissions().HasRight("mod_tool") && !client.GetHabbo().GetPermissions() .HasRight("staff_ignore_advertisement_reports")) client.SendPacket(new MotdNotificationComposer(builder.ToString())); } } public void SendPacket(MessageComposer packet, string fuse = "") { foreach (GameClient client in _clients.Values.ToList()) { if (client == null || client.GetHabbo() == null) continue; if (!string.IsNullOrEmpty(fuse)) { if (!client.GetHabbo().GetPermissions().HasRight(fuse)) continue; } client.SendPacket(packet); } } public void CreateAndStartClient(IChannelHandlerContext connection) { GameClient client = new(connection); if (_clients.TryAdd(connection.Channel.Id, client)) { //Hmmmmm? } else connection.CloseAsync(); } public void DisposeConnection(IChannelId clientId) { if (!TryGetClient(clientId, out GameClient client)) return; client?.Dispose(); _clients.TryRemove(clientId, out client); } public void LogClonesOut(int userId) { GameClient client = GetClientByUserId(userId); client?.Disconnect(); } public void RegisterClient(GameClient client, int userId, string username) { if (_usernameRegister.ContainsKey(username.ToLower())) _usernameRegister[username.ToLower()] = client; else _usernameRegister.TryAdd(username.ToLower(), client); if (_userIdRegister.ContainsKey(userId)) _userIdRegister[userId] = client; else _userIdRegister.TryAdd(userId, client); } public void UnregisterClient(int userId, string username) { _userIdRegister.TryRemove(userId, out GameClient _); _usernameRegister.TryRemove(username.ToLower(), out GameClient _); } public void CloseAll() { foreach (GameClient client in GetClients.ToList()) { if (client?.GetHabbo() != null) { try { using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor()) { dbClient.RunQuery(client.GetHabbo().GetQueryString); } Console.Clear(); Log.Info("<<- SERVER SHUTDOWN ->> INVENTORY IS SAVING"); } catch { } } } Log.Info("Done saving users inventory!"); Log.Info("Closing server connections..."); try { foreach (GameClient client in GetClients.ToList()) { if (client == null) continue; try { client.Dispose(); } catch { } } Console.Clear(); Log.Info("<<- SERVER SHUTDOWN ->> CLOSING CONNECTIONS"); } catch (Exception e) { ExceptionLogger.LogException(e); } if (_clients.Count > 0) _clients.Clear(); Log.Info("Connections closed!"); } private void TestClientConnections() { if (_clientPingStopwatch.ElapsedMilliseconds >= 30000) { _clientPingStopwatch.Restart(); List<GameClient> toPing = new(); foreach (GameClient client in _clients.Values.ToList()) { if (client.PingCount < 6) { client.PingCount++; toPing.Add(client); } else { lock (_timedOutConnections.SyncRoot) { _timedOutConnections.Enqueue(client); } } } DateTime start = DateTime.Now; foreach (GameClient client in toPing.ToList()) { try { client.SendPacket(new PongComposer()); } catch { lock (_timedOutConnections.SyncRoot) { _timedOutConnections.Enqueue(client); } } } } } private void HandleTimeouts() { if (_timedOutConnections.Count > 0) { lock (_timedOutConnections.SyncRoot) { while (_timedOutConnections.Count > 0) { GameClient client = null; if (_timedOutConnections.Count > 0) client = (GameClient) _timedOutConnections.Dequeue(); client?.Disconnect(); } } } } public int Count => _clients.Count; public ICollection<GameClient> GetClients => _clients.Values; } }
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var myList = Console.ReadLine().Split().Select(decimal.Parse).ToList(); myList.Sort(); Console.WriteLine(string.Join(" <= ", myList)); } }
using System; using System.Collections.Generic; using Acr.UserDialogs; using City_Center.Clases; using City_Center.Helper; using Xamarin.Forms; namespace City_Center.Page { public partial class DetalleRestaurante : ContentPage { private string[] ListaOpciones; public DetalleRestaurante() { InitializeComponent(); NavigationPage.SetTitleIcon(this, "logo@2x.png"); FechaR1.Text=String.Format("{0:dd/MM/yyyy}", DateTime.Today); } protected override void OnAppearing() { base.OnAppearing(); ListaOpciones = new string[] { VariablesGlobales.Img1, VariablesGlobales.Img2, VariablesGlobales.Img3, VariablesGlobales.Img4 }; listaDetalleRestaurante.ItemsSource = ListaOpciones; } void Handle_ItemSelected(object sender, Xamarin.Forms.SelectedItemChangedEventArgs e) { try { var Seleccion = e.SelectedItem; if (Seleccion != null) { var selection = e.SelectedItem; Img1provisional.Source = selection.ToString(); } } catch (Exception) { } } void Handle_Tapped(object sender, System.EventArgs e) { if (SLM.IsVisible == false) { SLM.IsVisible = true; SLR.IsVisible = false; } else { SLM.IsVisible = false; } } void Handle_Tapped_1(object sender, System.EventArgs e) { if (SLR.IsVisible == false) { SLR.IsVisible = true; SLM.IsVisible = false; } else { SLR.IsVisible = false; } } void Handle_Tapped_2(object sender, System.EventArgs e) { SLR.IsVisible = false; } void Handle_Tapped_3(object sender, System.EventArgs e) { SLM.IsVisible = false; } async void Chat_click(object sender, System.EventArgs e) { bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ? (bool)Application.Current.Properties["IsLoggedIn"] : false; if (isLoggedIn) { await ((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new SeleccionTipoChat()); } else { await Mensajes.Alerta("Es necesario que te registres para completar esta acción"); } } async void FechaR1_Tapped(object sender, System.EventArgs e) { #if __IOS__ DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); #endif var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig { IsCancellable = true, CancelText = "CANCELAR", MinimumDate = DateTime.Now.AddDays(0) }); if (result.Ok) { FechaR1.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate); FechaR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } else { FechaR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } } async void HoraR1_Tapped(object sender, System.EventArgs e) { #if __IOS__ DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); #endif if (VariablesGlobales.HorarioPIU == true) { var result = await UserDialogs.Instance.ActionSheetAsync("Horario", "CANCELAR", null, null, "12:30", "20:30", "21:00", "23:00"); if (result != "CANCELAR") { HoraR1.Text = result.ToString(); HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } else { HoraR1.Text = "12:30"; HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } } else if (VariablesGlobales.HorarioLEGULA == true) { var result = await UserDialogs.Instance.ActionSheetAsync("Horario", "CANCELAR", null, null, "21:00", "23:00"); if (result != "CANCELAR") { HoraR1.Text = result.ToString(); HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } else { HoraR1.Text = "21:00"; HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } } else if (VariablesGlobales.HorarioCityCenter == true) { var result = await UserDialogs.Instance.ActionSheetAsync("Horario", "CANCELAR", null, null, "20:30"); if (result != "CANCELAR") { HoraR1.Text = result.ToString(); HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } else { HoraR1.Text = "20:30"; HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } } else { var result = await UserDialogs.Instance.TimePromptAsync(new TimePromptConfig { IsCancellable = true }); if (result.Ok) { HoraR1.Text = Convert.ToString(result.SelectedTime); HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } else { HoraR1.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } } } async void Silla_Tapped(object sender, System.EventArgs e) { #if __IOS__ DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); #endif var result = await UserDialogs.Instance.ActionSheetAsync("Sillas niños", "CANCELAR", null, null, "No", "Si"); if (result != "CANCELAR") { SillaNiño.Text = result.ToString(); SillaNiño.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } else { SillaNiño.Unfocus(); DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSharpAvanzado { class Persona { public string Apellido { get; set; } = "Apellido"; public string Nombre { get; set; } = "Nombre"; public Documento DNI { get; set; } public Documento DNIContacto { get; set; } //Propiedad calculada //public string NombreCompleto //{ // get // { // return $"{Apellido}, {Nombre}"; // } //} //Nueva forma de hacer las propiedades calculadas public string NombreCompleto => $"{Apellido}, {Nombre}, {DNI}"; public string NombreCompletoConDescripcion => $"Apellido: {Apellido}, Nombre: {Nombre}, Dni: {DNI}, Dni Contacto: {DNIContacto?.Tipo ?? "Sin Contacto" } {DNIContacto?.Numero}"; public Persona(string apellido, string nombre) { if (string.IsNullOrWhiteSpace(apellido)) { throw new ArgumentException("Apellido no es válido"); } if (string.IsNullOrWhiteSpace(nombre)) { throw new ArgumentException("Nombre no es válido"); } Apellido = apellido; Nombre = nombre; } public Persona(Documento dni, string apellido, string nombre) : this(apellido,nombre) { Documento porDefecto = new Documento() { Tipo = "Sin Identificar", Numero = null }; //if (dni == null) //{ // dni = porDefecto; //} //DNI = dni; //CONDICION ? VALOR_POSITIVA : VALOR_NEGATIVA; // Asigno con IF en linea //DNI = dni == null ? porDefecto : dni; // Condicional null DNI = dni ?? porDefecto; } } }
//using System.Reflection; //using System.Threading.Tasks; //using Castle.DynamicProxy; //namespace Hybrid.Domain.UnitOfWorks //{ // public class UnitOfWorkInterceptor:IInterceptor // { // private readonly IUnitOfWorkManager _unitOfWorkManager; // public UnitOfWorkInterceptor(IUnitOfWorkManager unitOfWorkManager) // { // _unitOfWorkManager = unitOfWorkManager; // } // /// <summary> // /// 拦截 // /// </summary> // /// <param name="invocation"></param> // public void Intercept(IInvocation invocation) // { // //默认都开启工作单元,所以不需UnitOfWorkAttribute那些 // if (invocation.Method.ReturnType == typeof(Task) || // invocation.Method.ReturnType.GetTypeInfo().IsGenericType && // invocation.Method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) // { // PerformUowAsync(invocation); // } // else // { // PerformUow(invocation); // } // } // /// <summary> // /// 同步 // /// </summary> // /// <param name="invocation"></param> // private void PerformUow(IInvocation invocation) // { // using (var uow = _unitOfWorkManager.Begin()) // { // invocation.Proceed(); // uow.Complete(); // } // } // /// <summary> // /// 异步 // /// </summary> // /// <param name="invocation"></param> // private void PerformUowAsync(IInvocation invocation) // { // using (var uow = _unitOfWorkManager.Begin()) // { // invocation.Proceed(); // uow.CompleteAsync(); // } // } // } //}
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_RotateSelf : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_space(IntPtr l) { int result; try { RotateSelf rotateSelf = (RotateSelf)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushEnum(l, rotateSelf.space); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_space(IntPtr l) { int result; try { RotateSelf rotateSelf = (RotateSelf)LuaObject.checkSelf(l); Space space; LuaObject.checkEnum<Space>(l, 2, out space); rotateSelf.space = space; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_rotateSpeed(IntPtr l) { int result; try { RotateSelf rotateSelf = (RotateSelf)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rotateSelf.rotateSpeed); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_rotateSpeed(IntPtr l) { int result; try { RotateSelf rotateSelf = (RotateSelf)LuaObject.checkSelf(l); float rotateSpeed; LuaObject.checkType(l, 2, out rotateSpeed); rotateSelf.rotateSpeed = rotateSpeed; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_axis(IntPtr l) { int result; try { RotateSelf rotateSelf = (RotateSelf)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, rotateSelf.axis); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_axis(IntPtr l) { int result; try { RotateSelf rotateSelf = (RotateSelf)LuaObject.checkSelf(l); Vector3 axis; LuaObject.checkType(l, 2, out axis); rotateSelf.axis = axis; 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.RotateSelf"); LuaObject.addMember(l, "space", new LuaCSFunction(Lua_RO_RotateSelf.get_space), new LuaCSFunction(Lua_RO_RotateSelf.set_space), true); LuaObject.addMember(l, "rotateSpeed", new LuaCSFunction(Lua_RO_RotateSelf.get_rotateSpeed), new LuaCSFunction(Lua_RO_RotateSelf.set_rotateSpeed), true); LuaObject.addMember(l, "axis", new LuaCSFunction(Lua_RO_RotateSelf.get_axis), new LuaCSFunction(Lua_RO_RotateSelf.set_axis), true); LuaObject.createTypeMetatable(l, null, typeof(RotateSelf), typeof(MonoBehaviour)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using XRTTicket.Contexts; using XRTTicket.Models.Ticket; namespace XRTTicket.DAO { public class TicketTypeDao : BaseContext<TicketType>, IUnitOfWork<TicketType> { public int Next() => DbSet.Max(x => x.TicketTypeId) + 1; } }
using System; using System.Threading; using System.Threading.Tasks; using Shunxi.Business.Enums; using Shunxi.Business.Logic.Controllers.Status; using Shunxi.Business.Logic.Devices; using Shunxi.Business.Models; using Shunxi.Business.Models.cache; using Shunxi.Business.Protocols.Helper; using Shunxi.Common.Log; namespace Shunxi.Business.Logic.Controllers { public abstract class ControllerBase :IDisposable { //设备开始运行时间 public DateTime StartTime { get; set; } = DateTime.MinValue; //设备停止运行时间(分为自动停止和强制停止) public DateTime StopTime { get; set; } = DateTime.MinValue; /*设备运行次数 会影响设备的下一次运行日期 * if AlreadyRunTimes == 0 && starttime < DateTime.Now 则调整cultivation的starttime为当前时间。 * 否则不做调整 */ public int AlreadyRunTimes { get; set; } = 0; protected Timer LoopTimer; public DeviceStatusEnum CurrentStatus { get; set; } public StatusBase Status; public virtual bool IsEnable => true; protected virtual int IdlePollingInterval => 10 * 1000; protected virtual int StartingPollingInterval => 500; protected virtual int RunningPollingInterval => 500; protected virtual int PausingPollingInterval => 500; // protected AsyncManualResetEvent<DeviceIOResult> StartEvent = new AsyncManualResetEvent<DeviceIOResult>(); // protected AsyncManualResetEvent<DeviceIOResult> StopEvent = new AsyncManualResetEvent<DeviceIOResult>(); protected TaskCompletionSource<DeviceIOResult> StartEvent = new TaskCompletionSource<DeviceIOResult>(); protected TaskCompletionSource<DeviceIOResult> StopEvent = new TaskCompletionSource<DeviceIOResult>(); protected CancellationTokenSource CancellationTokenSource = new CancellationTokenSource(); public DeviceBase Device; public ControlCenter Center; protected ControllerBase(ControlCenter center, DeviceBase device) { SetStatus(DeviceStatusEnum.Idle); Device = device; Center = center; } public virtual void Cancel() { LoopTimer?.Dispose(); CancellationTokenSource.Cancel(); if (StartEvent.Task.Status != TaskStatus.Canceled && StartEvent.Task.Status != TaskStatus.Faulted && StartEvent.Task.Status != TaskStatus.RanToCompletion) { StartEvent.TrySetResult(new DeviceIOResult(false, "CANCEL")); } } public void SetStatus(DeviceStatusEnum state) { this.CurrentStatus = state; switch (state) { case DeviceStatusEnum.Idle: this.Status = new IdleStatus(this); break; case DeviceStatusEnum.Error: this.Status = new ErrorStatus(this); break; case DeviceStatusEnum.Pausing: this.Status = new PausingStatus(this); break; case DeviceStatusEnum.PrePause: this.Status = new PrePauseStatus(this); break; case DeviceStatusEnum.PreStart: this.Status = new PreStartStatus(this); break; case DeviceStatusEnum.Running: this.Status = new RunningStatus(this); break; case DeviceStatusEnum.Startting: this.Status = new StartingStatus(this); break; default: break; } } #region 控制命令 public abstract Task<DeviceIOResult> Start(); public virtual async Task<DeviceIOResult> ReStart() { if(!IsEnable || CurrentStatus == DeviceStatusEnum.AllFinished) return new DeviceIOResult(false, "DISABLED"); CancellationTokenSource = new CancellationTokenSource(); return await Start(); } //设备停止 public virtual async Task<DeviceIOResult> Stop() { if(!IsEnable || CurrentStatus == DeviceStatusEnum.AllFinished) return new DeviceIOResult(false, "DISABLED"); SetStatus(DeviceStatusEnum.PrePause); Device.Stop(); StopEvent = new TaskCompletionSource<DeviceIOResult>(); return await StopEvent.Task; } //紧急关机 还未实现 public abstract Task<DeviceIOResult> Close(); //培养周期内 设备停止后需要处理轮询逻辑 public virtual async Task<DeviceIOResult> Pause() { return await Stop(); } #endregion #region 处理指令反馈 public abstract void Next(SerialPortEventArgs args); protected void LoopHandle(Action action, int span = 0) { LoopTimer?.Dispose(); if (!IsEnable) return; if (span < 0) span = 0; LoopTimer = new Timer((obj) => { action.Invoke(); }, null, span, -1); } public virtual void StartRunningLoop() { if (CurrentStatus != DeviceStatusEnum.Running && CurrentStatus != DeviceStatusEnum.Startting) { LogFactory.Create() .Warnning( $"device{Device.DeviceId} SysStatus is {CurrentStatus}, can not send Running Directive"); return; } LoopHandle(Device.Running, CurrentStatus == DeviceStatusEnum.Startting ? StartingPollingInterval : RunningPollingInterval); } public virtual void StartPauseLoop() { if (CurrentStatus != DeviceStatusEnum.Pausing) { LogFactory.Create() .Warnning( $"device{Device.DeviceId} SysStatus is {CurrentStatus}, can not send Pausing Directive"); return; } LoopHandle(Device.Pausing, PausingPollingInterval); } public virtual void StartIdleLoop() { if (CurrentStatus != DeviceStatusEnum.Idle) { LogFactory.Create() .Warnning( $"device{Device.DeviceId} SysStatus is {CurrentStatus}, can not send Idle Directive"); return; } LoopHandle(Device.Idle, IdlePollingInterval); } public abstract void ProcessRunningDirectiveResult(DirectiveData data, CommunicationEventArgs comEventArgs); public abstract void ProcessTryPauseResult(DirectiveData data, CommunicationEventArgs comEventArgs); public abstract void ProcessPausingResult(DirectiveData data, CommunicationEventArgs comEventArgs); public virtual void ProcessTryStartResult(DirectiveData data, CommunicationEventArgs comEventArgs) { SetStatus(DeviceStatusEnum.Startting); comEventArgs.DeviceStatus = DeviceStatusEnum.Startting; //记录泵的开始时间 // 拿到TryStart反馈指令后启动running状态轮询 OnCommunicationChange(comEventArgs); StartRunningLoop(); } public virtual void ProcessIdleResult(DirectiveData data, CommunicationEventArgs comEventArgs) { if (CurrentStatus == DeviceStatusEnum.Idle) { comEventArgs.DeviceStatus = DeviceStatusEnum.Idle; } else { // 进入普通轮询状态 SetStatus(DeviceStatusEnum.Idle); comEventArgs.DeviceStatus = DeviceStatusEnum.Idle; } StartIdleLoop(); } #endregion #region 触发事件 public virtual void OnCommunication(CommunicationEventArgs args) { if (CurrentContext.Status == SysStatusEnum.Starting) { Center.OnSystemStatusChange(new RunStatusChangeEventArgs() { SysStatus = SysStatusEnum.Running }); Center.SyncSysStatusWithServer(); } } public virtual void OnCommunicationChange(CommunicationEventArgs e) { if (e == null) return; LogFactory.Create().Info($"****************************{e.DeviceId}->{e.DeviceStatus}***********************"); } public virtual void OnCustomError(CustomException obj) { Center.OnErrorEvent(obj); Dispose(); CurrentContext.Status = SysStatusEnum.Unknown; } #endregion public void Dispose() { Cancel(); } } }
namespace Social_Media_Posts { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class SocialMediaPosts { public static void Main(string[] args) { //var for reading the input; var input = Console.ReadLine(); //dictionary for result; var result = new Dictionary< string, Dictionary<string, List<string>> >(); while (input != "drop the media") { //var splited input; var token = input.Split(' ').ToArray(); //var for command; var command = token[0]; //var for post name; var postName = token[1]; //check for commands; if (command == "post") { if (!result.ContainsKey(postName)) { result[postName] = new Dictionary<string, List<string>>(); result[postName]["like"] = new List<string>(); result[postName]["dislike"] = new List<string>(); } } else if (command == "like") { result[postName]["like"].Add("like"); } else if (command == "dislike") { result[postName]["dislike"].Add(command); } else if (command == "comment") { //var for writer; var writer = token[2]; //var for comment; var comment = input.Substring(token[0].Length + token[1].Length + token[2].Length + 3); if (!result[postName].ContainsKey(writer)) { result[postName][writer] = new List<string>(); } result[postName][writer].Add(comment); } input = Console.ReadLine(); }//end of while loop; //printing the result; foreach (var item in result) { //var for likes in post; var likes = item.Value["like"]; //var for dislike in post; var dislikes = item.Value["dislike"]; Console.WriteLine("Post: {0} | Likes: {1} | Dislikes: {2}", item.Key, likes.Count, dislikes.Count); Console.WriteLine("Comments:"); //check for commnets; if (item.Value.Count == 2) { Console.WriteLine("None"); } else { foreach (var writer in item.Value) { if (writer.Key != "like" && writer.Key != "dislike") { foreach (var comment in writer.Value) { Console.WriteLine("* {0}: {1}", writer.Key, comment); } } } } }//end of printing; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; namespace Microsoft.EntityFrameworkCore.Cosmos { public class KeysWithConvertersCosmosTest : KeysWithConvertersTestBase<KeysWithConvertersCosmosTest.KeysWithConvertersCosmosFixture> { public KeysWithConvertersCosmosTest(KeysWithConvertersCosmosFixture fixture) : base(fixture) { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_struct_key_and_optional_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_comparable_struct_key_and_optional_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_generic_comparable_struct_key_and_optional_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_struct_key_and_required_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_comparable_struct_key_and_required_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_generic_comparable_struct_key_and_required_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_class_key_and_optional_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_comparable_class_key_and_optional_dependents() { } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents() { base.Can_insert_and_read_back_with_comparable_struct_binary_key_and_optional_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents() { base.Can_insert_and_read_back_with_comparable_struct_binary_key_and_required_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents() { base.Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_optional_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents() { base.Can_insert_and_read_back_with_generic_comparable_struct_binary_key_and_required_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents() { base.Can_insert_and_read_back_with_structural_struct_binary_key_and_optional_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents() { base.Can_insert_and_read_back_with_structural_struct_binary_key_and_required_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents() { base.Can_insert_and_read_back_with_struct_binary_key_and_optional_dependents(); } [ConditionalFact(Skip = "Issue=#16920 (Include)")] public override void Can_insert_and_read_back_with_struct_binary_key_and_required_dependents() { base.Can_insert_and_read_back_with_struct_binary_key_and_required_dependents(); } public class KeysWithConvertersCosmosFixture : KeysWithConvertersFixtureBase { protected override ITestStoreFactory TestStoreFactory => CosmosTestStoreFactory.Instance; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class MasterPage_RakeshMasterPage : System.Web.UI.MasterPage { BizCon_DB_ConnectionString con_biz = new BizCon_DB_ConnectionString(); // ARFocus_DB_Connectring con_arfoc = new ARFocus_DB_Connectring(); protected void Page_Load(object sender, EventArgs e) { try { if (Session["UserID"] != null) { int mys = Convert.ToInt32(Session["UserID"]); string user_name = Session["name"].ToString(); lbl_username.Text = user_name; string clientid = Session["ClientID"].ToString(); } else { Response.Redirect("Index.html"); } } catch (Exception ex) { Response.Redirect("Index.html"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VocabularyApi.Models { public class Student { public Guid Id { get; protected set; } public IReadOnlyCollection<UserVocabularyWord> UserVocabularyWords { get; protected set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TicTacToe { public class Player { private string playerPiece = "n"; //METHODS //Move takes a multi-dimensional array board, and a string piece that are both ref public void Move(ref string[,] board, ref string piece) { playerPiece = piece; int rows = 3; int columns = 3; bool turnOver = false; bool validMove = false; string playerMove; do { //Reset counters int availabilityCounter = 0; bool playerMoveValid = false; ///Check the board to see if any moves are available for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if ((board[i, j] == "o") || (board[i, j] == "x")) { availabilityCounter++; if (availabilityCounter == 9) { turnOver = true; } } } } if (!turnOver) { Console.WriteLine("\n\nPLEASE CHOOSE A NUMBER FOR YOUR NEXT MOVE: \n\n"); playerMove = Console.ReadLine(); do { //See if the player's move is equal to a string 1-9 and increase the playerMove counter if it is found //If the playerMove counter = 1 then the move has been found, if not then please ask the player to enter a valid move for (int r = 1; r <= 9; r++) { if (playerMove == Convert.ToString(r)) { playerMoveValid = true; } } //Make sure the player has entered a space on the board //if they haven't make them choose again if (!playerMoveValid) { Console.WriteLine("\nThat is not a valid choice please enter a new number...\n"); playerMove = Console.ReadLine(); } } while (!playerMoveValid) ; //This loop searchs through the board looking for player's desired move while his/her turn is not over for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { //Find the player's desired move, see if the spot is occupied, if not, place the player piece if ((board[i, j] == playerMove) & (board[i, j] != "o") & (board[i, j] != "x")) { board[i, j] = playerPiece; turnOver = true; validMove = true; } } } //If the move is not available because the space is occupied inform the player if (!validMove) { Console.WriteLine("THAT MOVE IS NOT AVAILABLE!\n"); } } //Updated so that while statement does check for mutually exclusive events. turnOver will never be true when validMove is false so I only need to check one of them. } while ((!turnOver)); }//End move player }//End player class public class Computer { private string computerPiece = "n"; //METHODS //Move takes a multidimensional array board refernce and a string piece reference public void Move(ref string[,] board, ref string cPiece) { //create an instance of the random class Random RandomClass = new Random(); computerPiece = cPiece; bool turnOver = false; int rows = 3; int columns = 3; //AI //The computer will make a move based on random numbers do { int availabilityCounter = 0; ///Check the board to see if any moves are available for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if ((board[i, j] == "o") || (board[i, j] == "x")) { availabilityCounter++; if (availabilityCounter == 9) { turnOver = true; } } } } if (!turnOver) { int randomOne = RandomClass.Next(0, 3); int randomTwo = RandomClass.Next(0, 3); //End turn when the computer places a piece if ((board[randomOne, randomTwo] != "x") & (board[randomOne, randomTwo] != "o")) { board[randomOne, randomTwo] = cPiece; turnOver = true; } } } while ((!turnOver)); }//End Move }//End Computer public class Board { //Creates a game board with pre-set values private string[,] gameBoard = { {"1","2","3"}, {"4","5","6"}, {"7","8","9"} }; //Methods //Display just displays the updated game board public void Display() { Console.WriteLine("\n{0} {1} {2}\n", gameBoard[0, 0], gameBoard[0, 1], gameBoard[0, 2]); Console.WriteLine("{0} {1} {2}\n", gameBoard[1, 0], gameBoard[1, 1], gameBoard[1, 2]); Console.WriteLine("{0} {1} {2}\n\n", gameBoard[2, 0], gameBoard[2, 1], gameBoard[2, 2]); } //CheckBoard accepts a board and checks it to see who has won, then returns a string that describes who won public string Check()//use gameBoard member here instead! { string gameOver = "n"; //Conditions for winning the game string[,] winningCombos = { {gameBoard[0,0], gameBoard[0,1], gameBoard[0,2]}, {gameBoard[1,0], gameBoard[1,1], gameBoard[1,2]}, {gameBoard[2,0], gameBoard[2,1], gameBoard[2,2]}, {gameBoard[0,0], gameBoard[1,0], gameBoard[2,0]}, {gameBoard[0,1], gameBoard[1,1], gameBoard[2,1]}, {gameBoard[0,2], gameBoard[1,2], gameBoard[2,2]}, {gameBoard[0,0], gameBoard[1,1], gameBoard[2,2]}, {gameBoard[0,2], gameBoard[1,1], gameBoard[2,0]} }; int totalCombos = 8; //Check the Board to see if anyone has won for (int i = 0; i < totalCombos; i++) { //Check all the winning rows to see if x's won if ((winningCombos[i, 0] == "x") & (winningCombos[i, 1] == "x") & (winningCombos[i, 2] == "x")) { gameOver = "X"; } //Check all the winning rows to see if o's have won if ((winningCombos[i, 0] == "o") & (winningCombos[i, 1] == "o") & (winningCombos[i, 2] == "o") & (gameOver != "X")) { gameOver = "O"; } } //return the status of the game return gameOver; }//End Check //accessor method for retrieving the board public string[,] Get() { return gameBoard; } }//End Board public class GameLoop { public void Run() { string userResponse = ""; string gameStatus = "n"; do { Console.WriteLine("\n\nWELCOME TO ANEXA'S TIC TAC TOE GAME!!"); //Create a new Player, a new Board, and a new Computer Player newPlayer = new Player(); Computer newComputer = new Computer(); Board newBoard = new Board(); //the variable turn will helps to determine when the game is a tie int turn = 0; //Use the Board accessor method to get the newly created board and store it in newGameBoard string[,] newGameBoard = newBoard.Get(); Console.WriteLine("\nWould you like to be X's or O's?"); string userXorO = Console.ReadLine(); //If the user does not enter x or o then keep asking until they do do { if ((userXorO != "x") & (userXorO != "o")) { Console.WriteLine("You must type lower case x or lower case o to continue: "); userXorO = Console.ReadLine(); } } while ((userXorO != "x") & (userXorO != "o")); //display the updated newGameBoard newBoard.Display(); do { string playerGamePiece = userXorO; //If the player chooses x then they will always move first if (userXorO == "x") { string computerPiece = "o"; //Get the player move newPlayer.Move(ref newGameBoard, ref playerGamePiece); //Get the status of the game after the player's move gameStatus = newBoard.Check(); //Display the updated board after the move newBoard.Display(); //increase the turn count so we can tell when there's a tie turn++; //same logic as player move newComputer.Move(ref newGameBoard, ref computerPiece); gameStatus = newBoard.Check(); newBoard.Display(); turn++; } //if the player chooses o then they will always move after the computer else if (userXorO == "o") { string computerPiece = "x"; //same as above newComputer.Move(ref newGameBoard, ref computerPiece); gameStatus = newBoard.Check(); newBoard.Display(); turn++; //same as above newPlayer.Move(ref newGameBoard, ref playerGamePiece); gameStatus = newBoard.Check(); newBoard.Display(); turn++; } //if the gameStatus has X as the winner, and the player's piece is X, then congratulate them if ((gameStatus == "X") & (userXorO == "x")) { Console.WriteLine("YOU WON!\n"); Console.WriteLine("Would you like to play again? (y or n)"); userResponse = Console.ReadLine(); } //if the game status has X as the winner and the player piece is o, then tell them they lost else if ((gameStatus == "X") & (userXorO == "o")) { Console.WriteLine("YOU LET THE COMPUTER BEAT YOU?\n"); Console.WriteLine("Would you like to play again? ( y or n )"); userResponse = Console.ReadLine(); } //Same logic as above if ((gameStatus == "O") & (userXorO == "x")) { Console.WriteLine("YOU LET THE COMPUTER BEAT YOU?\n"); Console.WriteLine("Would you like to play again? ( y or n )"); userResponse = Console.ReadLine(); } else if ((gameStatus == "O") & (userXorO == "o")) { Console.WriteLine("YOU WON!\n"); Console.WriteLine("Would you like to play again? (y or n)"); userResponse = Console.ReadLine(); } //if we have gone through all 9 turns and the game status does not show x or o as a winner then there is a tie, inform the player if ((turn > 9) & (gameStatus != "X") & (gameStatus != "O")) { Console.WriteLine("IT'S A TIE!!!\n"); Console.WriteLine("WOULD YOU LIKE TO PLAY AGAIN? (y or n)\n\n"); userResponse = Console.ReadLine(); gameStatus = "T"; } //continue to get player moves while the there is no winner and no tie } while ((gameStatus != "X") & (gameStatus != "O") & (gameStatus != "T")); //If the player chooses to quit then end the overall game loop. If the player chooses to continue playing start at the top of the outer do, while loop } while (userResponse != "n"); }//Run static void Main() { //Create an instance of the gameloop class and run it GameLoop g = new GameLoop(); g.Run(); } }//End GameLoop }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HelperEditor.Models { public class MantenimientoPersona { List<Persona> ListaPersona = new List<Persona>() { new Persona() { Codigo =1, Nombre = "Pedro", Peso = 67.3F, Trabaja = false, FechaNacimiento = new DateTime(2003,05,23) }, new Persona() { Codigo = 2, Nombre = "Pablo", Peso = 89.7F, Trabaja = true, FechaNacimiento = new DateTime(1998,12,23) }, new Persona() { Codigo =3, Nombre ="Lucas", Peso= 55.3F, Trabaja=false, FechaNacimiento= new DateTime(1985,05,19) } }; public Persona Retornar(int cod) { foreach (var per in ListaPersona) if (per.Codigo == cod) return per; return null; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore.Metadata.Conventions { /// <summary> /// A convention that configures the OnDelete behavior for foreign keys on the join entity type for /// self-referencing skip navigations /// </summary> public class SqlServerOnDeleteConvention : CascadeDeleteConvention, ISkipNavigationForeignKeyChangedConvention { /// <summary> /// Creates a new instance of <see cref="SqlServerOnDeleteConvention" />. /// </summary> /// <param name="dependencies"> Parameter object containing dependencies for this convention. </param> /// <param name="relationalDependencies"> Parameter object containing relational dependencies for this convention. </param> public SqlServerOnDeleteConvention( ProviderConventionSetBuilderDependencies dependencies, RelationalConventionSetBuilderDependencies relationalDependencies) : base(dependencies) { } /// <inheritdoc /> public virtual void ProcessSkipNavigationForeignKeyChanged( IConventionSkipNavigationBuilder skipNavigationBuilder, IConventionForeignKey? foreignKey, IConventionForeignKey? oldForeignKey, IConventionContext<IConventionForeignKey> context) { if (foreignKey is not null && foreignKey.IsInModel) { foreignKey.Builder.OnDelete(GetTargetDeleteBehavior(foreignKey)); } } /// <inheritdoc /> protected override DeleteBehavior GetTargetDeleteBehavior(IConventionForeignKey foreignKey) { var deleteBehavior = base.GetTargetDeleteBehavior(foreignKey); if (deleteBehavior != DeleteBehavior.Cascade) { return deleteBehavior; } if (foreignKey.IsBaseLinking()) { return DeleteBehavior.ClientCascade; } var selfReferencingSkipNavigation = foreignKey.GetReferencingSkipNavigations() .FirstOrDefault(s => s.Inverse != null && s.TargetEntityType == s.DeclaringEntityType); if (selfReferencingSkipNavigation == null) { return deleteBehavior; } if (selfReferencingSkipNavigation == selfReferencingSkipNavigation.DeclaringEntityType.GetDeclaredSkipNavigations() .First(s => s == selfReferencingSkipNavigation || s == selfReferencingSkipNavigation.Inverse) && selfReferencingSkipNavigation != selfReferencingSkipNavigation.Inverse) { selfReferencingSkipNavigation.Inverse!.ForeignKey?.Builder.OnDelete( GetTargetDeleteBehavior(selfReferencingSkipNavigation.Inverse.ForeignKey)); return DeleteBehavior.ClientCascade; } return deleteBehavior; } } }
using System; using System.Diagnostics; using System.Threading.Tasks; namespace NetworkToolkit.Tests { public class TestsBase { public int DefaultTestTimeout = 500; // in milliseconds. public async Task RunClientServer(Func<Task> clientFunc, Func<Task> serverFunc, int? millisecondsTimeout = null) { Task[] tasks = new[] { Task.Run(() => clientFunc()), Task.Run(() => serverFunc()) }; if (Debugger.IsAttached) { await tasks.WhenAllOrAnyFailed().ConfigureAwait(false); } else { await tasks.WhenAllOrAnyFailed(millisecondsTimeout ?? DefaultTestTimeout).ConfigureAwait(false); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JpaddressMultiRowSample { class AddressData { /** * 郵便番号 */ public string postal { get; set; } /** * 住所(漢字) */ public string address1 { get; set; } /** * 住所(カナ) */ public string address_kana { get; set; } } }
using CRM.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CRM.Service.Services.Interfaces { public interface IOfferService { void Insert(Offer entity); void Update(Offer entity); void Delete(Offer entity); void Delete(Guid id); Offer Find(Guid id); IEnumerable<Offer> GetAll(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public void PlayGame() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } public void LearnToPlay() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 2); } public void Story() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 3); } public void Credits() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 4); } }
using System; using System.Collections.Generic; #nullable disable namespace APIpoc.Models { public partial class TblProductImage { public int Id { get; set; } public int ProductId { get; set; } public string ImageName { get; set; } public string Src { get; set; } public virtual TblProduct Product { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using IdentityModel.Client; using ImageGallery.API.Client.Console.Classes; using ImageGallery.API.Client.Service.Classes; using ImageGallery.API.Client.Service.Configuration; using ImageGallery.API.Client.Service.Helpers; using ImageGallery.API.Client.Service.Interface; using ImageGallery.API.Client.Service.Models; using ImageGallery.API.Client.Service.Providers; using ImageGallery.API.Client.Service.Services; using ImageGallery.FlickrService; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Serilog; namespace ImageGallery.API.Client.Console { public class Program { /// <summary> /// /// </summary> public static IConfiguration Configuration { get; } = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true) .Build(); public static ITokenProvider TokenProvider { get; set; } public static IImageService ImageService { get; set; } public static IImageSearchService ImageSearchService { get; set; } public static int Main(string[] args) => MainAsync().GetAwaiter().GetResult(); private static async Task<int> MainAsync() { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); IConfiguration configuration = Configuration; var login = configuration["imagegallery-api:login"]; var password = configuration["imagegallery-api:password"]; var api = configuration["imagegallery-api:api"]; var imageGalleryApi = configuration["imagegallery-api:uri"]; TokenResponse token; try { Metric.Start("token"); token = await TokenProvider.RequestResourceOwnerPasswordAsync(login, password, api); token.Show(); } finally { Metric.StopAndWriteConsole("token"); } try { Metric.Start("Flickr Search and Post"); // start processing // waitForPostComplete is true by default, waiting when image has finished upload // if we don't need to wait (e.g. no afterward actions are needed) we can set it to false to speed up even more await PerformGetAndPost(token, imageGalleryApi, 30, true); } finally { Metric.StopAndWriteConsole("NEW flickrimg"); } try { Metric.Start("get"); await GoGetImageGalleryApi(token, imageGalleryApi); } finally { Metric.StopAndWriteConsole("get"); } System.Console.ReadLine(); return 0; } /// <summary> /// Uses conveyor queue logic to process images as soon as they are available /// </summary> /// <param name="token">Token</param> /// <param name="apiUri">ImageGallery Api Uri</param> /// <param name="threadCount"></param> /// <param name="waitForPostComplete"></param> /// <returns> /// A <see cref="Task"/> representing the asynchronous operation. /// </returns> private static async Task<string> PerformGetAndPost(TokenResponse token, string apiUri, int threadCount, bool waitForPostComplete) { var limit = System.Net.ServicePointManager.DefaultConnectionLimit; System.Net.ServicePointManager.DefaultConnectionLimit = threadCount * 2; ThreadPool.SetMinThreads(threadCount * 2, 4); var searchOptions = new SearchOptions { PhotoSize = "z", MachineTags = "machine_tags => nycparks:", }; try { // start search processing ImageSearchService.StartImagesSearchQueue(searchOptions, threadCount); int asyncCount = 0; // use single client for all queries using (var client = new HttpClient()) { client.SetBearerToken(token.AccessToken); // do while image search is running, image queue is not empty or there are some async tasks left while (ImageSearchService.IsSearchRunning || !ImageSearchService.ImageForCreations.IsEmpty || asyncCount > 0) { // get image from queue if (!ImageSearchService.ImageForCreations.TryDequeue(out var image)) continue; // wait for available threads while (asyncCount > threadCount) // http threads could stuck if there are too many. had to tweak this param { await Task.Delay(5); } asyncCount++; //run new processing thread ThreadPool.QueueUserWorkItem(state => { try { var status = GoPostImageGalleryApi(client, image, apiUri, waitForPostComplete).GetAwaiter().GetResult(); if (!status.IsSuccessStatusCode) { Log.Error($"{status.StatusCode.ToString()}"); } } finally { asyncCount--; } }); } } // Return Status Code return "Sucess"; } finally { System.Net.ServicePointManager.DefaultConnectionLimit = limit; } } /// <summary> /// Image Gallery API - Post Message /// </summary> /// <param name="client"></param> /// <param name="image"></param> /// <param name="apiUri"></param> /// <param name="waitForPostComplete"></param> /// <returns></returns> private static async Task<HttpResponseMessage> GoPostImageGalleryApi(HttpClient client, ImageForCreation image, string apiUri, bool waitForPostComplete) { Log.Information("ImageGalleryAPI Post {@Image}", image.ToString()); // TODO - Add Errors to be Handled var serializedImageForCreation = JsonConvert.SerializeObject(image); var response = await client.PostAsync( $"{apiUri}/api/images", new StringContent(serializedImageForCreation, System.Text.Encoding.Unicode, "application/json")) .ConfigureAwait(waitForPostComplete); // TODO - Log Transaction Time/Sucess Message if (waitForPostComplete) Log.Information("{@Status} Post Complete {@Image}", response.StatusCode, image.ToString()); return response; } /// <summary> /// Image Gallery API - Get Images /// </summary> /// <param name="token"></param> /// <param name="imageGalleryApi"></param> /// <returns></returns> private static async Task<string> GoGetImageGalleryApi(TokenResponse token, string imageGalleryApi) { // call api var client = new HttpClient(); client.SetBearerToken(token.AccessToken); var response = await client.GetAsync($"{imageGalleryApi}/api/images"); if (!response.IsSuccessStatusCode) { System.Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); var images = JsonConvert.DeserializeObject<List<ImageModel>>(content); System.Console.WriteLine(JArray.Parse(content)); System.Console.WriteLine($"ImagesCount:{images.Count}"); return content; } return null; } private static void ConfigureServices(IServiceCollection serviceCollection) { try { var log = new LoggerConfiguration() .WriteTo.ColoredConsole() .CreateLogger(); Log.Logger = log; Log.Information("The global logger has been configured"); Metric.Start("config"); serviceCollection.AddSingleton(new LoggerFactory() .AddConsole() .AddDebug()); serviceCollection.AddLogging(); serviceCollection.AddOptions(); serviceCollection.Configure<OpenIdConnectConfiguration>(Configuration.GetSection("openIdConnectConfiguration")); var openIdConfig = Configuration.GetSection("openIdConnectConfiguration").Get<OpenIdConnectConfiguration>(); var flickrConfig = Configuration.GetSection("flickrConfiguration").Get<FlickrConfiguration>(); var serviceProvider = new ServiceCollection() .AddScoped<ITokenProvider>(_ => new TokenProvider(openIdConfig)) .AddScoped<ISearchService>(_ => new SearchService(flickrConfig.ApiKey, flickrConfig.Secret)) .AddScoped<IImageService, ImageService>() .AddScoped<IImageSearchService, ImageSearchService>() .BuildServiceProvider(); TokenProvider = serviceProvider.GetRequiredService<ITokenProvider>(); ImageService = serviceProvider.GetRequiredService<IImageService>(); ImageSearchService = serviceProvider.GetRequiredService<IImageSearchService>(); } finally { Metric.StopAndWriteConsole("config"); } } } }
using System; using System.Collections.Generic; using System.Text; namespace KekManager.Domain { public class Subject { public int Id { get; set; } public string Name { get; set; } public int? SupervisorId { get; set; } public ResearchFellow Supervisor { get; set; } public ICollection<Kek> Keks { get; set; } public ICollection<Pek> Peks { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; using System.Diagnostics; namespace Combination { public partial class 机台日报表 : Form { public 机台日报表() { InitializeComponent(); } DataTable dtPO = new DataTable(); DataTable dt = new DataTable(); DataTable dtMachine = new DataTable(); Sql sql = new Sql(); int temp; private void btnSeek_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; try { dataGridView1.Rows.Clear(); string query = @"select a.ID,a.Mcode,a.MName,a.OOrder,a.OID,a.OPName,a.Ohour,a.PHour,a.POPcs,a.PPPcs,a.報廢kg,a.損耗率,case when a.預計產量 = 0 then 0 else a.PPPcs/a.預計產量 end as 績效,case when a.應有產量 = 0 then 0 else a.PPPcs/a.應有產量 end as 速度達成率,a.PNote1,a.PNote2 from ((select a.ID,a.MCode,a.Mname,a.OOrder,a.OID,a.OPName,a.OHour,b.PHour,b.POPcs,b.PPPcs,case when a.FNumber like '12.C%' then (b.POPcs-b.PPPcs)*(a.F_122)/1000 else (b.POPcs-b.PPPcs)*(a.F_123+a.F_122)/1000 end as 報廢kg, case when b.POPcs = b.PPPcs then '0' else (b.POPcs- b.PPPcs)/b.POPcs end as 損耗率,b.PNote1,b.PNote2, case when a.F_102 = '0' or a.F_108 = '0' or a.F_110 = '0' then '0' else (case when a.MUnit = 'KG' then (case when a.Fnumber like '12.C%' then ((b.Phour*a.MSpeed*60*1000)/(a.F_122)) else ((b.Phour*a.MSpeed*60*1000)/(a.F_122+a.F_123)) end) when a.MUnit = '张' then (b.Phour*a.MSpeed*60*a.F_110) when a.MUnit = '箱' then (b.Phour*a.MSpeed*60*a.F_102) when a.MUnit = '米' then (b.Phour*(a.Mspeed*60*1000/a.F_108)*a.F_110) else (b.Phour*a.MSpeed*60) end) end as 應有產量, case when a.F_102 = '0' or a.F_108 = '0' or a.F_110 = '0' then '0' else (case when a.MUnit = 'KG' then (case when a.Fnumber like '12.C%' then ((b.Phour*a.MSpeed*60*1000)/(a.F_122)) else ((b.Phour*a.MSpeed*60*1000)/(a.F_122+a.F_123)) end) when a.MUnit = '张' then (a.Ohour*a.MSpeed*60*a.F_110) when a.MUnit = '箱' then (a.Ohour*a.MSpeed*60*a.F_102) when a.MUnit = '米' then (a.Ohour*(a.Mspeed*60*1000/a.F_108)*a.F_110) else (a.Ohour*a.MSpeed*60) end) end as 預計產量 from (select e.MCode,a.ODate,e.MName,a.OOrder,a.OID,a.OPName,a.OHour,a.ID,c.F_123,c.F_122,c.FNumber,e.MUnit,e.MSpeed,c.F_102,c.F_108,c.F_110 from [ChengyiYuntech].[dbo].[ProduceOrder] a ,["+ sql.CYDB +"].[dbo].[T_Icitem] c,["+ sql.CYDB +"].[dbo].[ICMO] d,[ChengyiYuntech].[dbo].[Machine] e " + "where a.OStatus = '1' and a.OSample = '0' and a.OID = d.Fbillno and d.FitemID = c.FitemID and a.OMachineCode = e.MCode and CONVERT(varchar,a.Odate,23) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "') a left join " + "(select POID, PHour, POPcs, PPPcs, PNote1, PNote2 from[ChengyiYuntech].[dbo].[ScanRecord]) b on a.ID = b.POID) union " + "(select a.ID, a.MCode, a.Mname, a.OOrder, a.OID, a.OPName, a.OHour, b.PHour, b.POPcs, b.PPPcs,case when a.FNumber like '12.C%' then(b.POPcs - b.PPPcs) * (a.F_122) / 1000 else (b.POPcs - b.PPPcs) * (a.F_123 + a.F_122) / 1000 end as 報廢kg, " + "case when b.POPcs = b.PPPcs then '0' else (b.POPcs - b.PPPcs) / b.POPcs end as 損耗率, b.PNote1, b.PNote2, " + "case when a.F_102 = '0' or a.F_108 = '0' or a.F_110 = '0' then '0' else (case when a.MUnit = 'KG' then(case when a.Fnumber like '12.C%' then((b.Phour * a.MSpeed * 60 * 1000) / (a.F_122)) else ((b.Phour * a.MSpeed * 60 * 1000) / (a.F_122 + a.F_123)) end) " + "when a.MUnit = '张' then(b.Phour * a.MSpeed * 60 * a.F_110) when a.MUnit = '箱' then(b.Phour * a.MSpeed * 60 * a.F_102) when a.MUnit = '米' then(b.Phour * (a.Mspeed * 60 * 1000 / a.F_108) * a.F_110) else (b.Phour * a.MSpeed * 60) end) end as 應有產量, " + "case when a.F_102 = '0' or a.F_108 = '0' or a.F_110 = '0' then '0' else (case when a.MUnit = 'KG' then(case when a.Fnumber like '12.C%' then((b.Phour * a.MSpeed * 60 * 1000) / (a.F_122)) else ((b.Phour * a.MSpeed * 60 * 1000) / (a.F_122 + a.F_123)) end) " + "when a.MUnit = '张' then(a.Ohour * a.MSpeed * 60 * a.F_110) when a.MUnit = '箱' then(a.Ohour * a.MSpeed * 60 * a.F_102) when a.MUnit = '米' then(a.Ohour * (a.Mspeed * 60 * 1000 / a.F_108) * a.F_110) else (a.Ohour * a.MSpeed * 60) end) end as 預計產量 from " + "(select e.MCode, a.ODate, e.MName, a.OOrder, a.OID, a.OPName, a.OHour, a.ID, c.F_123, c.F_122, c.FNumber, e.MUnit, e.MSpeed, c.F_102, c.F_108, c.F_110 from[ChengyiYuntech].[dbo].[ProduceOrder] a " + ",["+ sql.CKDB +"].[dbo].[T_Icitem] c,["+ sql.CKDB +"].[dbo].[ICMO] d,[ChengyiYuntech].[dbo].[Machine] e " + "where a.OStatus = '1' and a.OSample = '0' and a.OID = d.Fbillno and d.FitemID = c.FitemID and a.OMachineCode = e.MCode and CONVERT(varchar, a.Odate, 23) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "') a left join " + "(select POID, PHour, POPcs, PPPcs, PNote1, PNote2 from[ChengyiYuntech].[dbo].[ScanRecord]) b on a.ID = b.POID) union " + "(select a.ID, e.MCode, e.Mname, a.OOrder, a.OID, a.OPName, a.OHour, '' as PHour, '' as POPcs, '' as PPPcs, '' as 報廢kg, '' as 損耗率, '' as PNote1, '' as PNote2, '' as 應有產量, '' as 預計產量 " + "from[ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[Machine] e where a.OStatus = '0' and a.OSample = '0' and a.OMachineCode = e.MCode and CONVERT(varchar, a.Odate, 23) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "') union " + "(select '' as ID, 'ZZ' as Mcode, '' as MName, '' as OOrder, '' as OID, '小計' as OPName, isnull(Sum(a.OHour), 0) as Ohour, isnull(SUM(a.PHour), 0) as PHour, isnull(SUM(a.POPcs), 0) as POPcs, isNull(SUM(a.PPPcs), 0) as PPPcs, isnull(SUM(a.報廢kg), 0) as 報廢kg, '' as 損耗率, '' as PNote1, '' as Pnote2, '' as 應有產量, '' as 預計產量 from " + "((select a.MCode, a.Mname, a.OOrder, a.OID, a.OPName, a.OHour, b.PHour, b.POPcs, b.PPPcs,case when a.FNumber like '12.C%' then(b.POPcs - b.PPPcs) * (a.F_122) / 1000 else (b.POPcs - b.PPPcs) * (a.F_123 + a.F_122) / 1000 end as 報廢kg, " + "case when b.POPcs = b.PPPcs then '0' else (b.POPcs - b.PPPcs) / b.POPcs end as 損耗率, b.PNote1, b.PNote2 from " + "(select e.MCode, a.ODate, e.MName, a.OOrder, a.OID, a.OPName, a.OHour, a.ID, c.F_123, c.F_122, c.FNumber from[ChengyiYuntech].[dbo].[ProduceOrder] a " + ",["+ sql.CYDB +"].[dbo].[T_Icitem] c,["+ sql.CYDB +"].[dbo].[ICMO] d,[ChengyiYuntech].[dbo].[Machine] e " + "where a.OStatus = '1' and a.OSample = '0' and a.OID = d.Fbillno and d.FitemID = c.FitemID and a.OMachineCode = e.MCode and CONVERT(varchar, a.Odate, 23) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "') a left join " + "(select POID, PHour, POPcs, PPPcs, PNote1, PNote2 from[ChengyiYuntech].[dbo].[ScanRecord]) b on a.ID = b.POID) union " + "(select a.MCode, a.Mname, a.OOrder, a.OID, a.OPName, a.OHour, b.PHour, b.POPcs, b.PPPcs,case when a.FNumber like '12.C%' then(b.POPcs - b.PPPcs) * (a.F_122) / 1000 else (b.POPcs - b.PPPcs) * (a.F_123 + a.F_122) / 1000 end as 報廢kg, " + "case when b.POPcs = b.PPPcs then '0' else (b.POPcs - b.PPPcs) / b.POPcs end as 損耗率, b.PNote1, b.PNote2 from " + "(select e.MCode, a.ODate, e.MName, a.OOrder, a.OID, a.OPName, a.OHour, a.ID, c.F_123, c.F_122, c.FNumber from[ChengyiYuntech].[dbo].[ProduceOrder] a " + ",["+ sql.CKDB +"].[dbo].[T_Icitem] c,["+ sql.CKDB +"].[dbo].[ICMO] d,[ChengyiYuntech].[dbo].[Machine] e " + "where a.OStatus = '1' and a.OSample = '0' and a.OID = d.Fbillno and d.FitemID = c.FitemID and a.OMachineCode = e.MCode and CONVERT(varchar, a.Odate, 23) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "') a left join " + "(select POID, PHour, POPcs, PPPcs, PNote1, PNote2 from[ChengyiYuntech].[dbo].[ScanRecord]) b on a.ID = b.POID) union " + "(select e.MCode, e.Mname, a.OOrder, a.OID, a.OPName, a.OHour, '' as PHour, '' as POPcs, '' as PPPcs, '' as 報廢kg, '' as 損耗率, '' as PNote1, '' as PNote2 " + "from[ChengyiYuntech].[dbo].[ProduceOrder] a,[ChengyiYuntech].[dbo].[Machine] e where a.OStatus = '0' and a.OSample = '0' and a.OMachineCode = e.MCode and CONVERT(varchar, a.Odate, 23) = '" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "')) a))a order by a.Mcode,a.OOrder,a.ID"; dt = sql.getQuery(query); foreach (DataRow item in dt.Rows) { int n = dataGridView1.Rows.Add(); dataGridView1.Rows[n].Cells[0].Value = dateTimePicker1.Value.ToString("yyyy/MM/dd"); dataGridView1.Rows[n].Cells[1].Value = item["Mcode"].ToString(); dataGridView1.Rows[n].Cells[2].Value = item["Mname"].ToString(); dataGridView1.Rows[n].Cells[3].Value = item["OOrder"].ToString(); dataGridView1.Rows[n].Cells[4].Value = item["OID"].ToString(); dataGridView1.Rows[n].Cells[5].Value = item["OPName"].ToString(); dataGridView1.Rows[n].Cells[6].Value = item["Ohour"].ToString(); dataGridView1.Rows[n].Cells[7].Value = item["PHour"].ToString(); dataGridView1.Rows[n].Cells[8].Value = Convert.ToDecimal(item["POPcs"]).ToString("N0"); dataGridView1.Rows[n].Cells[9].Value = Convert.ToDecimal(item["PPPcs"]).ToString("N0"); dataGridView1.Rows[n].Cells[10].Value = Convert.ToDecimal(item["報廢kg"]).ToString("N2"); dataGridView1.Rows[n].Cells[11].Value = Convert.ToDecimal(item["損耗率"]).ToString("p"); dataGridView1.Rows[n].Cells[12].Value = Convert.ToDecimal(item["績效"]).ToString("p"); dataGridView1.Rows[n].Cells[13].Value = Convert.ToDecimal(item["速度達成率"]).ToString("p"); dataGridView1.Rows[n].Cells[14].Value = Convert.ToString(item["PNote1"]); dataGridView1.Rows[n].Cells[15].Value = Convert.ToString(item["PNote2"]); temp = n; } int count = dataGridView1.Rows.Count; dataGridView1.Rows[count - 1].Cells[0].Value = ""; dataGridView1.Rows[count - 1].Cells[1].Value = ""; dataGridView1.Rows[count - 1].Cells[11].Value = ""; dt.Clear(); if (dataGridView1.Rows.Count == 0) { MessageBox.Show("查无资料"); } } catch (System.InvalidCastException) { dt.Clear(); dataGridView1.Rows.Clear(); MessageBox.Show("查无资料"); } Cursor = Cursors.Default; } private void btnExport_Click(object sender, EventArgs e) { try { Export_Data(); } catch (Exception) { MessageBox.Show("请将先前导出关闭"); } } private void Export_Data() { if (dataGridView1.Rows.Count != 0) { Excel.Application excelApp; Excel._Workbook wBook; Excel._Worksheet wSheet; Excel.Range wRange; string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); string inputPath = System.Environment.CurrentDirectory; string exportPath = path + @"\机台日报表导出" + dateTimePicker1.Value.ToString("yyMMdd"); string filePath = inputPath + @"\机台日报表"; // 開啟一個新的應用程式 excelApp = new Excel.Application(); // 讓Excel文件可見 excelApp.Visible = false; // 停用警告訊息 excelApp.DisplayAlerts = false; // 加入新的活頁簿 excelApp.Workbooks.Add(Type.Missing); wBook = excelApp.Workbooks.Open(filePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false); // 設定活頁簿焦點 wBook.Activate(); wSheet = (Excel._Worksheet)wBook.Worksheets[1]; wSheet.Name = "机台日报表"; wSheet.Cells[2, 1] = "机台日报表 " + dateTimePicker1.Value.ToString("yyyy/MM/dd"); wRange = wSheet.Range[wSheet.Cells[2, 1], wSheet.Cells[2, 1]]; wRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // storing Each row and column value to excel sheet for (int i = 0; i < dataGridView1.Rows.Count; i++) { for (int j = 1; j < dataGridView1.ColumnCount; j++) { wSheet.Cells[i + 4, j] = Convert.ToString(dataGridView1.Rows[i].Cells[j].Value); if (Convert.ToDecimal(dataGridView1.Rows[i].Cells[7].Value) == 0) { wRange = wSheet.Range[wSheet.Cells[i + 4, 1], wSheet.Cells[i + 4, 15]]; wRange.Select(); wRange.Interior.Color = ColorTranslator.ToOle(Color.Yellow); } } } Excel.Range last = wSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); Excel.Range allRange = wSheet.get_Range("A1", last); allRange.Font.Size = "14"; allRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous; //格線 allRange.Columns.AutoFit(); //Save Excel wBook.SaveAs(exportPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); wBook = null; wSheet = null; wRange = null; excelApp = null; GC.Collect(); MessageBox.Show("导出成功"); } else { MessageBox.Show("请确认是否有资料"); } } private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex > -1) { string execute = Convert.ToString(this.dataGridView1.Rows[e.RowIndex].Cells["Column10"].Value); if (Convert.ToDecimal(execute) == 0) { dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow; } } } private void btnMSpdA_Click(object sender, EventArgs e) { Cursor = Cursors.Default; Process p = new Process(); string inputPath = System.Environment.CurrentDirectory; string fileName = @"\SpeedAnalysis.exe"; p.StartInfo.FileName = inputPath + fileName; p.Start(); Cursor = Cursors.WaitCursor; } private void btnWasted_Click(object sender, EventArgs e) { Process p = new Process(); string inputPath = System.Environment.CurrentDirectory; string fileName = @"\报废原因分析.exe"; p.StartInfo.FileName = inputPath + fileName; p.Start(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DataLayer; namespace RemindMyPassword { public partial class Login : BasePage { protected void Loginbtn_Click(object sender, EventArgs e) { RMPUser tryuser = new RMPUser(Convert.ToString(Loginname.GetValue()), Convert.ToString(Password.GetValue())); if (tryuser.Entity != null) { Session[Constants.S_User] = tryuser; user = tryuser; Warninglbl.Text = String.Empty; this.Response.Redirect("~/HomePage.aspx"); } else { Warninglbl.Text = wo.GetMessage("LoginFailed"); } } protected override void SetInitialValues() { Password.textMode = TextBoxMode.Password; PageTitle = "Welcome.aspx"; } } }
namespace Smart.Mock.Data.SqlServer; using Microsoft.SqlServer.TransactSql.ScriptDom; public static class MockExtensions { public static ValidateResult ValidateSql(this MockDbCommand command) { return ValidateSql(command, DefaultParser.Create()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", Justification = "Ignore")] public static ValidateResult ValidateSql(this MockDbCommand command, TSqlParser parser) { var result = new ValidateResult(); foreach (var executedCommand in command.ExecutedCommands) { using var reader = new StringReader(executedCommand.CommandText); parser.Parse(reader, out var errors); if (errors is not null) { result.AddErrors(errors); } } return result; } public static ValidateResult ValidateSql(this MockDbConnection connection) { return ValidateSql(connection, DefaultParser.Create()); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", Justification = "Ignore")] public static ValidateResult ValidateSql(this MockDbConnection connection, TSqlParser parser) { var result = new ValidateResult(); foreach (var command in connection.Commands) { foreach (var executedCommand in command.ExecutedCommands) { using var reader = new StringReader(executedCommand.CommandText); parser.Parse(reader, out var errors); if (errors is not null) { result.AddErrors(errors); } } } return result; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MonsterSpawnPoint : MonoBehaviour { MonsterManager monsterManager; public string grade; [SerializeField, Tooltip("디버깅용")] string monsterToSpawn; private void OnTriggerEnter2D(Collider2D _collision) { if (_collision.CompareTag("Player")) //플레이어가 범위 내에 들어오면 { if (monsterToSpawn == null) { Debug.LogError("몬스터가 할당되지 않았습니다!"); return; } SpawnMonster(); } } // Start is called before the first frame update void Start() { monsterManager = MonsterManager.instance; GetMonsterToSpawn(); } void GetMonsterToSpawn() { if (StageManager.Instance.PlayerRoom <= 3) //1STAGE { grade = "D"; } else if (StageManager.Instance.PlayerRoom <= 9) { grade = "C"; } else if (StageManager.Instance.PlayerRoom <= 12) { grade = "B"; } else if (StageManager.Instance.PlayerRoom > 12) { grade = "A"; } List<string> monsterList = monsterManager.GetMonstersNameWithGrade(grade); int index = Random.Range(0, monsterList.Count); monsterToSpawn = monsterList[index]; } void SpawnMonster() { GetMonsterToSpawn(); GameObject spawnedMonster = MonsterPoolManager.instance.GetObject(monsterToSpawn); MonsterManager.instance.ReportMonsterSpawned(spawnedMonster); HMonster spawnedMonsterComp = spawnedMonster.GetComponent<HMonster>(); spawnedMonster.transform.position = new Vector3(transform.position.x, transform.position.y, 0); float chan = monsterManager.player.GetComponent<Player>().stats.chanceOfSpawnGoldenMonster; if (Probability(chan)) { spawnedMonsterComp.MakeGoldenMonster(); } spawnedMonsterComp.OperateOnEnable(); Destroy(gameObject); } bool Probability(float _percentage) { int maxRange = 10000; int pickedValue = Random.Range(0, maxRange); int chance = (int)(((System.Math.Truncate(_percentage * 100f) * 0.01f) * 100f) + 1); Debug.Log($"{pickedValue}, {chance}"); return pickedValue < chance ? true : false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WeSeBoGe { public static class Prompt { public static string ShowDialog(string text, string caption) { Form prompt = new Form(); prompt.Width = 500; prompt.Height = 200; prompt.Text = caption; Label textLabel = new Label() { Left = 50, Top = 20, Text = text }; TextBox inputBox = new TextBox() { Left = 50, Top = 50, Width = 400 }; Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70 }; confirmation.DialogResult = DialogResult.OK; prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.Controls.Add(inputBox); prompt.ShowDialog(); if (prompt.DialogResult == DialogResult.OK) { return inputBox.Text; } else { prompt.Dispose(); return null; } } } }
using UnityEngine; using System.Collections; public class Bala : MonoBehaviour { //Creamos una objeto llamado proyectil public GameObject proyectil; //Creamos un vector llamado fuerza con valor x 0 y y 1000 public Vector2 fuerza = new Vector2(0,1000); Rigidbody2D rg; // Use this for initialization void Start () { //llamamos al rigidbody rg = GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { if(Input.GetKey(KeyCode.Space)) { //Creamos el proyectil y lo metemos en la variable nuevo_proyectil GameObject nuevo_proyectil =(GameObject) Instantiate(proyectil, transform.position, transform.rotation); //Extraemos en rigidbody para poder aplicarle una fuerza rg = nuevo_proyectil.GetComponent<Rigidbody2D>(); //A los dos segundos se destruye el proyectil que ha sido invocado Destroy(nuevo_proyectil, 2); //Aplicamos la fuerza con el vector que hemos creado arriba rg.AddForce(fuerza); } } void OnTriggerEnter2D(Collider2D objeto) { //Si se encuentra un objeto con el tag enemigo la bala se destruira if(objeto.transform.tag == "enemigo") { Destroy(gameObject); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Triangle.Test { [TestClass] public class TriangleTest { [TestMethod] [ExpectedException(typeof(ArgumentException), "Side can't be less than 0.")] public void ConstructBySides_Should_ThrowException_When_SideIsNegative() { Triangle.ConstructBySides(-5, 4, 8); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Sum of two sides can't be less than third side.")] public void ConstructBySides_Should_ThrowException_When_TheRuleOfTriangleIsNotPerformed() { Triangle.ConstructBySides(2, 4, 8); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Angle must be between 0 and 180 degrees.")] public void ConstructByAngleAnd2Sides_Should_ThrowException_When_AngleIsGreaterThen180Degrees() { Triangle.ConstructByAngleAnd2Sides(200, 3, 6); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Angle must be between 0 and 180 degrees.")] public void ConstructByAngleAnd2Sides_Should_ThrowException_When_AngleIsNegative() { Triangle.ConstructByAngleAnd2Sides(-60, 3, 6); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Side can't be less than 0.")] public void ConstructByAngleAnd2Sides_Should_ThrowException_When_SideIsNegative() { Triangle.ConstructByAngleAnd2Sides(60, -3, 6); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Side can't be less than 0.")] public void ConstructBySideAnd2Angles_Should_ThrowException_When_SideIsNegative() { Triangle.ConstructBySideAnd2Angles(-5, 60, 30); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Angle can't be less than 0.")] public void ConstructBySideAnd2Angles_Should_ThrowException_When_AngleIsNegative() { Triangle.ConstructBySideAnd2Angles(5, -60, 30); } [TestMethod] [ExpectedException(typeof(ArgumentException), "Sum of two angles can't be more than 180 degrees.")] public void ConstructBySideAnd2Angles_Should_ThrowException_When_SumOfAnglesIsGreaterThen180Degrees() { Triangle.ConstructBySideAnd2Angles(5, 150, 40); } [TestMethod] public void GetArea_Should_ReturnCorrectAnswer_When_TriangleIsCreated_By_Sides() { double sideA = 87; double sideB = 87; double sideC = 126; Triangle triangle = Triangle.ConstructBySides(sideA, sideB, sideC); double area = triangle.GetArea(); Assert.AreEqual(3780, area, 1e-10); } [TestMethod] public void GetArea_Should_ReturnCorrectAnswer_When_TriangleIsCreated_By_AngleAnd2Sides() { double angle = 30; double sideA = 40; double sideB = 20; Triangle triangle = Triangle.ConstructByAngleAnd2Sides(angle, sideA, sideB); double area = triangle.GetArea(); Assert.AreEqual(200, area, 1e-10); } [TestMethod] public void GetArea_Should_ReturnCorrectAnswer_When_TriangleIsCreated_By_SideAnd2Angles() { double side = 24; double angleA = 150; double angleB = 15; Triangle triangle = Triangle.ConstructBySideAnd2Angles(side, angleA, angleB); double area = triangle.GetArea(); Assert.AreEqual(144, area, 1e-10); } } }
using System; using System.Collections.Generic; namespace Practical_Assignment { public class Repository { Database db = null; protected static Repository repo; static Repository() { repo = new Repository(); } protected Repository() { db = new Database(Database.DatabaseFilePath); } #region objTask Items public static objTaskSet GetTaskSet(int itemId) { return repo.db.GetTaskSet(itemId); } public static IList<objTaskSet> GetTaskSets() { return repo.db.GetTaskSets(); } public static int InsertTaskSet(objTaskSet taskSetItem) { return repo.db.InsertTaskSet(taskSetItem); } public static int InsertTaskSets(IList<objTaskSet> taskSetItems) { return repo.db.InsertTaskSets(taskSetItems); } public static int DeleteTaskSet(objTaskSet taskSetItem) { return repo.db.DeleteTaskSet(taskSetItem); } public static int DeleteAllTaskSets() { return repo.db.DeleteAllTaskSets(); } public static long SaveTaskSet(objTaskSet taskSetItem) { return repo.db.SaveTaskSet(taskSetItem); } #endregion #region objTask Items public static objProjectData GetProjectData(int itemId) { return repo.db.GetProjectData(itemId); } public static IList<objProjectData> GetAllProjectData() { return repo.db.GetAllProjectData(); } public static long GetMaxObjProjectDataId() { return repo.db.GetMaxObjProjectDataId(); } public static int InsertProjectData(objProjectData projectData) { return repo.db.InsertProjectData(projectData); } public static int InsertProjectData(IList<objProjectData> projectData) { return repo.db.InsertAllProjectData(projectData); } public static int DeleteProjectData(objProjectData projectData) { return repo.db.DeleteProjectData(projectData); } public static int DeleteAllProjectData() { return repo.db.DeleteAllProjectData(); } public static long SaveProjectData(objProjectData projectData) { return repo.db.SaveProjectData(projectData); } #endregion } }
using System; using System.Reflection; namespace ODataQuery.Nodes { static class StringFunc { private static readonly MethodInfo contains = typeof(string).GetMethod(nameof(string.Contains), new[] { typeof(string) }); public static FunctionNode Contains(Node @string, Node value) => new FunctionNode(contains, @string, value); private static readonly MethodInfo startsWith = typeof(string).GetMethod(nameof(string.StartsWith), new[] { typeof(string) }); public static FunctionNode StartsWith(Node @string, Node value) => new FunctionNode(startsWith, @string, value); private static readonly MethodInfo endsWith = typeof(string).GetMethod(nameof(string.EndsWith), new[] { typeof(string) }); public static FunctionNode EndsWith(Node @string, Node value) => new FunctionNode(endsWith, @string, value); private static readonly MethodInfo indexOf = typeof(string).GetMethod(nameof(string.IndexOf), new[] { typeof(string) }); public static FunctionNode IndexOf(Node @string, Node value) => new FunctionNode(indexOf, @string, value); private static readonly MethodInfo length = typeof(string).GetProperty(nameof(string.Length)).GetGetMethod(); public static PropertyNode Length(Node @string) => new PropertyNode(length, @string); private static readonly MethodInfo substring1 = typeof(string).GetMethod(nameof(string.Substring), new[] { typeof(int) }); public static FunctionNode Substring(Node @string, Node from) => new FunctionNode(substring1, @string, from); private static readonly MethodInfo substring2 = typeof(string).GetMethod(nameof(string.Substring), new[] { typeof(int), typeof(int) }); public static FunctionNode Substring(Node @string, Node from, Node length) => new FunctionNode(substring2, @string, from, length); private static readonly MethodInfo toUpper = typeof(string).GetMethod(nameof(string.ToUpper), Type.EmptyTypes); public static FunctionNode ToUpper(Node @string) => new FunctionNode(toUpper, @string); private static readonly MethodInfo toLower = typeof(string).GetMethod(nameof(string.ToLower), Type.EmptyTypes); public static FunctionNode ToLower(Node @string) => new FunctionNode(toLower, @string); private static readonly MethodInfo trim = typeof(string).GetMethod(nameof(string.Trim), Type.EmptyTypes); public static FunctionNode Trim(Node @string) => new FunctionNode(trim, @string); private static readonly MethodInfo concat = typeof(string).GetMethod(nameof(string.Concat), BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string), typeof(string) }, null); public static FunctionNode Concat(Node string1, Node string2) => new FunctionNode(concat, null, string1, string2); } static class DateFunc { private static readonly MethodInfo year1 = typeof(DateTime).GetProperty(nameof(DateTime.Year)).GetGetMethod(); private static readonly MethodInfo year2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Year)).GetGetMethod(); public static DatePropertyNode Year(Node date) => new DatePropertyNode(year1, year2, date); private static readonly MethodInfo month1 = typeof(DateTime).GetProperty(nameof(DateTime.Month)).GetGetMethod(); private static readonly MethodInfo month2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Month)).GetGetMethod(); public static DatePropertyNode Month(Node date) => new DatePropertyNode(month1, month2, date); private static readonly MethodInfo day1 = typeof(DateTime).GetProperty(nameof(DateTime.Day)).GetGetMethod(); private static readonly MethodInfo day2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Day)).GetGetMethod(); public static DatePropertyNode Day(Node date) => new DatePropertyNode(day1, day2, date); private static readonly MethodInfo hour1 = typeof(DateTime).GetProperty(nameof(DateTime.Hour)).GetGetMethod(); private static readonly MethodInfo hour2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Hour)).GetGetMethod(); public static DatePropertyNode Hour(Node date) => new DatePropertyNode(hour1, hour2, date); private static readonly MethodInfo minute1 = typeof(DateTime).GetProperty(nameof(DateTime.Minute)).GetGetMethod(); private static readonly MethodInfo minute2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Minute)).GetGetMethod(); public static DatePropertyNode Minute(Node date) => new DatePropertyNode(minute1, minute2, date); private static readonly MethodInfo second1 = typeof(DateTime).GetProperty(nameof(DateTime.Second)).GetGetMethod(); private static readonly MethodInfo second2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Second)).GetGetMethod(); public static DatePropertyNode Second(Node date) => new DatePropertyNode(second1, second2, date); private static readonly MethodInfo date1 = typeof(DateTime).GetProperty(nameof(DateTime.Date)).GetGetMethod(); private static readonly MethodInfo date2 = typeof(DateTimeOffset).GetProperty(nameof(DateTimeOffset.Date)).GetGetMethod(); public static DatePropertyNode Date(Node date) => new DatePropertyNode(date1, date2, date); } static class NumberFunc { public static Node Round(Node number) => new MathNode(nameof(Math.Round), number); public static Node Floor(Node number) => new MathNode(nameof(Math.Floor), number); public static Node Ceiling(Node number) => new MathNode(nameof(Math.Ceiling), number); } }
// Copyright 2019 Google Inc. All Rights Reserved. // // 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; using System.Runtime.InteropServices; namespace NtApiDotNet { /// <summary> /// Safe buffer for token privileges. /// </summary> public class SafeTokenPrivilegesBuffer : SafeStructureInOutBuffer<TokenPrivileges> { /// <summary> /// Constructor. /// </summary> /// <param name="privs">List of privileges.</param> public SafeTokenPrivilegesBuffer(LuidAndAttributes[] privs) : base(new TokenPrivileges() { PrivilegeCount = privs.Length }, Marshal.SizeOf(typeof(LuidAndAttributes)) * privs.Length, true) { Data.WriteArray(0, privs, 0, privs.Length); } private SafeTokenPrivilegesBuffer() : base(IntPtr.Zero, 0, false) { } /// <summary> /// NULL safe buffer. /// </summary> new public static SafeTokenPrivilegesBuffer Null { get { return new SafeTokenPrivilegesBuffer(); } } } #pragma warning restore 1591 }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Atendimento_V2 { class Senhas { //atributos private int proximoAtendimento; private Queue<Senha> filaSenhas; //própriedades getter e setter public void setProximoAtendimento(int value) { this.proximoAtendimento += value; } public void setSenha(Senha senha) { this.filaSenhas.Enqueue(senha); } public int getProximoAtendimento() { return this.proximoAtendimento; } public Senha getSenha() { return this.filaSenhas.Dequeue(); } //Construtor public Senhas() { filaSenhas = new Queue<Senha>(); setProximoAtendimento(1); } //métodos funcionais public void gerarSenha() { Senha senha = new Senha(getProximoAtendimento()); setSenha(senha); setProximoAtendimento(1); } public List<String> dadosResumido() { List<String> senhas = new List<string>(); foreach (Senha s in filaSenhas) { senhas.Add(s.dadosParciais()); } return senhas; } public int contarSenhas() { return this.filaSenhas.Count; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIController : MonoBehaviour { //UI界面 public GameObject UIVisual; //物体和玩家之间的最大UI可见距离 [SerializeField] private float mMaxDistanceForUI=1; /// <summary> /// 必须设置的函数 /// </summary> public void SetMaxDistanceForUI(float _maxDistanceForUI) { mMaxDistanceForUI = _maxDistanceForUI; } //判断 public void ShowUI_Update() { if (Vector2.Distance(transform.position, GameManager.GetInstance().GetGamePlayer().transform.position) <= mMaxDistanceForUI) { UIVisual.SetActive(true); } else { UIVisual.SetActive(false); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { ShowUI_Update(); } }
namespace ns13 { using System; using System.Runtime.CompilerServices; [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)] internal sealed class Attribute25 : Attribute { [CompilerGenerated] private string string_0; public Attribute25() { } public Attribute25([Attribute2] string anonymousProperty) { this.String_0 = anonymousProperty; } [Attribute2] public string String_0 { [CompilerGenerated] get { return this.string_0; } [CompilerGenerated] private set { this.string_0 = value; } } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace ORMHandsOn { public class StudentConfiguration : EntityTypeConfiguration<Student> { public StudentConfiguration() { ToTable("Students"); Property(s => s.Id).HasColumnName("Id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); Property(s => s.Name).HasColumnName("Name"); Property(s => s.Age).HasColumnName("Age"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TipsGenerator : MonoBehaviour { public int intTip; public enum endCondition { PressB, PressA, ScopeAndShoot, ScopeAndShootBrambles, EnumShoot, Move, Dash, Net, Equip, BigJump, Key, EndKey, DashTempete, TirTempete, DashIllu } public endCondition m_condition; bool isShowingTip; bool jump; bool dontShowTipAgain; public string SFXName; float clockHide; bool canHide; bool canClockHide; bool canPlaySFX; public GameObject gameObjectNeeded; private void Start() { canClockHide = true; canPlaySFX = true; } private void OnTriggerEnter(Collider other) { if (other.tag == "Player") { if (dontShowTipAgain == false ) { if (AudioManager.instance.sounds[0].source != null && canPlaySFX) { AudioManager.instance.Play(SFXName); canPlaySFX = false; } } if (isShowingTip == false) { Show(); } } } private void Update() { if (clockHide > 0) { clockHide -= Time.deltaTime; canHide = true; canClockHide = false; } else { if (canHide) { Hide(); canHide = false; canClockHide = true; } } if (m_condition == endCondition.PressA && isShowingTip) { if (Input.GetKeyDown(KeyCode.Joystick1Button0)) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.Dash && isShowingTip) { if (gameObjectNeeded.GetComponent<TriggerTips>().succes == true) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.DashTempete && isShowingTip) { if (Input.GetKeyDown(KeyCode.Joystick1Button2) && gameObjectNeeded.GetComponent<MovingCube>().CollideWithPlayer == true) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.DashIllu && isShowingTip) { if (Input.GetKeyDown(KeyCode.Joystick1Button2) && Character3D.m_instance.GetComponent<ButterflyTypeSelection>().SelectionTypeValue == 1) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.Net && isShowingTip) { if (Character3D.m_instance.GetComponent<ButterflyInventory>().ButterflyInInventoryValue >= 1) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.Equip && isShowingTip) { if (Input.GetKeyDown(KeyCode.Joystick1Button4) || Input.GetKeyDown(KeyCode.Joystick1Button5)) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.ScopeAndShoot && isShowingTip) { if (gameObjectNeeded.GetComponent<Receptacle>().Completed == true) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.ScopeAndShootBrambles && isShowingTip) { if (Input.GetAxis("Aim") > 0 && Input.GetAxisRaw("Fire1") == 1) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.Key && isShowingTip) { if (Input.GetKeyDown(KeyCode.Joystick1Button3)) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.BigJump && isShowingTip) { if (gameObjectNeeded.GetComponent<TriggerTips>().succes == true) { Hide(); dontShowTipAgain = true; } } if (m_condition == endCondition.EndKey && isShowingTip) { if (Input.GetAxisRaw("GiveKey") == 1 && KeyInventory.instance.GetKeyCount() >= 3) { Hide(); } if (KeyInventory.instance.GetKeyCount() < 3) { if (canClockHide) { clockHide = 5; } } } } private void Hide() { isShowingTip = false; TipsManager.instance.HideTip(TipsManager.TipType.BottomTip); } private void Show() { if (dontShowTipAgain == false) { TipsManager.instance.ShowTip(intTip, TipsManager.TipType.BottomTip); isShowingTip = true; } } }
using System; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; namespace PICSimulator.View { /// <summary> /// Interaction logic for RegisterBox.xaml /// </summary> public partial class RegisterBox : UserControl { public delegate void RegisterSelChangedEvent(uint reg); public event RegisterSelChangedEvent RegisterChanged; public uint Value { get { return Convert.ToUInt32(((box.SelectedItem as FrameworkElement).Tag as string), 16); } set { cstmBox.Text = Convert.ToString(value, 16); box.SelectedItem = cstmBox; } } public RegisterBox() { InitializeComponent(); box.SelectionChanged += (sender, e) => { if (RegisterChanged != null) RegisterChanged(Value); }; } private bool suppress_TC_Event = false; private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { if (suppress_TC_Event) return; TextBox t = sender as TextBox; if (t == null) return; if (t.Text.ToUpper() != t.Text) { int ss = t.SelectionStart; t.Text = t.Text.ToUpper(); t.SelectionStart = ss; } int tbv = TryB16(cstmBox.Text); if (tbv < 0) { suppress_TC_Event = true; cstmBox.Text = "00"; suppress_TC_Event = false; } if (tbv > 0xFF) { suppress_TC_Event = true; cstmBox.Text = "FF"; suppress_TC_Event = false; } string s = Convert.ToString(TryB16(cstmBox.Text), 16).ToUpper(); if (s != t.Text) { int ss = t.SelectionStart; t.Text = s; t.SelectionStart = ss; } cstmBox.Tag = s; } private int TryB16(string s) { try { return Convert.ToInt32(cstmBox.Text, 16); } catch { return -1; } } private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) { TextBox t = sender as TextBox; if (t == null) return; e.Handled = !(Regex.Match(e.Text, @"^[0-9A-Fa-f]$").Success && TryB16(t.Text + e.Text) >= 0x00 && TryB16(t.Text + e.Text) <= 0xFF); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Console2.From_026_To_050 { /* Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. */ // this question must can be done in 1. recursive 2. DP. // Additional though, what if can move to 8 directions? public class _036_MinSumPath { /// <summary> /// this method use recursive. /// </summary> /// <param name="input"></param> /// <returns></returns> public int FindMinSumPathRecursive(int[,] input) { int res = FindMinSumPathWorker(input, input.GetLength(0) - 1, input.GetLength(1) - 1); return res; } public int FindMinSumPathWorker(int[,] input, int i, int j) { if (i == 0 && j == 0) { return input[0, 0]; } int value1 = i - 1 >= 0 ? FindMinSumPathWorker(input, i - 1, j) : -1; int value2 = j - 1 >= 0 ? FindMinSumPathWorker(input, i, j - 1) : -1; if (value1 > 0 && value2 > 0) { return Math.Min(value1, value2) + input[i, j]; } else if (value1 < 0 && value2 < 0) { return -1; } else { return Math.Max(value1, value2) + input[i, j]; } } public int FindMinSumPathDP(int[,] input) { return 0; } } }
// *** WARNING: this file was generated by pulumigen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Outputs.Authorization.V1 { /// <summary> /// SubjectAccessReviewStatus /// </summary> [OutputType] public sealed class SubjectAccessReviewStatus { /// <summary> /// Allowed is required. True if the action would be allowed, false otherwise. /// </summary> public readonly bool Allowed; /// <summary> /// Denied is optional. True if the action would be denied, otherwise false. If both allowed is false and denied is false, then the authorizer has no opinion on whether to authorize the action. Denied may not be true if Allowed is true. /// </summary> public readonly bool Denied; /// <summary> /// EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request. /// </summary> public readonly string EvaluationError; /// <summary> /// Reason is optional. It indicates why a request was allowed or denied. /// </summary> public readonly string Reason; [OutputConstructor] private SubjectAccessReviewStatus( bool allowed, bool denied, string evaluationError, string reason) { Allowed = allowed; Denied = denied; EvaluationError = evaluationError; Reason = reason; } } }
using System.Collections; using UnityEngine; using UnityEngine.Events; public enum ObstacleSize { None = 0, VeryLow, Low, Medium, High, VeryHigh, Above1, Above2, Above3, Above4, Above5, Above6 } [System.Serializable] public class CapsuleColliderProperties { public float OffsetX; public float OffsetY; public float SizeX; public float SizeY; } public class CharacterController2D : MonoBehaviour { public PlayerAnimations Animator; [SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps. [SerializeField] private float m_BoostJumpMultiplier = 0f; // Multiplier of current horizontal velocity to boost forward when jumping [Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100% [Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement [SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping; [SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character [SerializeField] private CircleCollider2D m_GroundCheck; // A position marking where to check if the player is grounded. [SerializeField] private CircleCollider2D m_CeilingCheck; // A position marking where to check for ceilings [SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching [SerializeField] private CapsuleCollider2D CharacterCollider; [SerializeField] private CapsuleColliderProperties m_StandingCollider; [SerializeField] private CapsuleColliderProperties m_JumpingCollider; [SerializeField] private float m_groundApproachingDistance = 1f; public float MaxVerticalVelocityBeforeFallIsFatal; public float MaxVerticalVelocityBeforeClimbingIsImpossible; public Vector2 JumpFromSlidingForce; public Vector2 JumpFromClimbingForce; public GameObject CharacterDiesFromFallFX; private bool m_Grounded; // Whether or not the player is grounded. private bool m_Climbing; const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand up private Rigidbody2D m_Rigidbody2D; private bool m_FacingRight = true; // For determining which way the player is currently facing. public bool FacingRight => m_FacingRight; private Vector3 m_Velocity = Vector3.zero; private bool _hasJumped; private bool _dieOnLand; private bool _isControllable; private bool _interruptClimbToJump; private bool _hasWallJumped; private float allowJumpBecauseOfCoyoteTimeUntilThisTime; public float MaxCoyoteTimeTreshold; [Header("Climbing")] [Space] public Transform[] ObstacleRaycastStartPositions; public float FrontObstacleRaycastDistance = 0.2f; public float ClimbTransitionSpeed = 1f; public float MaxClimbDistanceIfObstacleIsTooHigh = 2f; public float MaxClimbDistanceAfterJumpIfObstacleIsTooHigh = 1f; [Header("Events")] [Space] public UnityEvent OnJumpEvent; public UnityEvent OnFallEvent; public UnityEvent OnLandEvent; public UnityEvent OnGroundApproachingEvent; public UnityEvent OnSlideStartEvent; public UnityEvent OnTurnAroundEvent; [System.Serializable] public class ObstacleClimbEvent : UnityEvent<ObstacleSize> { } public ObstacleClimbEvent OnClimbStartEvent; public UnityEvent OnClimbEndEvent; [System.Serializable] public class BoolEvent : UnityEvent<bool> { } public BoolEvent OnCrouchEvent; private bool m_wasCrouching = false; [Header("Sounds")] public AudioClip FallsHigh; public AudioClip ClimbSfx; private void Awake() { _isControllable = true; m_Rigidbody2D = GetComponent<Rigidbody2D>(); if (OnJumpEvent == null) OnJumpEvent = new UnityEvent(); if (OnFallEvent == null) OnFallEvent = new UnityEvent(); if (OnLandEvent == null) OnLandEvent = new UnityEvent(); if (OnGroundApproachingEvent == null) OnGroundApproachingEvent = new UnityEvent(); if (OnCrouchEvent == null) OnCrouchEvent = new BoolEvent(); if (OnClimbStartEvent == null) OnClimbStartEvent = new ObstacleClimbEvent(); if (OnClimbEndEvent == null) OnClimbEndEvent = new UnityEvent(); if (OnSlideStartEvent == null) OnSlideStartEvent = new UnityEvent(); if (OnTurnAroundEvent == null) OnTurnAroundEvent = new UnityEvent(); } private void Update() { bool wasGrounded = m_Grounded; m_Grounded = false; // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground // This can be done using layers instead but Sample Assets will not overwrite your project settings. Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.transform.position, m_GroundCheck.radius, m_WhatIsGround); for (int i = 0; i < colliders.Length; i++) { if (colliders[i].gameObject != gameObject) { m_Grounded = true; _obstacleCurrentlyClimbing = null; _hasJumped = false; //if (!wasGrounded) OnLandEvent.Invoke(); if (colliders[i].sharedMaterial != null && colliders[i].sharedMaterial.name == "SlidingSteep") { StartSliding(colliders[i].GetComponent<SteepGround>()); } if (_dieOnLand && !_dead) { Die(); } } } //Debug.DrawRay(m_GroundCheck.transform.position, Vector2.down * m_groundApproachingDistance, Color.green); var ground = Physics2D.CircleCast(m_GroundCheck.transform.position, m_GroundCheck.radius, Vector2.down, m_groundApproachingDistance, m_WhatIsGround); if (!m_Grounded && !m_Climbing && !wasGrounded && ground.collider != null && m_Rigidbody2D.velocity.y < 0) { OnGroundApproachingEvent.Invoke(); } else if (wasGrounded && !m_Grounded && !_hasJumped && !m_Climbing) { OnFallEvent.Invoke(); } if (!m_Grounded && -m_Rigidbody2D.velocity.y > MaxVerticalVelocityBeforeFallIsFatal && !_dieOnLand) { Debug.Log("fatal fall + " + (-m_Rigidbody2D.velocity.y)); GetComponent<AudioSource>().PlayOneShot(FallsHigh); _isControllable = false; _dieOnLand = true; Animator.StartFatalFall(); } if (m_Grounded) { ApplyColliderProperties(m_StandingCollider); } else { ApplyColliderProperties(m_JumpingCollider); } } private void ApplyColliderProperties(CapsuleColliderProperties properties) { CharacterCollider.offset = new Vector2(properties.OffsetX, properties.OffsetY); CharacterCollider.size = new Vector2(properties.SizeX, properties.SizeY); } public void StartSliding(SteepGround steepGroundToSlideOn) { if (_dieOnLand) { Debug.Log("Cancelling fatal fall"); var audio = GetComponent<AudioSource>(); if (audio.clip == FallsHigh) { audio.Stop(); } Animator.CancelFatalFall(); _dieOnLand = false; // Can't die from jumping on steep surfaces _isControllable = true; } //m_Rigidbody2D.simulated = false; GetComponent<SlidingCharacterController2D>().enabled = true; Animator.StartSliding(); enabled = false; } public void EndSliding(EndSlidingCondition condition) { //GetComponent<Rigidbody2D>().simulated = true; GetComponent<SlidingCharacterController2D>().enabled = false; enabled = true; Animator.EndSliding(); if (condition == EndSlidingCondition.Jump) { m_Grounded = false; m_Rigidbody2D.velocity = m_FacingRight ? JumpFromSlidingForce : new Vector2(-JumpFromSlidingForce.x, JumpFromSlidingForce.y); OnJumpEvent.Invoke(); } } private bool _dead; private void Die() { _dead = true; _isControllable = false; Instantiate(CharacterDiesFromFallFX, transform.position, Quaternion.Euler(0, 0, 0)); GetComponent<PlayerAttackable>().Die(m_Rigidbody2D.velocity * 100f); } public void MoveToEndOfLevel(Vector2 endOfLevelPosition) { _isControllable = false; StartCoroutine(_MoveToEndOfLevel(endOfLevelPosition)); } private IEnumerator _MoveToEndOfLevel(Vector2 endOfLevelPosition) { while (true) { transform.position = Vector3.MoveTowards(transform.position, endOfLevelPosition, 4f * Time.deltaTime); Animator.SetSpeed(1); yield return null; // Stop running when reaching the end if (Vector2.Distance(transform.position, endOfLevelPosition) < 0.1f) { Animator.SetSpeed(0); break; } } } public void Move(float move, bool crouch, bool jump) { if (!_isControllable) return; // If crouching, check to see if the character can stand up //if (!crouch) //{ // // If the character has a ceiling preventing them from standing up, keep them crouching // if (Physics2D.OverlapCircle(m_CeilingCheck.transform.position, k_CeilingRadius, m_WhatIsGround)) // { // crouch = true; // } //} //only control the player if grounded or airControl is turned on if (m_Grounded || m_AirControl) { // If crouching if (crouch) { if (!m_wasCrouching) { m_wasCrouching = true; OnCrouchEvent.Invoke(true); } // Reduce the speed by the crouchSpeed multiplier move *= m_CrouchSpeed; // Disable one of the colliders when crouching if (m_CrouchDisableCollider != null) m_CrouchDisableCollider.enabled = false; } else { // Enable the collider when not crouching if (m_CrouchDisableCollider != null) m_CrouchDisableCollider.enabled = true; if (m_wasCrouching) { m_wasCrouching = false; OnCrouchEvent.Invoke(false); } } // Move the character by finding the target velocity Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y); // And then smoothing it out and applying it to the character m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing); // If the input is moving the player right and the player is facing left if (move > 0 && !m_FacingRight) { // ... flip the player. Look(true); } // Otherwise if the input is moving the player left and the player is facing right else if (move < 0 && m_FacingRight) { // ... flip the player. Look(false); } } if (m_Grounded) allowJumpBecauseOfCoyoteTimeUntilThisTime = Time.time + MaxCoyoteTimeTreshold; // If the player should jump... if ((m_Grounded || allowJumpBecauseOfCoyoteTimeUntilThisTime > Time.time) && jump) { _hasJumped = true; allowJumpBecauseOfCoyoteTimeUntilThisTime = 0; if (!DetectAndClimbObstacle()) { //no obstacle: jump // Add vertical updwards force. // Also, if already moving in a direction, boost in that direction var jumpForce = new Vector2(move * m_BoostJumpMultiplier, m_JumpForce); Jump(jumpForce); } } else if (!m_Grounded && !m_Climbing && (Input.GetButton("Jump") || _hasWallJumped)) { // If obstacle is encountered mid-air and jump button is down, jump over it // Do the same if player comes from a wall jump because it makes controls easier DetectAndClimbObstacle(); } else if (m_Climbing && jump) { // if jumping while climbing, jump away from the wall m_Grounded = false; m_Climbing = false; m_Rigidbody2D.simulated = true; _interruptClimbToJump = true; _hasWallJumped = true; m_Rigidbody2D.velocity = m_FacingRight ? new Vector2(-JumpFromClimbingForce.x, JumpFromClimbingForce.y) : JumpFromClimbingForce; Look(!m_FacingRight); OnJumpEvent.Invoke(); } } private void Jump(Vector2 jumpForce, ForceMode2D forceMode2D = ForceMode2D.Force) { // Add a vertical force to the player. m_Grounded = false; m_Rigidbody2D.AddForce(jumpForce, forceMode2D); OnJumpEvent.Invoke(); } private bool DetectAndClimbObstacle() { // If something above, do not climb Collider2D[] colliders = Physics2D.OverlapCircleAll(m_CeilingCheck.transform.position, m_CeilingCheck.radius, m_WhatIsGround); for (int i = 0; i < colliders.Length; i++) { if (colliders[i].gameObject != gameObject) { return false; } } var obstacleSize = ObstacleSize.None; var obstacleApproxPosition = Vector2.zero; GameObject obstacleObject = null; for (var i = 0; i < ObstacleRaycastStartPositions.Length; ++i) { var startPos = ObstacleRaycastStartPositions[i]; var hit = Physics2D.Raycast(startPos.position, new Vector2(m_FacingRight ? 1 : -1, 0), FrontObstacleRaycastDistance, m_WhatIsGround); if (hit.collider != null) { obstacleSize = (ObstacleSize)(i + 1); obstacleApproxPosition = hit.point; obstacleObject = hit.collider.gameObject; } else if (obstacleSize == ObstacleSize.None && (ObstacleSize)(i + 1) == ObstacleSize.Above1) { // no obstacle in front up to a certain height. Even if there is something above, we don't want to climb on it return false; } } if (obstacleSize != ObstacleSize.None) { if (obstacleObject == _obstacleCurrentlyClimbing) return false; if (m_Rigidbody2D.velocity.y < -MaxVerticalVelocityBeforeClimbingIsImpossible) return false; // if there is an obstacle in front, climb it ClimbOverObstacle(obstacleSize, obstacleApproxPosition, obstacleObject); return true; } return false; } private GameObject _obstacleCurrentlyClimbing; private void ClimbOverObstacle(ObstacleSize obstacleSize, Vector2 obstacleApproxPosition, GameObject obstacleObject) { //Debug.Log($"Climb over obstacle {obstacleSize} ({obstacleObject.name}). grounded: {m_Grounded}, climbing: {m_Climbing}, haswalljumped: {_hasWallJumped}, interrupt: {_interruptClimbToJump}"); _obstacleCurrentlyClimbing = obstacleObject; if ((obstacleSize == ObstacleSize.Above6 && m_Grounded) || (obstacleSize >= ObstacleSize.Above3 && !m_Grounded)) { // if obstacle is too high, we can't go on top of it but we still try to climb it m_Climbing = true; // animate to this location m_Rigidbody2D.velocity = Vector2.zero; var targetPosition = new Vector2(transform.position.x, transform.position.y + (m_Grounded ? MaxClimbDistanceIfObstacleIsTooHigh : MaxClimbDistanceAfterJumpIfObstacleIsTooHigh)); StartCoroutine(MoveToTargetPosition(targetPosition)); GetComponent<AudioSource>().PlayOneShot(ClimbSfx); OnClimbStartEvent.Invoke(obstacleSize); } else { // identify where to land on the obstacle var hit = Physics2D.Raycast(obstacleApproxPosition + Vector2.up * 2, Vector3.down, 5, m_WhatIsGround); Debug.DrawRay(obstacleApproxPosition + Vector2.up * 2, Vector3.down * 5, Color.white, 2f); if (hit.collider != null) { Debug.DrawLine(new Vector3(hit.point.x - 1, hit.point.y, 1), new Vector3(hit.point.x + 1, hit.point.y, 1), Color.red, 2f); Debug.DrawLine(new Vector3(hit.point.x, hit.point.y - 1, 1), new Vector3(hit.point.x, hit.point.y + 1, 1), Color.red, 2f); //Debug.Log("position to reach : " + hit.point); m_Climbing = true; // animate to this location m_Rigidbody2D.velocity = Vector2.zero; StartCoroutine(MoveToTargetPosition(hit.point)); GetComponent<AudioSource>().PlayOneShot(ClimbSfx); OnClimbStartEvent.Invoke(obstacleSize); } } m_Grounded = false; } private IEnumerator MoveToTargetPosition(Vector2 targetPosition) { // The character is not moved by physics during climb m_Rigidbody2D.simulated = false; // First go up, then go forward var firstTargetPos = new Vector2(transform.position.x, targetPosition.y); var secondTargetPos = targetPosition; while (Vector2.Distance(transform.position, firstTargetPos) > 0.01f && !_interruptClimbToJump) { transform.position = Vector2.MoveTowards(transform.position, firstTargetPos, ClimbTransitionSpeed * Time.deltaTime); yield return new WaitForEndOfFrame(); } while (Vector2.Distance(transform.position, secondTargetPos) > 0.01f && !_interruptClimbToJump) { transform.position = Vector2.MoveTowards(transform.position, secondTargetPos, ClimbTransitionSpeed * Time.deltaTime); yield return new WaitForEndOfFrame(); } // Climbing is over (or cancelled) move it by physics again m_Rigidbody2D.simulated = true; OnClimbEndEvent.Invoke(); yield return new WaitForSeconds(0.3f); // player can still input a wall jump for a while so we wait before reading _interruptClimbToJump _hasWallJumped = _interruptClimbToJump; _interruptClimbToJump = false; m_Climbing = false; } private void Look(bool right) { // Switch the way the player is labelled as facing. if (m_FacingRight != right) OnTurnAroundEvent.Invoke(); m_FacingRight = right; // Multiply the player's x local scale by -1. Vector3 theScale = transform.localScale; if (right) theScale.x = Mathf.Abs(theScale.x); else theScale.x = -Mathf.Abs(theScale.x); //theScale.x *= -1; transform.localScale = theScale; } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Web.UI; using NopSolutions.NopCommerce.BusinessLogic.Products.Specs; using NopSolutions.NopCommerce.Common.Utils; using System.Web.UI.WebControls; using NopSolutions.NopCommerce.BusinessLogic.Colors; namespace NopSolutions.NopCommerce.Web.Administration.Modules { public partial class SpecificationAttributeInfoControl : BaseNopAdministrationUserControl { private void BindData() { SpecificationAttribute specificationAttribute = SpecificationAttributeManager.GetSpecificationAttributeByID(this.SpecificationAttributeID); if (specificationAttribute != null) { this.txtName.Text = specificationAttribute.Name; this.txtDisplayOrder.Value = specificationAttribute.DisplayOrder; } SpecificationAttributeOptionCollection saoCol = SpecificationAttributeManager.GetSpecificationAttributeOptionsBySpecificationAttribute(SpecificationAttributeID); grdSpecificationAttributeOptions.DataSource = saoCol; grdSpecificationAttributeOptions.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.BindData(); } if (SpecificationAttributeID <= 0) pnlSpecAttrOptions.Visible = false; } protected void btnAddSpecificationAttributeOption_Click(object sender, EventArgs e) { Response.Redirect("SpecificationAttributeOptionAdd.aspx?SpecificationAttributeID=" + this.SpecificationAttributeID); } public SpecificationAttribute SaveInfo() { SpecificationAttribute specificationAttribute = SpecificationAttributeManager.GetSpecificationAttributeByID(this.SpecificationAttributeID); if (specificationAttribute != null) { specificationAttribute = SpecificationAttributeManager.UpdateSpecificationAttribute(specificationAttribute.SpecificationAttributeID, txtName.Text, txtDisplayOrder.Value); ColorManager.UpdateColor(specificationAttribute.Name, txtName.Text); } else { specificationAttribute = SpecificationAttributeManager.InsertSpecificationAttribute(txtName.Text, txtDisplayOrder.Value); } return specificationAttribute; } protected void OnSpecificationAttributeOptionsCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "UpdateOption") { int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = grdSpecificationAttributeOptions.Rows[index]; SimpleTextBox txtName = row.FindControl("txtOptionName") as SimpleTextBox; NumericTextBox txtDisplayOrder = row.FindControl("txtOptionDisplayOrder") as NumericTextBox; HiddenField hfSpecificationAttributeOptionID = row.FindControl("hfSpecificationAttributeOptionID") as HiddenField; string name = txtName.Text; int displayOrder = txtDisplayOrder.Value; int saoID = int.Parse(hfSpecificationAttributeOptionID.Value); SpecificationAttributeOption sao = SpecificationAttributeManager.GetSpecificationAttributeOptionByID(saoID); if (sao != null) { SpecificationAttributeManager.UpdateSpecificationAttributeOptions(saoID, SpecificationAttributeID, name, displayOrder); ColorManager.UpdateColor(sao.Name, name); } BindData(); } } protected void OnSpecificationAttributeOptionsDeleting(object sender, GridViewDeleteEventArgs e) { int saoID = (int)grdSpecificationAttributeOptions.DataKeys[e.RowIndex]["SpecificationAttributeOptionID"]; SpecificationAttributeOption sao = SpecificationAttributeManager.GetSpecificationAttributeOptionByID(saoID); if (sao != null) { SpecificationAttributeManager.DeleteSpecificationAttributeOption(sao.SpecificationAttributeOptionID); string paletteFolderPath = Server.MapPath("~/images/palette/"); ColorManager.DeleteColor(sao.Name, paletteFolderPath); BindData(); } } protected void OnSpecificationAttributeOptionsDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Button btnUpdate = e.Row.FindControl("btnUpdate") as Button; if (btnUpdate != null) btnUpdate.CommandArgument = e.Row.RowIndex.ToString(); } } public int SpecificationAttributeID { get { return CommonHelper.QueryStringInt("SpecificationAttributeID"); } } } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; namespace PIT_Server { public static class Database { static Dictionary<string, Character> _chars; public static void Init() { _chars = new Dictionary<string, Character>(); Console.WriteLine(Lobby.SpacePorts.Count); Lobby.SpacePorts.TryAdd(new Spaceport(0, new Rocket(0)), null); Lobby.SpacePorts.TryAdd(new Spaceport(1, new Rocket(2)), null); Lobby.SpacePorts.TryAdd(new Spaceport(2, new Rocket(1)), null); for (int i = 0; i < 1000; i++) { _chars[i.ToString()] = new Character("user" + i + "" + i, i.ToString(), i.ToString()); } } public static bool Authenticate(string login, string pass) { Character c; try { _chars.TryGetValue(login, out c); } catch { return false; } if (c != null) if (c.Password == pass) return true; return false; } public static Character GetChar(string login) { return _chars[login]; } public static Character GetCharbyName(string name) { return _chars.Values.ToList<Character>().Find(new Predicate<Character>(x => x.Name == name)); } } public class Character { public string Name; public string Login; public string Password; public Character(string name, string login, string password) { Name = name; Login = login; Password = password; } public int[] GenerateLevels() { int[] lvls = new int[6]; return lvls; } } }
using System; using System.Collections.Generic; using System.Text; namespace FastSQL.Sync.Core.Enums { [Flags] public enum EntityType { Connection = 1, Entity = 2, Attribute = 4, Transformation = 8, Exporter = 16, PullResult = 32, PullDependencies = 64, ScheduleOption = 128, QueueItem = 256, Message = 512, MessageDeliveryChannelModel = 1024, Reporter = 2048 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Player : PhysicsObject { [Header("Attributes")] //Attributes private int maxHealth = 100; [SerializeField] private float maxSpeed = 1f; [SerializeField] private float jumpPower = 10; public int attackPower = 25; [SerializeField] private float attackDuration; [Header("Inventory")] //Linked to collectibles public int health = 100; public int ammo; public int coinsCollected; [Header("References")] [SerializeField] private GameObject attackBox; //Items public Sprite keySprite; public Sprite keyGemSprite; public Sprite inventoryItemBlank; //UI Ref private Vector2 healthBarOrigSize; //UI Ref public Dictionary<string, Sprite> inventory = new Dictionary<string, Sprite>(); //Singleton Instantiation private static Player instance; public static Player Instance { get { if (instance == null) instance = GameObject.FindObjectOfType<Player>(); return instance; } } private void Awake() { if (GameObject.Find("New Player")) Destroy(gameObject); } // Start is called before the first frame update void Start() { DontDestroyOnLoad(gameObject); gameObject.name = "New Player"; healthBarOrigSize = GameManager.Instance.healthBar.rectTransform.sizeDelta; UpdateUI(); SetSpawnPosition(); } // Update is called once per frame void Update() { //Left & Right movement targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0); //Time.deltaTime calc in PhysicsObject Script //Jump if (Input.GetButtonDown("Jump") && grounded) { velocity.y = jumpPower; //Vec2 var called in PO.cs } //Player turning if (targetVelocity.x < -.01) { transform.localScale = new Vector2(-1, 1); } else if (targetVelocity.x > .01) { transform.localScale = new Vector2(1, 1); } //use fire1 to set attackBox to active, otherwise set to false if (Input.GetButtonDown("Fire1")) { StartCoroutine(ActivateAttack()); } //Die if player health is 0 if (health <= 0) { Die(); } } //Activate Attack Function public IEnumerator ActivateAttack() { attackBox.SetActive(true); yield return new WaitForSeconds(attackDuration); attackBox.SetActive(false); } //Update UI elements public void UpdateUI() { if (healthBarOrigSize == Vector2.zero) healthBarOrigSize = GameManager.Instance.healthBar.rectTransform.sizeDelta; //Coins UI text = Coins collected GameManager.Instance.coinsText.text = coinsCollected.ToString(); //Set the HB width to a % of its original value //healthBar.x * (health / maxHealth) GameManager.Instance.healthBar.rectTransform.sizeDelta = new Vector2(healthBarOrigSize.x * ((float)health / (float)maxHealth), GameManager.Instance.healthBar.rectTransform.sizeDelta.y); } public void AddInventoryItem(string inventoryName, Sprite image) { inventory.Add(inventoryName, image); // The blank sprite should swap with the key sprite GameManager.Instance.inventoryItemImage.sprite = inventory[inventoryName]; } public void SetSpawnPosition() { transform.position = GameObject.Find("SpawnLocation").transform.position; } public void Die() { SceneManager.LoadScene("SampleScene"); } public void RemoveInventoryItem(string inventoryName) { inventory.Remove(inventoryName); // The blank sprite should swap with the key sprite GameManager.Instance.inventoryItemImage.sprite = inventoryItemBlank; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; namespace Server_Computer { public partial class Server_Computer : Form { public Server_Computer() { InitializeComponent(); } static public int portNumber; private void Server_Computer_Load(object sender, EventArgs e) { string host = Dns.GetHostName(); IPHostEntry ip = Dns.GetHostByName(host); string ipAdresi = ip.AddressList[0].ToString(); lblID.Text = ipAdresi; } ListenPorts lp; private void btn_Dinle_Click(object sender, EventArgs e) { portNumber = Convert.ToInt32(txt_Port.Text); timer1.Start(); #region Port Atama İşlemi IPEndPoint ipPoint = new IPEndPoint(IPAddress.Any, portNumber); IPEndPoint ipPoint1 = new IPEndPoint(IPAddress.Any, (portNumber + 1)); IPEndPoint[] ipPoints = new IPEndPoint[2] { ipPoint, ipPoint1 }; #endregion #region Port Dinleme lp = new ListenPorts(ipPoints); #endregion txt_AlınanVeri.Items.Add("Dinleniyor..."); #region Thread Çalıştırma lp.beginListen(); #endregion } private void btn_Durdur_Click(object sender, EventArgs e) { timer1.Stop(); txt_AlınanVeri.Items.Add("Server Durduruldu..."); } private void timer1_Tick(object sender, EventArgs e) { if (ListenPorts.aaaaa != null) { txt_AlınanVeri.Items.Add(ListenPorts.aaaaa); txt_AlınanVeri.Refresh(); } else return; } } }
using System; using System.Collections.Generic; namespace RestApiEcom.Models { public partial class TRCBatimentContribuable { public int AbcId { get; set; } public int? AbcContId { get; set; } public int? AbcBatId { get; set; } public DateTime? AbcDate { get; set; } public DateTime? AbcDateFin { get; set; } public virtual TCBatiment AbcBat { get; set; } public virtual TCContribuable AbcCont { get; set; } } }
namespace GameStoreApp.Data { using Microsoft.EntityFrameworkCore; public class TemplateDbContext : DbContext { public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder builder) { builder.UseSqlServer(@"Server=BALTSERVER\SQLEXPRESS;Database=TemplateDb;Integrated security=True"); } protected override void OnModelCreating(ModelBuilder builder) { builder .Entity<User>() .HasIndex(u => u.Email) .IsUnique(); } } }
// Author: 陈旭东 // Create date: 2015-4-8 // Description: 这个一般处理程序专门处理老师的事件方法 using System.Web; using System.Data; using System.Web.SessionState; using System; using System.Text; using System.Collections.Generic; using XGhms.Helper; using System.Collections; namespace XGhms.Web.Handles { /// <summary> /// TeacherHandler 的摘要说明 /// </summary> public class TeacherHandler : IHttpHandler, IRequiresSessionState { BLL.classes classBll = new BLL.classes(); BLL.college collegeBll = new BLL.college(); BLL.users_info userinfoBll = new BLL.users_info(); BLL.users userBll = new BLL.users(); BLL.term termBll = new BLL.term(); BLL.course courseBll = new BLL.course(); BLL.course_student courstuBll = new BLL.course_student(); BLL.course_homework courhwBll = new BLL.course_homework(); BLL.homework_student hwstuBll = new BLL.homework_student(); public void ProcessRequest(HttpContext context) { DataTable dt = new Common.TerPageBase().GetLoginUserInfo(); if (dt == null) { context.Response.Write("未登录或已超时,请重新登录!"); return; } //取得处事类型 string action = HttpContext.Current.Request["action"]; #region 根据不同的action执行不同的方法 switch (action) { case "GetClassInfoByTerIDClsID": GetClassInfoByTerIDClsID(context); break; case "CreateExcelByClassID": CreateExcelByClassID(context); break; case "SaveClassInfo": SaveClassInfo(context); break; case "GetTerCourseByTrem": GetTerCourseByTrem(context); break; case "GetStuListByCourseID": GetStuListByCourseID(context); break; case "GetCollegeList": GetCollegeList(context); break; case "SaveCourseInfo": SaveCourseInfo(context); break; case "GetCourseListByTerandTerm": GetCourseListByTerandTerm(context); break; case "GetHomeWorkListBytermAndCor": GetHomeWorkListBytermAndCor(context); break; case "GetHomeWorkTotalNumBytermAndCor": GetHomeWorkTotalNumBytermAndCor(context); break; case "deleteHomeWork": deleteHomeWork(context); break; case "GetStuListRandomByCourseID": GetStuListRandomByCourseID(context); break; case "GetCourseInfoBycid": GetCourseInfoBycid(context); break; case "addnewHW": addnewHW(context); break; case "GetAllClassByCollegeID": GetAllClassByCollegeID(context); break; case "GetAllTermForNow": GetAllTermForNow(context); break; case "CheckUserIDExist": CheckUserIDExist(context); break; case "GetCourseInfoByID": GetCourseInfoByID(context); break; case "updoldHW": updoldHW(context); break; case "GetHWInfoByid": GetHWInfoByid(context); break; case "GetHomeWorkTotalNumByThreeCS": GetHomeWorkTotalNumByThreeCS(context); break; case "GetHomeWorkListByByThreeCS": GetHomeWorkListByByThreeCS(context); break; case "deleteStuHomework": deleteStuHomework(context); break; case "GetStuHWInfoByID": GetStuHWInfoByID(context); break; case "CheckStudentWork": CheckStudentWork(context); break; case "ReformWork": ReformWork(context); break; case "GetNoCheckWorkNum": GetNoCheckWorkNum(context); break; case "GetCheckWorkNum": GetCheckWorkNum(context); break; case "GetThreeHWlistForDefault": GetThreeHWlistForDefault(context); break; case "GetTwentyScoreByCourseID": GetTwentyScoreByCourseID(context); break; //case "UpdateUserCourseByUserID": // UpdateUserCourseByUserID(context); // break; //case "DeleteStuFromCourse": // DeleteStuFromCourse(context); // break; //case "CreateExcelByCourseID": // CreateExcelByCourseID(context); // break; default: break; } #endregion } #region 根据班级ID获取班级信息 protected void GetClassInfoByTerIDClsID(HttpContext context) { context.Response.ContentType = "text/plain"; int classID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取班级ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (!classBll.Exists(classID)) { context.Response.Write("{\"msgtype\":0}"); context.Response.End(); return; } if (dt.Rows[0]["role_name"].ToString() == "HeadTeacher") { if (classBll.Exists(classID, userID)) { Model.classes classModel = classBll.GetModel(classID); StringBuilder str = new StringBuilder(); str.Append("{\"msgtype\":2,"); //表示该用户可以修改班级的信息 str.Append("\"class_name\":\"" + classModel.class_name + "\","); str.Append("\"college\":\"" + collegeBll.GetModel(classModel.college_id).college_name + "\","); str.Append("\"head_teacher\":\"你自己\","); str.Append("\"class_leader\":" + GetUserForDropdownList(classModel.class_leader) + ","); str.Append("\"squad_leader\":" + GetUserForDropdownList(classModel.squad_leader) + ","); str.Append("\"class_group_secretary\":" + GetUserForDropdownList(classModel.class_group_secretary) + ","); str.Append("\"study_secretary\":" + GetUserForDropdownList(classModel.study_secretary) + ","); str.Append("\"life_secretary\":" + GetUserForDropdownList(classModel.life_secretary)); str.Append("}"); context.Response.Write(str.ToString()); context.Response.End(); return; } } Model.classes classModel2 = classBll.GetModel(classID); StringBuilder str2 = new StringBuilder(); str2.Append("{\"msgtype\":1,"); //表示该用户只可以查看班级的信息 str2.Append("\"class_name\":\"" + classModel2.class_name + "\","); str2.Append("\"college\":\"" + collegeBll.GetModel(classModel2.college_id).college_name + "\","); str2.Append("\"head_teacher\":\"" + userBll.GetUserNumByUserID(Convert.ToInt32(classModel2.head_teacher)) + "-" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(classModel2.head_teacher)) + "\","); str2.Append("\"class_leader\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(classModel2.class_leader)) + "\","); str2.Append("\"squad_leader\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(classModel2.squad_leader)) + "\","); str2.Append("\"class_group_secretary\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(classModel2.class_group_secretary)) + "\","); str2.Append("\"study_secretary\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(classModel2.study_secretary)) + "\","); str2.Append("\"life_secretary\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(classModel2.life_secretary)) + "\""); str2.Append("}"); context.Response.Write(str2.ToString()); context.Response.End(); } #endregion #region 导出改班级的学生,(导出Excel表) protected void CreateExcelByClassID(HttpContext context) { int classID = Convert.ToInt32(HttpContext.Current.Request["classID"]); //获取班级ID DataSet ds = userinfoBll.GetAllStudentByClassID(classID); string typeid = "1"; string FileName = classBll.GetModel(classID).class_name + "名单.xls"; HttpResponse resp; resp = context.Response; //resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); //使用GB2312对文件名进行编码 resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + "\""); resp.ContentType = "application/ms-excel;"; string colHeaders = "", ls_item = ""; int i = 0; //定义表对象与行对像,同时用DataSet对其值进行初始化 DataTable dt = ds.Tables[0]; DataRow[] myRow = dt.Select(""); // typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件 if (typeid == "1") { //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 for (i = 0; i < dt.Columns.Count - 1; i++) colHeaders += dt.Columns[i].Caption.ToString() + "\t"; colHeaders += dt.Columns[i].Caption.ToString() + "\n"; //向HTTP输出流中写入取得的数据信息 resp.Write(colHeaders); //逐行处理数据 foreach (DataRow row in myRow) { //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n for (i = 0; i < row.ItemArray.Length - 1; i++) ls_item += row[i].ToString() + "\t"; ls_item += row[i].ToString() + "\n"; //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 resp.Write(ls_item); ls_item = ""; } } else { if (typeid == "2") { //从DataSet中直接导出XML数据并且写到HTTP输出流中 resp.Write(ds.GetXml()); } } //写缓冲区中的数据到HTTP头文件中 resp.End(); } #endregion #region 辅导员修改班级 protected void SaveClassInfo(HttpContext context) { context.Response.ContentType = "text/plain"; int classID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取班级ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (!classBll.Exists(classID)) { context.Response.Write("{\"msg\":\"你没有权限修改该班级\"}"); context.Response.End(); return; } int sel_leader = Convert.ToInt32(HttpContext.Current.Request["sel_leader"]); //获取班长ID int sel_squadLeader = Convert.ToInt32(HttpContext.Current.Request["sel_squadLeader"]); //获取副班长ID int sel_groupSecretary = Convert.ToInt32(HttpContext.Current.Request["sel_groupSecretary"]); //获取团支书ID int sel_stduySecretary = Convert.ToInt32(HttpContext.Current.Request["sel_stduySecretary"]); //获取学习委员ID int sel_lifeSecretary = Convert.ToInt32(HttpContext.Current.Request["sel_lifeSecretary"]); //获取生活委员ID int ri = classBll.UpdateClassByTer(classID, sel_leader, sel_squadLeader, sel_groupSecretary, sel_stduySecretary, sel_lifeSecretary); if (ri==1) { context.Response.Write("{\"msg\":\"修改成功!\"}"); } else { context.Response.Write("{\"msg\":\"修改失败!\"}"); } } #endregion #region 获取学院列表 protected void GetCollegeList(HttpContext context) { context.Response.ContentType = "text/plain"; IEnumerable<Model.college> modelList = collegeBll.GetAllCollegeList(); StringBuilder str = new StringBuilder(); str.Append("{\"collegeList\":["); foreach (Model.college model in modelList) { str.Append("{\"id\":" + model.id + ","); str.Append("\"collegeName\":\"" + model.college_name + "\","); str.Append("\"collegeAdmin\":\""); string[] s = model.college_admin.Split(new char[] { ',' }); for (int i = 0; i < s.Length - 1; i++) { if (i == s.Length - 2) { str.Append(userinfoBll.GetUserRealNameForID(Convert.ToInt32(s[i]))); } else { str.Append(userinfoBll.GetUserRealNameForID(Convert.ToInt32(s[i])) + ", "); } } str.Append("\"},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据学院获取班级列表 protected void GetAllClassByCollegeID(HttpContext context) { context.Response.ContentType = "text/plain"; int collegeID = Convert.ToInt32(HttpContext.Current.Request["collegeID"]); //获取学院ID IEnumerable<Model.classes> classList = classBll.GetClassListByCollege(collegeID); string collegeName = collegeBll.GetModel(collegeID).college_name; if (((System.Collections.Generic.List<XGhms.Model.classes>)classList).Count == 0) { context.Response.Write("{\"classList\":[]}"); return; } StringBuilder str = new StringBuilder(); str.Append("{\"classList\":["); foreach (Model.classes model in classList) { str.Append("{\"id\":" + model.id + ","); str.Append("\"className\":\"" + model.class_name + "\","); str.Append("\"collegeName\":\"" + collegeName + "\","); str.Append("\"headerTer\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(model.head_teacher)) + "\","); str.Append("\"stuLeader\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(model.class_leader)) + "\"},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 获取学期的下拉列表(根据当前的) protected void GetAllTermForNow(HttpContext context) { context.Response.ContentType = "text/plain"; IEnumerable<Model.term> modelList = termBll.GetAllTrem(); StringBuilder str = new StringBuilder(); str.Append("{\"termList\":["); foreach (Model.term model in modelList) { str.Append("{\"id\":" + model.id + ","); str.Append("\"termName\":\"" + model.term_name + "\","); str.Append("\"termCheck\":"); if (model.term_name == Utils.GetNowTerm(DateTime.Today.Year, DateTime.Today.Month)) { str.Append("1"); } else { str.Append("0"); } str.Append("},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据学期和老师的ID获取老师的课程列表 protected void GetTerCourseByTrem(HttpContext context) { context.Response.ContentType = "text/plain"; int tremID = Convert.ToInt32(HttpContext.Current.Request["tremID"]); //获取学期ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID DataTable dtc = courseBll.GetCourseListByTerTrem(userID, tremID); if (dtc.Rows.Count == 0) { context.Response.Write("{\"courseList\":[]}"); context.Response.End(); return; } StringBuilder str = new StringBuilder(); str.Append("{\"courseList\":["); for (int i = 0; i < dtc.Rows.Count; i++) { Model.course model = courseBll.GetModel(Convert.ToInt32(dtc.Rows[i]["id"])); str.Append("{\"id\":" + model.id + ","); str.Append("\"course_number\":\"" + model.course_number + "\","); str.Append("\"course_name\":\"" + model.course_name + "\","); str.Append("\"term\":\"" + termBll.GetModel(model.term_id).term_name + "\","); str.Append("\"teacher\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(model.teacher)) + "\","); str.Append("\"college\":\"" + collegeBll.GetModel(model.college_id).college_name + "\""); str.Append("},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据课程ID和老师的ID获取课程的信息 protected void GetCourseInfoByID(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取课程ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (!courseBll.Exists(courseID,userID)) { context.Response.Write("{\"msgtype\":0}"); context.Response.End(); return; } else { Model.course model = courseBll.GetModel(courseID); StringBuilder str = new StringBuilder(); str.Append("{\"msgtype\":1,"); str.Append("\"course_name\":\"" + model.course_name + "\","); str.Append("\"course_number\":\"" + model.course_number + "\","); str.Append("\"term\":\"" + termBll.GetModel(model.term_id).term_name + "\","); str.Append("\"college\":\"" + collegeBll.GetModel(model.college_id).college_name + "\","); str.Append("\"teacher\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(model.teacher)) + "\","); str.Append("\"other_teacher\":\""+userBll.GetUserNumByUserID(Convert.ToInt32(model.other_teacher))+"-"+ userinfoBll.GetUserRealNameForID(Convert.ToInt32(model.other_teacher)) + "\","); str.Append("\"student\":\"" + model.student_leader + "\","); str.Append("\"course_info\":\"" + HttpUtility.UrlEncodeUnicode(model.course_info).Replace("+", "%20") + "\""); str.Append("}"); context.Response.Write(str.ToString()); } } #endregion #region 检查用户,根据用户的编号检查 protected void CheckUserIDExist(HttpContext context) { context.Response.ContentType = "text/plain"; string userID = HttpContext.Current.Request["userID"]; //获取用户ID if (userID.Contains("-")) { userID = (userID.Split('-'))[0].ToString(); } if (userBll.Exists(userID)) { string userName = userinfoBll.GetUserRealNameForID(userBll.GetUserIDByUserNum(userID)); if (userName == "" || userName == null) { context.Response.Write("{\"msg\":0}"); //用户真实姓名不存在 } else { context.Response.Write("{\"msg\":1,\"userName\":\"" + userName + "\"}"); //显示 } } else { context.Response.Write("{\"msg\":2}"); //用户不存在 } } #endregion #region 根据课程ID获取学生列表 protected void GetStuListByCourseID(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID; if (HttpContext.Current.Request["id"]==null||HttpContext.Current.Request["id"]=="") { int hwID = Convert.ToInt32(HttpContext.Current.Request["hwid"]); //获取课程ID courseID = courhwBll.GetModel(hwID).course_id; } else { courseID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取课程ID } DataTable dt = courstuBll.SelectCourseStudentList(courseID); StringBuilder str = new StringBuilder(); str.Append("{\"stulist\":["); for (int i = 0; i < dt.Rows.Count; i++) { str.Append("{\"id\":"+dt.Rows[i]["student_id"]); str.Append(",\"value\":\"" + dt.Rows[i]["real_name"] + "\"},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 随机数的产生,用于随机产生几个名额的学生 protected void GetStuListRandomByCourseID(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID; if (HttpContext.Current.Request["id"] == null || HttpContext.Current.Request["id"] == "") { int hwID = Convert.ToInt32(HttpContext.Current.Request["hwid"]); //获取课程ID courseID = courhwBll.GetModel(hwID).course_id; } else { courseID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取课程ID } int num = Convert.ToInt32(HttpContext.Current.Request["value"]); //获取随机的数目 DataTable dt = courstuBll.SelectCourseStudentList(courseID); if (dt.Rows.Count<=num) { StringBuilder str = new StringBuilder(); str.Append("{\"stulist\":["); for (int i = 0; i < dt.Rows.Count; i++) { str.Append("{\"id\":" + dt.Rows[i]["student_id"]); str.Append(",\"value\":\"" + dt.Rows[i]["real_name"] + "\"},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); context.Response.End(); return; } else { //产生num个随机的数,从dt.Rows.Count里面 Random ab = new Random();//定义一个随机数对象 int[] x1 = new int[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { x1[i] = i; } ArrayList al = new ArrayList(x1); int[] x2 = new int[num]; int y; for (int i = 0; i < num; i++) { y = ab.Next(0, al.Count); x2[i] = Convert.ToInt32(al[y]); al.Remove(al[y]); } StringBuilder str = new StringBuilder(); str.Append("{\"stulist\":["); for (int i = 0; i < num; i++) { str.Append("{\"id\":" + dt.Rows[x2[i]]["student_id"]); str.Append(",\"value\":\"" + dt.Rows[x2[i]]["real_name"] + "\"},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); context.Response.End(); } } #endregion #region 保存课程信息 protected void SaveCourseInfo(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取课程ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (!courseBll.Exists(courseID, userID)) { context.Response.Write("{\"msg\":\"没有权限\"}"); context.Response.End(); return; } string oteacherID = HttpContext.Current.Request["otherTeacher"]; //获取助教ID if (oteacherID.Contains("-")) { oteacherID = (oteacherID.Split('-'))[0].ToString(); } int studentID = Convert.ToInt32(HttpContext.Current.Request["student"]); //获取学生ID string courseInfo = HttpContext.Current.Request["courseinfo"]; //获取课程信息 //执行更新语句 int ri = courseBll.Update(courseID,userBll.GetUserIDByUserNum(oteacherID).ToString(),Utils.XSSstring(studentID.ToString()), courseInfo); if (ri==1) { context.Response.Write("{\"msg\":\"更新成功\"}"); } else { context.Response.Write("{\"msg\":\"更新失败\"}"); } } #endregion #region 根据学期ID和老师的ID获取老师的本学期课程列表(用于下拉列表) protected void GetCourseListByTerandTerm(HttpContext context) { context.Response.ContentType = "text/plain"; int tremID = Convert.ToInt32(HttpContext.Current.Request["tremID"]); //获取学期ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID DataTable dtc = courseBll.GetCourseListByTerTrem(userID, tremID); if (dtc.Rows.Count == 0) { context.Response.Write("{\"courseList\":[]}"); context.Response.End(); return; } StringBuilder str = new StringBuilder(); str.Append("{\"courseList\":["); for (int i = 0; i < dtc.Rows.Count; i++) { Model.course model = courseBll.GetModel(Convert.ToInt32(dtc.Rows[i]["id"])); str.Append("{\"id\":" + model.id + ","); str.Append("\"course_name\":\"" + model.course_name + "\""); str.Append("},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据课程ID获取作业总数,并且分页显示 protected void GetHomeWorkListBytermAndCor(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID = Convert.ToInt32(HttpContext.Current.Request["courseID"]); //获取课程ID int totalNum = courhwBll.GetPageNumOfCourseID(courseID); int pagenum = 1; if (totalNum <= 10) //总数小于10条的情况 { pagenum = 1; } else //总数大于10条的情况 { if ((totalNum % 10) == 0) //能被10整除的情况 { pagenum = (totalNum / 10); } else //不能被10整除的情况 { pagenum = (totalNum / 10) + 1; } } context.Response.Write("{\"pagenum\":" + pagenum + "}"); context.Response.End(); } #endregion #region 根据课程ID获取作业列表,用于分页显示 protected void GetHomeWorkTotalNumBytermAndCor(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID = Convert.ToInt32(HttpContext.Current.Request["courseID"]); //获取课程ID int pageNow = Convert.ToInt32(HttpContext.Current.Request["nowPageNum"]); //获取页码 DataTable dt = courhwBll.GetPageOfCourseID(courseID, (pageNow - 1) * 10 + 1, pageNow * 10); if (dt.Rows.Count==0) { context.Response.Write("{\"hwList\":[]}"); context.Response.End(); return; } StringBuilder str = new StringBuilder(); str.Append("{\"hwList\":["); for (int i = 0; i < dt.Rows.Count; i++) { Model.course_homework courhwModel = courhwBll.GetModel(Convert.ToInt32(dt.Rows[i]["id"])); str.Append("{\"id\":" + courhwModel.id + ","); str.Append("\"homework_name\":\"" + courhwModel.homework_name + "\","); str.Append("\"course_name\":\"" + courseBll.GetModel(courseID).course_name + "\","); str.Append("\"homework_beginTime\":\"" + courhwModel.homework_beginTime.ToString("yyyy-MM-dd hh:mm") + "\","); str.Append("\"homework_endTime\":\"" + courhwModel.homework_endTime.ToString("yyyy-MM-dd hh:mm") + "\""); str.Append("},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据作业ID删除作业 protected void deleteHomeWork(HttpContext context) { context.Response.ContentType = "text/plain"; int hwID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取作业ID DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID Model.course_homework courhwModel = courhwBll.GetModel(hwID); if (courseBll.GetModel(courhwModel.course_id).teacher == userID.ToString()) { if (courhwBll.Delete(hwID)) { context.Response.Write("{\"msg\":\"删除成功\"}"); context.Response.End(); } else { context.Response.Write("{\"msg\":\"删除失败\"}"); context.Response.End(); } } else { context.Response.Write("{\"msg\":\"没有权限\"}"); context.Response.End(); } } #endregion #region 根据课程ID获取课程信息 protected void GetCourseInfoBycid(HttpContext context) { context.Response.ContentType = "text/plain"; int cid = Convert.ToInt32(HttpContext.Current.Request["cid"]); //获取课程ID Model.course courseModel = courseBll.GetModel(cid); //首先获取学期是否是本学期 if (termBll.GetModel(courseModel.term_id).term_name==Utils.GetNowTerm(DateTime.Today.Year,DateTime.Today.Month)) { DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (courseBll.Exists(cid, userID)) { StringBuilder str = new StringBuilder(); Model.course model = courseBll.GetModel(cid); str.Append("{\"msgtype\":1,\"id\":" + model.id + ","); str.Append("\"course_number\":\"" + model.course_number + "\","); str.Append("\"course_name\":\"" + model.course_name + "\","); str.Append("\"term\":\"" + termBll.GetModel(model.term_id).term_name + "\","); str.Append("\"teacher\":\"" + userinfoBll.GetUserRealNameForID(Convert.ToInt32(model.teacher)) + "\","); str.Append("\"college\":\"" + collegeBll.GetModel(model.college_id).college_name + "\""); str.Append("}"); context.Response.Write(str.ToString()); context.Response.End(); } else { context.Response.Write("{\"msgtype\":0,\"msg\":\"你没有权限添加该课程的作业\"}"); context.Response.End(); } } else { context.Response.Write("{\"msgtype\":0,\"msg\":\"该课程已过期,请重新选择\"}"); context.Response.End(); } } #endregion #region 根据作业ID获取作业信息 protected void GetHWInfoByid(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取作业ID Model.course_homework courhwModel = courhwBll.GetModel(id); int courseID = courhwModel.course_id; Model.course courseModel = courseBll.GetModel(courseID); DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (courseBll.Exists(courseID, userID)) { StringBuilder str = new StringBuilder(); str.Append("{\"msgtype\":1,\"id\":" + courhwModel.id + ","); str.Append("\"course_name\":\"" + courseModel.course_name + "\","); str.Append("\"term\":\"" + termBll.GetModel(courseModel.term_id).term_name + "\","); str.Append("\"homework_name\":\"" + HttpUtility.UrlEncodeUnicode(courhwModel.homework_name).Replace("+", "%20") + "\","); str.Append("\"homework_info\":\"" + HttpUtility.UrlEncodeUnicode(courhwModel.homework_info).Replace("+", "%20") + "\","); str.Append("\"homework_beginTime\":\"" + courhwModel.homework_beginTime.ToString("yyyy/MM/dd HH:mm") + "\","); str.Append("\"homework_endTime\":\"" + courhwModel.homework_endTime.ToString("yyyy/MM/dd HH:mm") + "\""); str.Append("}"); context.Response.Write(str.ToString()); context.Response.End(); } else { context.Response.Write("{\"msgtype\":0,\"msg\":\"你没有权限查看该课程的作业\"}"); context.Response.End(); } } #endregion #region 添加发布新的作业 protected void addnewHW(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取课程ID Model.course courseModel = courseBll.GetModel(id); //首先获取学期是否是本学期 if (termBll.GetModel(courseModel.term_id).term_name == Utils.GetNowTerm(DateTime.Today.Year, DateTime.Today.Month)) { DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (courseBll.Exists(id, userID)) { string hwName = HttpContext.Current.Request["hwName"]; //获取作业名 string hwInfo = HttpContext.Current.Request["hwCon"]; //获取作业信息 string userList = HttpContext.Current.Request["userList"]; //获取学生列表 string beginTime=HttpContext.Current.Request["beginTime"]; //获取作业开始时间 string endTime=HttpContext.Current.Request["endTime"]; //获取作业结束时间 string[] s = userList.Split(new char[] { ',' }); int succes = 0; int error = 0; int newhwID = courhwBll.InsertNewHWGethwID(id, hwName, hwInfo, beginTime, endTime); for (int i = 0; i < s.Length - 1; i++) { if (hwstuBll.Insertstuhw(newhwID,Convert.ToInt32(s[i]))== 1) { succes = succes + 1; } else { error = error + 1; } } context.Response.Write("{\"msg\":\"发布作业成功" + succes + "个,失败" + error + "个\"}"); context.Response.End(); } else { context.Response.Write("{\"msg\":\"你没有权限添加该课程的作业\"}"); context.Response.End(); } } else { context.Response.Write("{\"msg\":\"该课程已过期,请重新选择\"}"); context.Response.End(); } } #endregion #region 修改作业 protected void updoldHW(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取作业ID int courseID = courhwBll.GetModel(id).course_id; Model.course courseModel = courseBll.GetModel(courseID); //首先获取学期是否是本学期 if (termBll.GetModel(courseModel.term_id).term_name == Utils.GetNowTerm(DateTime.Today.Year, DateTime.Today.Month)) { DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (courseBll.Exists(courseID, userID)) { string hwName = HttpContext.Current.Request["hwName"]; //获取作业名 string hwInfo = HttpContext.Current.Request["hwCon"]; //获取作业信息 string userList = HttpContext.Current.Request["userList"]; //获取学生列表 string beginTime = HttpContext.Current.Request["beginTime"]; //获取作业开始时间 string endTime = HttpContext.Current.Request["endTime"]; //获取作业结束时间 string[] s = userList.Split(new char[] { ',' }); int succes = 0; int error = 0; int ri = courhwBll.UpdateHW(id, hwName, hwInfo, beginTime, endTime); if (ri != 1) { context.Response.Write("{\"msg\":\"修改失败\"}"); context.Response.End(); return; } for (int i = 0; i < s.Length - 1; i++) { if (!hwstuBll.Exists("homework_id=" + id + " and student_id="+Convert.ToInt32(s[i]))) { if (hwstuBll.Insertstuhw(id, Convert.ToInt32(s[i])) == 1) { succes = succes + 1; } else { error = error + 1; } } } context.Response.Write("{\"msg\":\"修改作业成功,添加成功" + succes + "个,失败" + error + "个\"}"); context.Response.End(); } else { context.Response.Write("{\"msg\":\"你没有权限修改该课程的作业\"}"); context.Response.End(); } } else { context.Response.Write("{\"msg\":\"该作业已过期,请重新选择\"}"); context.Response.End(); } } #endregion #region 获取分页数目你,学生的作业分页查询 protected void GetHomeWorkTotalNumByThreeCS(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID = Convert.ToInt32(HttpContext.Current.Request["courseID"]); //获取课程ID int hwStatus = Convert.ToInt32(HttpContext.Current.Request["hwStatus"]); //获取作业状态 int totalNum = hwstuBll.GetHomeWorkTotalNumByThreeCS(courseID, hwStatus); int pagenum = 1; if (totalNum <= 10) //总数小于10条的情况 { pagenum = 1; } else //总数大于10条的情况 { if ((totalNum % 10) == 0) //能被10整除的情况 { pagenum = (totalNum / 10); } else //不能被10整除的情况 { pagenum = (totalNum / 10) + 1; } } context.Response.Write("{\"pagenum\":" + pagenum + "}"); context.Response.End(); } #endregion #region 学生的作业分页显示的方法 protected void GetHomeWorkListByByThreeCS(HttpContext context) { context.Response.ContentType = "text/plain"; int courseID = Convert.ToInt32(HttpContext.Current.Request["courseID"]); //获取课程ID int hwStatus = Convert.ToInt32(HttpContext.Current.Request["hwStatus"]); //获取作业状态 int pageNow = Convert.ToInt32(HttpContext.Current.Request["nowPageNum"]); //获取页码 DataTable dt = hwstuBll.GetHomeWorkListByByThreeCSOfPage(courseID, hwStatus, (pageNow - 1) * 10 + 1, pageNow * 10); if (dt.Rows.Count == 0) { context.Response.Write("{\"hwList\":[]}"); context.Response.End(); return; } StringBuilder str = new StringBuilder(); str.Append("{\"hwList\":["); for (int i = 0; i < dt.Rows.Count; i++) { Model.homework_student hwstuModel=hwstuBll.GetModel(Convert.ToInt32(dt.Rows[i]["id"])); Model.course_homework courhwModel = courhwBll.GetModel(hwstuModel.homework_id); Model.course courseModel = courseBll.GetModel(courhwModel.course_id); str.Append("{\"id\":" + courhwModel.id + ","); str.Append("\"stuhwID\":" + hwstuModel.id + ","); str.Append("\"homework_name\":\"" + courhwModel.homework_name + "\","); str.Append("\"course_name\":\"" + courseModel.course_name + "\","); str.Append("\"student_name\":\"" + userinfoBll.GetUserRealNameForID(hwstuModel.student_id) + "\","); str.Append("\"homework_status\":" + hwstuModel.homework_status); str.Append("},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据作业ID删除该学生的作业 protected void deleteStuHomework(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取学生作业ID /*权限检查 Begin*/ DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (courseBll.GetModel(courhwBll.GetModel(hwstuBll.GetModel(id).homework_id).course_id).teacher != userID.ToString()) { context.Response.Write("{\"msg\":\"你没有权限删除该作业\"}"); context.Response.End(); return; } else { if (hwstuBll.Delete(id)) { context.Response.Write("{\"msg\":\"删除成功\"}"); context.Response.End(); return; } else { context.Response.Write("{\"msg\":\"删除失败\"}"); context.Response.End(); return; } } /*权限检查 End*/ } #endregion #region 根据学生作业的ID获取详细信息 protected void GetStuHWInfoByID(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取学生作业ID /*权限检查 Begin*/ DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID Model.homework_student hwstuModel = hwstuBll.GetModel(id); Model.course_homework courhwModel = courhwBll.GetModel(hwstuModel.homework_id); Model.course courseModel = courseBll.GetModel(courhwModel.course_id); if (courseModel.teacher != userID.ToString()) //检查权限 { context.Response.Write("{\"msgtype\":0,\"msg\":\"你没有权限查看该作业\"}"); context.Response.End(); return; }/*权限检查 End*/ else { if (hwstuModel.homework_status==1) { int ri = hwstuBll.terLookingStuWork(id); } StringBuilder str = new StringBuilder(); str.Append("{\"msgtype\":1,\"id\":" + hwstuModel.id + ","); //作业ID str.Append("\"course_name\":\"" + courseModel.course_name + "\","); //课程名 str.Append("\"term\":\"" + termBll.GetModel(courseModel.term_id).term_name + "\","); //学期 str.Append("\"homework_name\":\"" + courhwModel.homework_name + "\","); //作业名 str.Append("\"student_name\":\"" + userinfoBll.GetUserRealNameForID(hwstuModel.student_id) + "\","); //学生姓名 str.Append("\"student_num\":\"" + userBll.GetUserNumByUserID(hwstuModel.student_id) + "\","); //学生学号 str.Append("\"submit_time\":\"" + hwstuModel.submit_time.ToString("yyyy-MM-dd HH:mm") + "\","); //作业提交时间 str.Append("\"homework_con\":\"" + HttpUtility.UrlEncodeUnicode(hwstuModel.submit_content).Replace("+", "%20") + "\","); //提交的作业内容 if (hwstuModel.submit_file==null) { str.Append("\"submit_file\":\"\","); //作业的路径 } else { str.Append("\"submit_file\":\"" + HttpUtility.UrlEncodeUnicode(hwstuModel.submit_file).Replace("+", "%20") + "\","); //作业的路径 } if (hwstuModel.homework_comment == null) { str.Append("\"homework_comment\":\"\","); //作业的回复 } else { str.Append("\"homework_comment\":\"" + HttpUtility.UrlEncodeUnicode(hwstuModel.homework_comment).Replace("+", "%20") + "\","); //作业的回复 } str.Append("\"homework_score\":" + hwstuModel.homework_score); //作业的成绩 str.Append("}"); context.Response.Write(str.ToString()); context.Response.End(); } } #endregion #region 根据学生的ID,老师修改批阅学生的作业 protected void CheckStudentWork(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取学生作业ID string con = HttpContext.Current.Request["con"]; //获取老师的评价 int score= Convert.ToInt32(HttpContext.Current.Request["score"]); //获取学生作业的成绩 /*权限检查 Begin*/ DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID Model.homework_student hwstuModel = hwstuBll.GetModel(id); Model.course_homework courhwModel = courhwBll.GetModel(hwstuModel.homework_id); Model.course courseModel = courseBll.GetModel(courhwModel.course_id); if (courseModel.teacher != userID.ToString()) //检查权限 { context.Response.Write("{\"msg\":\"你没有权限修改该作业\"}"); context.Response.End(); return; }/*权限检查 End*/ else { if (hwstuModel.homework_status==0||hwstuModel.homework_status==3) { context.Response.Write("{\"msg\":\"等学生做完了作业再批改吧\"}"); context.Response.End(); return; } int ri = hwstuBll.terCheckStuHomeWork(id, con, score); if (ri==1) { context.Response.Write("{\"msg\":\"提交成功\"}"); context.Response.End(); return; } else { context.Response.Write("{\"msg\":\"提交失败\"}"); context.Response.End(); return; } } } #endregion #region 重做作业,让学生重做作业 protected void ReformWork(HttpContext context) { context.Response.ContentType = "text/plain"; int id = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取学生作业ID /*权限检查 Begin*/ DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID if (courseBll.GetModel(courhwBll.GetModel(hwstuBll.GetModel(id).homework_id).course_id).teacher != userID.ToString()) { context.Response.Write("{\"msg\":\"你没有权限修改该作业\"}"); context.Response.End(); return; } else { int ri = hwstuBll.ReformWork(id); if (ri==1) { context.Response.Write("{\"msg\":\"提交成功\"}"); context.Response.End(); return; } else { context.Response.Write("{\"msg\":\"提交失败\"}"); context.Response.End(); return; } } /*权限检查 End*/ } #endregion #region 获取老师未完成批改的作业数目 protected void GetNoCheckWorkNum(HttpContext context) { context.Response.ContentType = "text/plain"; DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID int ri = hwstuBll.GetNoCheckWorkNum(userID); context.Response.Write("{\"num\":"+ri+"}"); context.Response.End(); } #endregion #region 获取老师已完成批改的作业数目 protected void GetCheckWorkNum(HttpContext context) { context.Response.ContentType = "text/plain"; DataTable dt = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dt.Rows[0]["id"]); //获取老师ID int ri = hwstuBll.GetCheckWorkNum(userID); context.Response.Write("{\"num\":" + ri + "}"); context.Response.End(); } #endregion #region 获取最近三条数据,查看学生的未批改的作业 protected void GetThreeHWlistForDefault(HttpContext context) { context.Response.ContentType = "text/plain"; DataTable dtuser = (DataTable)context.Session["UserInfo"]; //获取session值 int userID = Convert.ToInt32(dtuser.Rows[0]["id"]); //获取老师ID DataTable dt = hwstuBll.GetThreeNoChecikForDefault(userID); if (dt.Rows.Count == 0) { context.Response.Write("{\"hwList\":[]}"); context.Response.End(); return; } StringBuilder str = new StringBuilder(); str.Append("{\"hwList\":["); for (int i = 0; i < dt.Rows.Count; i++) { Model.homework_student hwstuModel = hwstuBll.GetModel(Convert.ToInt32(dt.Rows[i]["id"])); Model.course_homework courhwModel = courhwBll.GetModel(hwstuModel.homework_id); Model.course courseModel = courseBll.GetModel(courhwModel.course_id); str.Append("{\"id\":" + courhwModel.id + ","); str.Append("\"stuhwID\":" + hwstuModel.id + ","); str.Append("\"homework_name\":\"" + courhwModel.homework_name + "\","); str.Append("\"course_name\":\"" + courseModel.course_name + "\","); str.Append("\"student_name\":\"" + userinfoBll.GetUserRealNameForID(hwstuModel.student_id) + "\","); str.Append("\"homework_status\":" + hwstuModel.homework_status); str.Append("},"); } str.Append("]}"); context.Response.Write(str.Remove((str.Length - 3), 1)); } #endregion #region 根据课程ID显示其最近的20条成绩曲线 protected void GetTwentyScoreByCourseID(HttpContext context) { context.Response.ContentType = "text/plain"; DataTable dt = (DataTable)context.Session["UserInfo"]; //获取Session的值 string type = HttpContext.Current.Request["type"]; //获取要显示的类型 int courseID = Convert.ToInt32(HttpContext.Current.Request["id"]); //获取课程的ID //检查该课程是否存在并该学生是否学习该课程 if (courseBll.Exists(courseID)) { StringBuilder str = new StringBuilder(); str.Append("["); //根据学生ID和课程ID获取前20条数据 DataTable dtOfcor = courhwBll.GetTwentyHWByCourID(courseID); if (type == "stu") //返回该学生的作业 { for (int i = 0; i < dtOfcor.Rows.Count; i++) { str.Append("[" + (i + 1) + ","); str.Append(hwstuBll.GetScoreByStuIDhwID(Convert.ToInt32(dt.Rows[0]["id"]), Convert.ToInt32(dtOfcor.Rows[i]["id"])) + ","); str.Append("\"" + dtOfcor.Rows[i]["homework_name"].ToString() + "\","); str.Append("\"" + Convert.ToDateTime(dtOfcor.Rows[i]["homework_beginTime"]).ToString("MM月dd号") + "\""); str.Append("],"); } } if (type == "all") //返回班级平均分 { for (int i = 0; i < dtOfcor.Rows.Count; i++) { str.Append("[" + (i + 1) + ","); str.Append(courhwBll.GetAVGByhwID(Convert.ToInt32(dtOfcor.Rows[i]["id"])) + ","); str.Append("\"" + dtOfcor.Rows[i]["homework_name"].ToString() + "\","); str.Append("\"" + Convert.ToDateTime(dtOfcor.Rows[i]["homework_beginTime"]).ToString("MM月dd号") + "\""); str.Append("],"); } } str.Append("]"); context.Response.Write(str.Remove((str.Length - 2), 1)); } else { context.Response.Write("false"); context.Response.End(); return; } } #endregion #region 如果为空,显示0 public string GetUserForDropdownList(string userID) { if (userID==null) { return "0"; } else { return userID; } } #endregion public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MegaCalculator { public class ValueNode : INode { private double _value; public ValueNode(double val) { _value = val; } public double GetValue() { return _value; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace kamidori_asm { class CustomBinaryReader { BinaryReader file; Char[] data; bool atEOF = false; public long Length = 0; public long Position = 0; public CustomBinaryReader(string input) { file = new BinaryReader(File.OpenRead(input)); Length = file.BaseStream.Length; data = new Char[Length]; data = file.ReadChars((int)Length); file.Close(); } public char ReadChar() { if (Position + 1 >= Length) atEOF = true; return data[Position++]; } public char PeekChar() { return data[Position]; } public bool IsEOF() { return atEOF; } public void Seek(long offset) { Position = offset; if (Position + 1 >= Length) atEOF = true; else if (atEOF == true) atEOF = false; } public void Close() { // any cleanup needed goes here } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System.Linq; using dojoTest.Models; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; namespace dojoTest.Controllers { public class HomeController : Controller { private DojoContext _context; public HomeController(DojoContext context) { _context = context; } [HttpGet] [Route("/dashboard")] public IActionResult Dashboard() { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return RedirectToAction("LoginPage", "User"); } else { List<User> Users = _context.Users.Include(p=>p.Posts).ThenInclude(l=>l.Likes).ToList(); List<Post> Posts = _context.Posts.Include(u=>u.Likes).OrderByDescending(x => x.Created_At).ToList(); User selectedUser = _context.Users.Where(u=>u.UserId == id).Include(p=>p.Posts).ThenInclude(l=>l.Likes).SingleOrDefault(); ViewBag.LoggedinUser = id; ViewBag.AllPosts = Posts; ViewBag.User = selectedUser; ViewBag.UserName = HttpContext.Session.GetString("name"); return View("Dashboard"); } } [HttpPost] [Route("/newpost")] public IActionResult CreatePost(UserPost check) { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return RedirectToAction("RegisterPage", "User"); } else { if(ModelState.IsValid) { Post newPost = new Post { Content = check.Content, Created_At = DateTime.Now, UserId = (int)id, }; _context.Posts.Add(newPost); _context.SaveChanges(); return RedirectToAction("Dashboard"); } else { TempData["PostError"] = "Post must be at least 5 characters"; return RedirectToAction("Dashboard"); } } } [HttpGet] [Route("/user/{userId}")] public IActionResult UserPage(int userId) { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return RedirectToAction("LoginPage", "User"); } else { User selectedUser = _context.Users.Where(u=>u.UserId == userId).Include(p=>p.Posts).ThenInclude(l=>l.Likes).SingleOrDefault(); List<Like> userLikes = _context.Likes.Where(u=>u.UserId == userId).ToList(); ViewBag.Likes = userLikes; ViewBag.User = selectedUser; return View("UserPage"); } } [HttpGet] [Route("/like/{postId}")] public IActionResult Like(int postId) { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return RedirectToAction("RegisterPage", "User"); } else { Like exists = _context.Likes.Where(p=>p.PostId == postId).Where(u=>u.UserId == id).FirstOrDefault(); if(exists == null) { Like newLike = new Like { PostId = postId, UserId = (int)id, }; _context.Likes.Add(newLike); _context.SaveChanges(); return RedirectToAction("Dashboard"); } else { _context.Likes.Remove(exists); _context.SaveChanges(); return RedirectToAction("Dashboard"); } } } [HttpGet] [Route("/post/{postId}")] public IActionResult PostPage(int postId) { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return RedirectToAction("LoginPage", "User"); } else { Post selectedPost = _context.Posts.Where(u=>u.PostId == postId).Include(l=>l.Likes).SingleOrDefault(); Like likes = _context.Likes.Where(p=>p.PostId == postId).FirstOrDefault(); User selectedUser = _context.Users.Where(u=>u.UserId == selectedPost.UserId).FirstOrDefault(); List<Like> likesList = _context.Likes.Where(p=>p.PostId == postId).Include(u=>u.LikedBy).ToList(); ViewBag.Post = selectedPost; ViewBag.LikesList = likesList; ViewBag.name = selectedUser.FirstName; return View("PostPage"); } } [HttpGet] [Route("/delete/{postId}")] public IActionResult PostDelete(int postId) { int? id = HttpContext.Session.GetInt32("userId"); if(id == null) { return RedirectToAction("LoginPage", "User"); } else { Post selectedPost = _context.Posts.Where(u=>u.PostId == postId).Include(l=>l.Likes).SingleOrDefault(); _context.Posts.Remove(selectedPost); _context.SaveChanges(); return RedirectToAction("Dashboard"); } } } }
using System; using System.Windows; using System.Windows.Media; using System.Windows.Controls; using Hearthstone_Deck_Tracker.Plugins; using Hearthstone_Deck_Tracker.API; namespace HDT_QoL { public class MainPlugin : IPlugin { private MainOverlay _overlay; private InputManager _inputManager; public string Name => "HDT_QoL"; public string Description => "Some quality of life improvements for HDT."; public string ButtonText => "Settings"; public string Author => "Lesterberne"; public Version Version => new Version(0, 0, 14); public MenuItem MenuItem => null; public void OnButtonPress() => SettingsWindow.Flyout.IsOpen = true; public void OnLoad() { _overlay = new MainOverlay(); MainHandler.Overlay = _overlay; _inputManager = new InputManager(_overlay); MainHandler.Input = _inputManager; Core.OverlayCanvas.Children.Add(_overlay); Canvas.SetZIndex(_overlay, -100); Canvas.SetTop(_overlay, Properties.Settings.Default.OverlayTop); Canvas.SetLeft(_overlay, Properties.Settings.Default.OverlayLeft); GameEvents.OnGameStart.Add(MainHandler.GameStart); GameEvents.OnGameEnd.Add(MainHandler.GameEnd); GameEvents.OnTurnStart.Add(MainHandler.TurnStart); Core.OverlayWindow.SizeChanged += new SizeChangedEventHandler(MainHandler.HandleSizeChangeEvent); Properties.Settings.Default.PropertyChanged += SettingsChanged; SettingsChanged(null, null); } private void SettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { _overlay.RenderTransform = new ScaleTransform(Properties.Settings.Default.OverlayScale / 100, Properties.Settings.Default.OverlayScale / 100); _overlay.Opacity = Properties.Settings.Default.OverlayOpacity / 100; } public void MountOverlay() { } public void UnmountOverlay() { } public void OnUnload() { Properties.Settings.Default.Save(); Core.OverlayCanvas.Children.Remove(_overlay); _inputManager.Dispose(); } public void OnUpdate() { } public void SetWindowLeft() { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using C1.Win.C1FlexGrid; using QTHT.BusinesLogic; using HoaDonDataAccess.DataAccess; using HoaDonDataAccess.BusinesLogic; using DanhMuc.DataAccess; using DanhMuc.BusinesLogic; using CGCN.DataAccess; using System.Globalization; using DanhMuc.Report; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; namespace DanhMuc.Interface { public partial class CreatHDBanForCustome : Form { private CellStyle cs1; private logBL _ctrlog = new logBL(); private string sidkh = ""; #region Method private void LoadCBNhanVien() { nhanvienBL ctrNhanVien = new nhanvienBL(); DataTable dt = new DataTable(); dt = ctrNhanVien.GetAll(); cbNhanVien.DataSource = dt; cbNhanVien.DisplayMember = "hoten"; cbNhanVien.ValueMember = "taikhoan"; } private void HienThiTTKhachHang() { tblkhachhang obj = new tblkhachhang(); tblkhachhangBL ctr = new tblkhachhangBL(); obj = ctr.GetByID(sidkh); if (obj == null) { MessageBox.Show("Lỗi: Không lấy được thông tin của khách hàng","Thông báo",MessageBoxButtons.OK,MessageBoxIcon.Error); return; } try { txtTenKH.Text = obj.tenkh.Trim(); } catch { txtTenKH.Text = "N/A"; } try { txtCapDaiLy.Text = obj.id_capdl.Trim(); } catch { txtCapDaiLy.Text = "N/A"; } try { txtDienThoai.Text = obj.dt.Trim(); } catch { txtDienThoai.Text = "N/A"; } try { txtDiaChi.Text = obj.diachi.Trim(); } catch { txtDiaChi.Text = "N/A"; } } private void HienThiTTHoaDon() { try { tblhoadonban obj = new tblhoadonban(); tblhoadonbanBL ctr = new tblhoadonbanBL(); obj = ctr.GetByID(txtID.Text.Trim()); txtChietKhau.Text = obj.chietkhau.ToString("N0", CultureInfo.InvariantCulture); txtTienThanhToan.Text = obj.tienthanhtoan.ToString("N0", CultureInfo.InvariantCulture); txtNgayXuat.Text = obj.ngaytao.ToString("dd/MM/yyyy HH:mm:ss"); txtNoToaTruoc.Text = ctr.GetTienConNo(obj.id_khachhang, obj.ngaytao).ToString("N0", CultureInfo.InvariantCulture); txtGhiChu.Text = obj.ghichu.Trim(); flxMatHang.Focus(); } catch { HienThiDSMatHang(); } } private void HienThiDSMatHang() { try { DataTable dt = new DataTable(); tblmathangbanBL ctr = new tblmathangbanBL(); dt = ctr.GetByHDID(txtID.Text.Trim()); dt.Columns.Add("tt", typeof(Int32)); flxMatHang.DataSource = dt; FormatGridMatHang(); } catch { } } private void FormatGridMatHang() { for (int i = 0; i < flxMatHang.Cols.Count; i++) { if (i == 0) { flxMatHang[0, i] = "STT"; flxMatHang.Cols[i].Visible = true; flxMatHang.Cols[i].Width = 60; } else if (flxMatHang.Cols[i].Caption.Equals("mathang")) { flxMatHang[0, i] = "Mặt hàng(*)"; flxMatHang.Cols[i].Visible = true; flxMatHang.Cols[i].ComboList = "..."; } else if (flxMatHang.Cols[i].Caption.Equals("soluong")) { flxMatHang[0, i] = "Số lượng (*)"; flxMatHang.Cols[i].Visible = true; flxMatHang.Cols["soluong"].Format = "N0"; } else if (flxMatHang.Cols[i].Caption.Equals("donvi")) { flxMatHang[0, i] = "Đơn vị"; flxMatHang.Cols[i].Visible = true; flxMatHang.Cols["donvi"].AllowEditing = false; } else if (flxMatHang.Cols[i].Caption.Equals("giaban")) { flxMatHang[0, i] = "Giá bán(*)"; flxMatHang.Cols[i].Visible = true; flxMatHang.Cols["giaban"].Format = "N0"; } else if (flxMatHang.Cols[i].Caption.Equals("thanhtien")) { flxMatHang[0, i] = "Thành tiền"; flxMatHang.Cols[i].Visible = true; flxMatHang.Cols["thanhtien"].AllowEditing = false; flxMatHang.Cols["thanhtien"].Format = "N0"; } else { flxMatHang.Cols[i].Visible = false; } flxMatHang.Cols[i].TextAlignFixed = TextAlignEnum.CenterCenter; } Font _font = new Font("Time new Roman", 14); flxMatHang.Font = _font; double tongtien = 0; for (int j = 1; j < flxMatHang.Rows.Count; j++) { flxMatHang[j, 0] = j; flxMatHang[j, "tt"] = 0; double thanhtienforrow = 0; try { thanhtienforrow = Convert.ToDouble(flxMatHang[j, "thanhtien"].ToString().Trim()); } catch { } tongtien = tongtien + thanhtienforrow; } txtTongTien.Text = tongtien.ToString("N0", CultureInfo.InvariantCulture); double tienthanhtoan = 0; try { tienthanhtoan = Convert.ToDouble(txtTienThanhToan.Text.Trim()); } catch { } double chietkhau = 0; try { chietkhau = Convert.ToDouble(txtChietKhau.Text.Trim()); } catch { } double tienconnotoatruoc = 0; try { tienconnotoatruoc = Convert.ToDouble(txtNoToaTruoc.Text.Trim()); } catch { } txtConNo.Text = ((tongtien - tienthanhtoan - chietkhau) + tienconnotoatruoc).ToString("N0", CultureInfo.InvariantCulture); flxMatHang.Cols[0].TextAlign = TextAlignEnum.CenterCenter; flxMatHang.AutoSizeCols(); flxMatHang.AutoSizeRows(); } private void TinhToan() { double tongtien = 0; try { tongtien = Convert.ToDouble(txtTongTien.Text.Trim()); } catch { } double chietkhau = 0; try { chietkhau = Convert.ToDouble(txtChietKhau.Text.Trim()); } catch { } double tienthanhtoan = 0; try { tienthanhtoan = Convert.ToDouble(txtTienThanhToan.Text.Trim()); } catch { } double tienconnotoatruoc = 0; try { tienconnotoatruoc = Convert.ToDouble(txtNoToaTruoc.Text.Trim()); } catch { } txtConNo.Text = ((tongtien - tienthanhtoan - chietkhau) + tienconnotoatruoc).ToString("N0", CultureInfo.InvariantCulture); } private void XuatHoaDon() { string sidhd = ""; try { sidhd = txtID.Text.Trim(); } catch { } if (sidhd.Trim().Equals("") == false && sidhd.Trim().Equals("-1") == false) { Application.DoEvents(); tsProgressBar1.Visible = true; tsProgressBar1.PerformStep(); DataTable dt = new DataTable(); dt = (DataTable)flxMatHang.DataSource; Application.DoEvents(); tsProgressBar1.PerformStep(); frmReportHDBan frm = new frmReportHDBan(); rptHoaDonBan _rptHoaDonBan = new rptHoaDonBan(); ReportDocument reportDocument = new ReportDocument(); ParameterFields pfields = new ParameterFields(); #region Khai báo parametter tiêu đề ngày tháng ParameterField pTenKH = new ParameterField(); ParameterDiscreteValue dispTenKH = new ParameterDiscreteValue(); ParameterField pDienThoai = new ParameterField(); ParameterDiscreteValue dispDienThoai = new ParameterDiscreteValue(); ParameterField pNgayXuat = new ParameterField(); ParameterDiscreteValue dispNgayXuat = new ParameterDiscreteValue(); ParameterField pNoCu = new ParameterField(); ParameterDiscreteValue dispNoCu = new ParameterDiscreteValue(); ParameterField pTienDaTT = new ParameterField(); ParameterDiscreteValue dispTienDaTT = new ParameterDiscreteValue(); ParameterField pGhiChu = new ParameterField(); ParameterDiscreteValue disGhiChu = new ParameterDiscreteValue(); ParameterField pChietKhau = new ParameterField(); ParameterDiscreteValue disChietKhau = new ParameterDiscreteValue(); string tenKH = ""; string DT = ""; string ngayXuat = ""; string noCu = ""; string tienTT = ""; string ghiChu = ""; string chietKhau = ""; tenKH = txtTenKH.Text.Trim(); DT = txtDienThoai.Text.Trim(); ngayXuat = txtNgayXuat.Text.Trim(); noCu = txtNoToaTruoc.Text.Trim(); tienTT = txtTienThanhToan.Text.Trim(); ghiChu = txtGhiChu.Text.Trim(); chietKhau = txtChietKhau.Text.Trim(); Application.DoEvents(); tsProgressBar1.PerformStep(); dispTenKH.Value = tenKH; pTenKH.Name = "pTenKH"; pTenKH.CurrentValues.Add(dispTenKH); pfields.Add(pTenKH); Application.DoEvents(); tsProgressBar1.PerformStep(); dispDienThoai.Value = DT; pDienThoai.Name = "pDienThoai"; pDienThoai.CurrentValues.Add(dispDienThoai); pfields.Add(pDienThoai); Application.DoEvents(); tsProgressBar1.PerformStep(); dispNgayXuat.Value = ngayXuat; pNgayXuat.Name = "pNgayXuat"; pNgayXuat.CurrentValues.Add(dispNgayXuat); pfields.Add(pNgayXuat); Application.DoEvents(); tsProgressBar1.PerformStep(); dispNoCu.Value = noCu; pNoCu.Name = "pNoCu"; pNoCu.CurrentValues.Add(dispNoCu); pfields.Add(pNoCu); Application.DoEvents(); tsProgressBar1.PerformStep(); dispTienDaTT.Value = tienTT; pTienDaTT.Name = "pTienDaTT"; pTienDaTT.CurrentValues.Add(dispTienDaTT); pfields.Add(pTienDaTT); Application.DoEvents(); tsProgressBar1.PerformStep(); disGhiChu.Value = ghiChu; pGhiChu.Name = "pGhiChu"; pGhiChu.CurrentValues.Add(disGhiChu); pfields.Add(pGhiChu); Application.DoEvents(); tsProgressBar1.PerformStep(); disChietKhau.Value = chietKhau; pChietKhau.Name = "pChietKhau"; pChietKhau.CurrentValues.Add(disChietKhau); pfields.Add(pChietKhau); #endregion Application.DoEvents(); tsProgressBar1.PerformStep(); frm.crystalReportViewer1.ParameterFieldInfo = pfields; Application.DoEvents(); tsProgressBar1.PerformStep(); frm.crystalReportViewer1.ReportSource = _rptHoaDonBan; Application.DoEvents(); tsProgressBar1.PerformStep(); _rptHoaDonBan.SetDataSource(dt); Application.DoEvents(); tsProgressBar1.Value = tsProgressBar1.Maximum; frm.ShowDialog(); Application.DoEvents(); tsProgressBar1.Value = 0; tsProgressBar1.Visible = false; } } #endregion #region Method Cập nhật private void Add() { txtNgayXuat.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); txtID.Text = "-1"; HienThiDSMatHang(); txtTongTien.Text = "0"; txtNoToaTruoc.Text = "0"; txtTienThanhToan.Text = "0"; txtConNo.Text = "0"; txtChietKhau.Text = "0"; flxMatHang.Focus(); } private void AddMatHang() { try { flxMatHang.Rows.Add(); flxMatHang[flxMatHang.Rows.Count - 1, "tt"] = 1; flxMatHang[flxMatHang.Rows.Count - 1, "id"] = ""; flxMatHang[flxMatHang.Rows.Count - 1, 0] = (flxMatHang.Rows.Count - 1).ToString(); flxMatHang.Select(flxMatHang.Rows.Count - 1, flxMatHang.Cols["mathang"].Index); } catch { } } private void Save() { string kq = ""; tbltienthanhtoanBL ctrtientt = new tbltienthanhtoanBL(); tblmathangBL ctrmathang = new tblmathangBL(); tblhoadonbanBL ctrhoadon = new tblhoadonbanBL(); tblhoadonban objhoadon = new tblhoadonban(); objhoadon = GetDataHoaDon(); tblmathangbanBL ctrmathangban = new tblmathangbanBL(); List<tblmathangban> lstmathang = new List<tblmathangban>(); lstmathang = GetListMatHangBan(); if (objhoadon != null && lstmathang != null) { if (txtID.Text.Trim().Equals("-1") == true) { kq = ctrhoadon.Insert(objhoadon); if (kq.Trim().Equals("") == true) { //txtID.Text = objhoadon.id.Trim(); tbltienthanhtoan objtientt = new tbltienthanhtoan(); objtientt.id = Guid.NewGuid().ToString().Trim(); objtientt.idhd = objhoadon.id; objtientt.ngaytt = objhoadon.ngaytao; objtientt.tientt = objhoadon.tienthanhtoan; ctrtientt.Insert(objtientt); } } else { kq = ctrhoadon.Update(objhoadon); tbltienthanhtoan objtientt = new tbltienthanhtoan(); objtientt = ctrtientt.GetByIDHDvsNgayTT(objhoadon.id, objhoadon.ngaytao); if (objtientt != null) { objtientt.tientt = objhoadon.tienthanhtoan; ctrtientt.Update(objtientt); } else { objtientt = new tbltienthanhtoan(); objtientt.id = Guid.NewGuid().ToString().Trim(); objtientt.idhd = objhoadon.id; objtientt.ngaytt = objhoadon.ngaytao; objtientt.tientt = objhoadon.tienthanhtoan; ctrtientt.Insert(objtientt); } //_ctrlog.Append(Data.use, "Sửa hóa đơn cho khách hàng: " + txtTenKH.Text.Trim() + " ; id: " + objhoadon.id); _ctrlog.Append(Data.use, "Sửa hóa đơn cho khách hàng: " + txtTenKH.Text.Trim() + " xuất ngày: " + txtNgayXuat.Text.Trim() + "; id: " + objhoadon.id + ";\nChi tiết: Tổng tiền hàng: " + txtTongTien.Text + " - Nợ cũ: " + txtNoToaTruoc.Text + " - Tiền thanh toán: " + txtTienThanhToan.Text + " - Tổng nợ mới: " + txtConNo.Text); } if (kq.Trim().Equals("") == true) { if (lstmathang != null) { if (objhoadon != null && lstmathang.Count > 0) { for (int i = 0; i < lstmathang.Count; i++) { tblmathangban temp = new tblmathangban(); temp = ctrmathangban.GetByID(lstmathang[i].id); if (temp == null) { lstmathang[i].id_hoadon = objhoadon.id; kq = ctrmathangban.Insert(lstmathang[i]); if (kq.Trim().Equals("") == false) { ctrhoadon.Delete(objhoadon.id); break; } else //Cập nhật lại số lượng còn trong kho { tblmathang objmathang = new tblmathang(); objmathang = ctrmathang.GetByID(lstmathang[i].id_mathang.Trim()); objmathang.soluong = objmathang.soluong - lstmathang[i].soluong; ctrmathang.Update(objmathang); } } else { lstmathang[i].id_hoadon = objhoadon.id; kq = ctrmathangban.Update(lstmathang[i]); if (kq.Trim().Equals("") == false) { break; } else //Cập nhật lại số lượng còn trong kho { tblmathang objmathang = new tblmathang(); objmathang = ctrmathang.GetByID(lstmathang[i].id_mathang.Trim()); objmathang.soluong = (objmathang.soluong + temp.soluong) - lstmathang[i].soluong; ctrmathang.Update(objmathang); } } } if (kq.Trim().Equals("") == false) { MessageBox.Show("Lỗi cập nhật hóa đơn.\nChi tiết lỗi: " + kq, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { if (txtID.Text.Trim().Equals("-1") == true) { txtID.Text = objhoadon.id.Trim(); _ctrlog.Append(Data.use, "Thêm mới hóa đơn cho khách hàng: " + txtTenKH.Text.Trim() + " xuất ngày: " + txtNgayXuat.Text.Trim() + "; id: " + objhoadon.id + ";\nChi tiết: Tổng tiền hàng: " + txtTongTien.Text + " - Nợ cũ: " + txtNoToaTruoc.Text + " - Tiền thanh toán: " + txtTienThanhToan.Text + " - Tổng nợ mới: " + txtConNo.Text); } } } } } else { MessageBox.Show("Lỗi cập nhật hóa đơn.\nChi tiết lỗi: " + kq, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if (kq.Trim().Equals("") == true && lstmathang != null) { MessageBox.Show("Cập nhật hóa đơn bán thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); HienThiTTHoaDon(); HienThiDSMatHang(); ultraToolbarsManager1.Tools["btn_Del"].SharedProps.Visible = true; ultraToolbarsManager1.Tools["btnExportHD"].SharedProps.Visible = true; } } private void DelMatHang() { tblmathangBL ctrmathang = new tblmathangBL(); tblmathangbanBL ctr = new tblmathangbanBL(); string kq = ""; string sid = ""; try { sid = flxMatHang[flxMatHang.RowSel, "id"].ToString().Trim(); } catch { } if (sid.Trim().Equals("") == true) { flxMatHang.Rows.Remove(flxMatHang.RowSel); for (int j = 1; j < flxMatHang.Rows.Count; j++) { flxMatHang[j, 0] = j; } } else { if (MessageBox.Show("Xác nhận xóa dữ liệu?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { //Cập nhật lại số lượng tblmathang objmathang = new tblmathang(); string sidmathang = flxMatHang[flxMatHang.RowSel, "id_mathang"].ToString().Trim(); objmathang = ctrmathang.GetByID(sidmathang); tblmathangban objmathangban = new tblmathangban(); objmathangban = ctr.GetByID(sid); objmathang.soluong = objmathangban.soluong + objmathang.soluong; kq = ctr.Delete(sid); if (kq.Trim().Equals("") == true) { ctrmathang.Update(objmathang); flxMatHang.Rows.Remove(flxMatHang.RowSel); double tongtien = 0; for (int j = 1; j < flxMatHang.Rows.Count; j++) { flxMatHang[j, 0] = j; try { tongtien = tongtien + Convert.ToDouble(flxMatHang[j, "thanhtien"].ToString().Trim()); } catch { } } txtTongTien.Text = tongtien.ToString("N0", CultureInfo.InvariantCulture); TinhToan(); _ctrlog.Append(Data.use, "Xóa mặt hàng:" + objmathang.ten + " của hóa đơn xuất cho khách hàng: " + txtTenKH.Text.Trim() + " xuất ngày: " + txtNgayXuat.Text.Trim() + "; id: " + txtID.Text.Trim() + ";\nChi tiết: Tổng tiền hàng: " + txtTongTien.Text + " - Nợ cũ: " + txtNoToaTruoc.Text + " - Tiền thanh toán: " + txtTienThanhToan.Text + " - Tổng nợ mới: " + txtConNo.Text); } } } } private void UpdateSoLuongMatHang() { tblmathangbanBL ctrmathangban = new tblmathangbanBL(); tblmathangBL ctrmathang = new tblmathangBL(); DataTable dt = new DataTable(); dt = ctrmathangban.GetByHDID(txtID.Text.Trim()); for (int i = 0; i < dt.Rows.Count; i++) { string sidmathang = ""; try { sidmathang = dt.Rows[i]["id_mathang"].ToString().Trim(); } catch { } string sidmathangban = ""; try { sidmathangban = dt.Rows[i]["id"].ToString().Trim(); } catch { } if (sidmathang.Trim().Equals("") == false && sidmathangban.Trim().Equals("") == false) { tblmathangban objmathangban = new tblmathangban(); objmathangban = ctrmathangban.GetByID(sidmathangban); tblmathang objmathang = new tblmathang(); objmathang = ctrmathang.GetByID(sidmathang); objmathang.soluong = objmathangban.soluong + objmathang.soluong; try { ctrmathang.Update(objmathang); } catch { } } } } private void Del() { tblhoadonbanBL ctr = new tblhoadonbanBL(); string kq = ""; if (MessageBox.Show("Xác nhận xóa dữ liệu?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { UpdateSoLuongMatHang(); kq = ctr.Delete(txtID.Text.Trim()); if (kq.Trim().Equals("") == true) { string stientttemp = "N/A"; try { stientttemp = ctr.GetByID(txtID.Text.Trim()).tienthanhtoan.ToString(); } catch { } //_ctrlog.Append(Data.use, "Xóa hóa đơn của khách hàng: " + txtTenKH.Text.Trim() + " ; idhd: " + txtID.Text.Trim()); _ctrlog.Append(Data.use, "Xóa hóa đơn bán của khách hàng: " + txtTenKH.Text.Trim() + " xuất ngày: " + txtNgayXuat.Text.Trim() + "; id: " + txtID.Text.Trim() + ";\nChi tiết: Tổng tiền hàng: " + txtTongTien.Text + " - Nợ cũ: " + txtNoToaTruoc.Text + " - Tiền thanh toán: " + stientttemp + " - Tổng nợ mới: " + txtConNo.Text); Add(); HienThiDSMatHang(); } else { MessageBox.Show("Xóa hóa đơn không thành công.\nChi tiết lỗi: " + kq, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } #endregion #region GetData private bool CheckMatHang(string sidmathang, int irow) { for (int i = 1; i < flxMatHang.Rows.Count; i++) { string sidmathangtemp = ""; try { sidmathangtemp = flxMatHang[i, "id_mathang"].ToString().Trim(); } catch { } if (sidmathang.Trim().Equals("") == false && sidmathang.Trim().Equals(sidmathangtemp) == true && i != irow) { return true; } } return false; } private tblhoadonban GetDataHoaDon() { tblhoadonban obj = new tblhoadonban(); if (sidkh.Trim().Equals("") == true) { MessageBox.Show("Lỗi lấy thông tin khách hàng.\nVui lòng tắt chức năng và thao tác lại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtTenKH.Focus(); return null; } if (txtID.Text.Equals("-1") == true) { obj.id = Guid.NewGuid().ToString(); } else { obj.id = txtID.Text.Trim(); } obj.id_khachhang = sidkh; try { obj.chietkhau = Convert.ToDouble(txtChietKhau.Text.Trim()); } catch { } obj.ghichu = txtGhiChu.Text.Trim(); obj.ngaytao = DateTime.ParseExact( txtNgayXuat.Text.Trim(), "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); try { obj.tienthanhtoan = Convert.ToDouble(txtTienThanhToan.Text.Trim()); } catch { } try { obj.userid = cbNhanVien.SelectedValue.ToString().Trim(); } catch { obj.userid = Data.use.Trim(); } return obj; } private List<tblmathangban> GetListMatHangBan() { tblmathangBL ctrmathang = new tblmathangBL(); tblmathangbanBL ctrmathangban = new tblmathangbanBL(); try { List<tblmathangban> lst = new List<tblmathangban>(); for (int i = 1; i < flxMatHang.Rows.Count; i++) { tblmathangban obj = new tblmathangban(); if (flxMatHang[i, "tt"].ToString().Trim().Equals("1") == true) { obj.id = Guid.NewGuid().ToString(); } else { obj.id = flxMatHang[i, "id"].ToString().Trim(); } if (flxMatHang[i, "id_mathang"].ToString().Trim().Equals("") == false) { try { obj.soluong = Convert.ToInt32(flxMatHang[i, "soluong"].ToString().Trim()); } catch { obj.soluong = 0; } try { obj.giaban = Convert.ToDouble(flxMatHang[i, "giaban"].ToString().Trim()); } catch { obj.giaban = 0; } if (obj.soluong == 0) { MessageBox.Show("Số lượng phải lớn hơn 0 và là số", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); flxMatHang.Select(i, flxMatHang.Cols["soluong"].Index); flxMatHang.SetUserData(i, 0, "Số lượng phải lớn hơn 0 và là số"); flxMatHang.Rows[i].Style = cs1; return null; } } if (flxMatHang[i, "id_mathang"].ToString().Trim().Equals("") == false || obj.soluong > 0) { if (flxMatHang[i, "id_mathang"].ToString().Trim().Equals("") == true) { MessageBox.Show("Mặt hàng chưa được nhập", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); flxMatHang.Select(i, flxMatHang.Cols["mathang"].Index); flxMatHang.SetUserData(i, 0, "Mặt hàng chưa được nhập"); flxMatHang.Rows[i].Style = cs1; return null; } //if (flxMatHang[i, "giaban"].ToString().Trim().Equals("") == true || flxMatHang[i, "giaban"].ToString().Trim().Equals("0") == true) if (obj.giaban == 0) { MessageBox.Show("Giá bán chưa được nhập", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); flxMatHang.Select(i, flxMatHang.Cols["giaban"].Index); flxMatHang.SetUserData(i, 0, "Giá bán chưa được nhập"); flxMatHang.Rows[i].Style = cs1; return null; } obj.id_mathang = flxMatHang[i, "id_mathang"].ToString().Trim(); obj.giaban = Convert.ToDouble(flxMatHang[i, "giaban"].ToString().Trim()); tblmathang objmathang = new tblmathang(); objmathang = ctrmathang.GetByID(obj.id_mathang); if (flxMatHang[i, "tt"].ToString().Trim().Equals("1") == true) { if (obj.soluong > objmathang.soluong) { MessageBox.Show("Số lượng trong kho còn ít hơn số lượng xuất.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); flxMatHang.Select(i, flxMatHang.Cols["soluong"].Index); flxMatHang.SetUserData(i, 0, "Số lượng trong kho còn ít hơn số lượng xuất."); flxMatHang.Rows[i].Style = cs1; return null; } } if (flxMatHang[i, "tt"].ToString().Trim().Equals("2") == true) { tblmathangban tempmathangban = new tblmathangban(); tempmathangban = ctrmathangban.GetByID(obj.id); if (obj.soluong > objmathang.soluong + tempmathangban.soluong) { MessageBox.Show("Số lượng trong kho còn ít hơn số lượng xuất.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); flxMatHang.Select(i, flxMatHang.Cols["soluong"].Index); flxMatHang.SetUserData(i, 0, "Số lượng trong kho còn ít hơn số lượng xuất."); flxMatHang.Rows[i].Style = cs1; return null; } } obj.ngaytao = DateTime.Now; lst.Add(obj); } } return lst; } catch { return null; } } #endregion public CreatHDBanForCustome(string sidkh) { this.sidkh = sidkh; InitializeComponent(); } private void CreatHDBanForCustome_Load(object sender, EventArgs e) { cs1 = flxMatHang.Styles.Add("error"); cs1.BackColor = Color.Blue; HienThiTTKhachHang(); LoadCBNhanVien(); cbNhanVien.SelectedValue = Data.use; if (Data.use.Trim().Equals("admin") == true) { cbNhanVien.Enabled = true; txtNgayXuat.ReadOnly = false; } else { cbNhanVien.Enabled = false; txtNgayXuat.ReadOnly = true; } Add(); tblhoadonbanBL ctrhdb = new tblhoadonbanBL(); DateTime dtngaytao = new DateTime(); try { dtngaytao = DateTime.ParseExact( txtNgayXuat.Text.Trim(), "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture); } catch { } try { txtNoToaTruoc.Text = ctrhdb.GetTienConNo(sidkh, dtngaytao).ToString("N0", CultureInfo.InvariantCulture); } catch { txtNoToaTruoc.Text = "-/-"; } flxMatHang.Focus(); flxMatHang.KeyActionEnter = KeyActionEnum.MoveAcross; } #region Xử lý sự kiện lưới mặt hàng private void flxMatHang_KeyDown(object sender, KeyEventArgs e) { if ((e.Control && e.KeyCode == Keys.A) || e.KeyCode == Keys.Add) { AddMatHang(); } else if (e.KeyCode == Keys.Delete) { DelMatHang(); } } private void flxMatHang_AfterEdit(object sender, RowColEventArgs e) { try { int hang = flxMatHang.Row; if (Convert.ToInt32(flxMatHang[hang, "tt"]) == 0) { flxMatHang[flxMatHang.RowSel, flxMatHang.Cols.Count - 1] = 2; } if (flxMatHang.Cols[flxMatHang.ColSel].Name.ToUpper().Equals("GIABAN") == true && flxMatHang.RowSel == flxMatHang.Rows.Count - 1) { if (flxMatHang.RowSel == flxMatHang.Rows.Count - 1) { AddMatHang(); flxMatHang.StartEditing(flxMatHang.Rows.Count - 1, 3); } else { flxMatHang.StartEditing(flxMatHang.RowSel + 1, 3); } //AddMatHang(); flxMatHang.StartEditing(flxMatHang.Rows.Count - 1, 3); } flxMatHang[flxMatHang.RowSel, "thanhtien"] = (Convert.ToDouble(flxMatHang[flxMatHang.RowSel, "soluong"].ToString().Trim()) * Convert.ToDouble(flxMatHang[flxMatHang.RowSel, "giaban"].ToString().Trim())).ToString(); flxMatHang.AutoSizeCols(); flxMatHang.AutoSizeRows(); double tongtien = 0; for (int i = 1; i < flxMatHang.Rows.Count; i++) { double thanhtienofrow = 0; try { thanhtienofrow = Convert.ToDouble(flxMatHang[i, "thanhtien"].ToString()); } catch { } tongtien = tongtien + thanhtienofrow; } txtTongTien.Text = tongtien.ToString("N0", CultureInfo.InvariantCulture); TinhToan(); } catch { } } private void flxMatHang_CellButtonClick(object sender, RowColEventArgs e) { try { frmChonMatHang frm = new frmChonMatHang(); frm.type = 1; frm.ShowDialog(); string sidmathang = ""; try { sidmathang = frm.sreturn; if (sidmathang.Trim().Equals("") == true) { sidmathang = flxMatHang[flxMatHang.RowSel, "id_mathang"].ToString().Trim(); } } catch { } if (CheckMatHang(sidmathang, flxMatHang.RowSel) == true) { MessageBox.Show("Mặt hàng đã có trong đơn hàng này.\nVui lòng chọn một mặt hàng khác.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (flxMatHang.RowSel == flxMatHang.Rows.Count - 1) { flxMatHang.StartEditing(flxMatHang.Rows.Count - 1, 4); } else { flxMatHang.StartEditing(flxMatHang.RowSel, 4); } //flxMatHang.StartEditing(flxMatHang.Rows.Count - 1, 4); return; } tblmathang obj = new tblmathang(); tblmathangBL ctr = new tblmathangBL(); obj = ctr.GetByID(sidmathang); //flxMatHang[flxMatHang.RowSel, "id"] = ""; flxMatHang[flxMatHang.RowSel, "id_hoadon"] = ""; flxMatHang[flxMatHang.RowSel, "id_mathang"] = sidmathang; flxMatHang[flxMatHang.RowSel, "mathang"] = obj.ten.Trim(); //flxMatHang[flxMatHang.RowSel, "soluong"] = ""; flxMatHang[flxMatHang.RowSel, "donvi"] = obj.donvi.Trim(); try { if (txtCapDaiLy.Text.ToUpper().Trim().Equals("ĐẠI LÝ CẤP 1") == true) { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl1.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl1; } catch { } } if (txtCapDaiLy.Text.ToUpper().Trim().Equals("ĐẠI LÝ CẤP 2") == true) { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl2.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl2; } catch { } } if (txtCapDaiLy.Text.ToUpper().Trim().Equals("ĐẠI LÝ CẤP 3") == true) { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl3.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl3; } catch { } } if (txtCapDaiLy.Text.ToUpper().Trim().Equals("ĐẠI LÝ CẤP 4") == true) { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl4.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl4; } catch { } } if (txtCapDaiLy.Text.ToUpper().Trim().Equals("ĐẠI LÝ CẤP 5") == true) { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl5.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl5; } catch { } } if (txtCapDaiLy.Text.ToUpper().Trim().Equals("KHÁCH LẺ") == true) { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl5.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl5; } catch { } } if (Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "tt"]) == 0) { flxMatHang[flxMatHang.RowSel, flxMatHang.Cols.Count - 1] = 2; } flxMatHang_AfterEdit(sender, e); } catch { flxMatHang[flxMatHang.RowSel, "giaban"] = obj.giadl5.ToString().Trim(); try { flxMatHang[flxMatHang.RowSel, "thanhtien"] = Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "soluong"]) * obj.giadl5; } catch { } if (Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "tt"]) == 0) { flxMatHang[flxMatHang.RowSel, flxMatHang.Cols.Count - 1] = 2; } flxMatHang_AfterEdit(sender, e); } } catch { if (Convert.ToInt32(flxMatHang[flxMatHang.RowSel, "tt"]) == 0) { flxMatHang[flxMatHang.RowSel, flxMatHang.Cols.Count - 1] = 2; } flxMatHang_AfterEdit(sender, e); } } private void flxMatHang_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { menu_MatHangBan.Show(flxMatHang, e.X, e.Y); } else { return; } } private void flxMatHang_RowColChange(object sender, EventArgs e) { string loi = ""; try { int n = flxMatHang.RowSel; for (int i = 1; i <= flxMatHang.Rows.Count - 1; i++) { loi = flxMatHang.GetUserData(i, 0).ToString(); if (string.IsNullOrEmpty(loi) == true) { flxMatHang.Rows[i].Style = null; } } // to mau dong if (n > 0) { loi = flxMatHang.GetUserData(n, 0).ToString(); if (string.IsNullOrEmpty(loi) == true) { flxMatHang.Rows[n].Style = null; } } } catch { } } #endregion #region Xử lý tsmenu private void tsThemMoiMatHangBan_Click(object sender, EventArgs e) { AddMatHang(); } private void tsXoaMatHangBan_Click(object sender, EventArgs e) { DelMatHang(); } private void tsHuyMatHangBan_Click(object sender, EventArgs e) { if (txtID.Text.Trim().Equals("-1") == true) { Add(); } else { HienThiTTHoaDon(); HienThiDSMatHang(); } } #endregion private void txtChietKhau_TextChanged(object sender, EventArgs e) { double thanhtien = 0; try { thanhtien = Convert.ToDouble(txtTongTien.Text.Trim()); } catch { } double notoatruoc = 0; try { notoatruoc = Convert.ToDouble(txtNoToaTruoc.Text.Trim()); } catch { } double tienthanhtoan = 0; try { tienthanhtoan = Convert.ToDouble(txtTienThanhToan.Text.Trim()); } catch { } double chietkhau = 0; try { txtChietKhau.Text = Convert.ToDouble(txtChietKhau.Text.Trim()).ToString("N0", CultureInfo.InvariantCulture); try { chietkhau = Convert.ToDouble(txtChietKhau.Text.Trim()); } catch { txtChietKhau.Text = "0"; txtChietKhau.SelectionStart = txtChietKhau.Text.Length; } txtConNo.Text = ((thanhtien + notoatruoc) - (tienthanhtoan + chietkhau)).ToString("N0", CultureInfo.InvariantCulture); txtChietKhau.SelectionStart = txtChietKhau.Text.Length; } catch { txtChietKhau.Text = "0"; txtChietKhau.SelectionStart = txtChietKhau.Text.Length; } } private void txtTienThanhToan_TextChanged(object sender, EventArgs e) { double thanhtien = 0; try { thanhtien = Convert.ToDouble(txtTongTien.Text.Trim()); } catch { } double notoatruoc = 0; try { notoatruoc = Convert.ToDouble(txtNoToaTruoc.Text.Trim()); } catch { } double chietkhau = 0; try { chietkhau = Convert.ToDouble(txtChietKhau.Text.Trim()); } catch { } double tienthanhtoan = 0; try { txtTienThanhToan.Text = Convert.ToDouble(txtTienThanhToan.Text.Trim()).ToString("N0", CultureInfo.InvariantCulture); try { tienthanhtoan = Convert.ToDouble(txtTienThanhToan.Text.Trim()); } catch { txtTienThanhToan.Text = "0"; txtTienThanhToan.SelectionStart = txtTienThanhToan.Text.Length; } txtConNo.Text = ((thanhtien + notoatruoc) - (tienthanhtoan + chietkhau)).ToString("N0", CultureInfo.InvariantCulture); txtTienThanhToan.SelectionStart = txtTienThanhToan.Text.Length; } catch { txtTienThanhToan.Text = "0"; txtTienThanhToan.SelectionStart = txtTienThanhToan.Text.Length; } } private void ultraToolbarsManager1_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e) { switch (e.Tool.Key) { case "btn_Save": // ButtonTool flxMatHang.Focus(); Save(); break; case "btn_Abort": // ButtonTool if (txtID.Text.Trim().Equals("-1") == true) { Add(); } else { HienThiTTHoaDon(); HienThiDSMatHang(); } break; case "btn_Del": // ButtonTool Del(); break; case "btnExportHD": // ButtonTool XuatHoaDon(); break; } } } }
using System.ComponentModel.DataAnnotations; using HacktoberfestProject.Web.Models.Entities; namespace HacktoberfestProject.Web.Models.DTOs { public class Project { public Project() { } public Project(ProjectEntity projectEntity) { RepoName = projectEntity.RepoName; Owner = projectEntity.Owner; Url = projectEntity.Url; } [Display(Name = "Repository Name")] public string RepoName { get; set; } [Display(Name = "URL")] public string Url { get; set; } [Display(Name = "Repository Owner")] public string Owner { get; set; } } }
/*********************** @ author:zlong @ Date:2015-01-08 @ Desc:业务招待管理实体 * ********************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DriveMgr.Model { public class BusinessEntertainModel { #region Model private int _id; private decimal? _entertainamount; private string _entertainobject; private string _transactor; private DateTime? _transactdate; private string _entertainuse; private string _remark; private string _createperson; private DateTime? _createdate; private string _updateperson; private DateTime? _updatedate; private bool _deletemark; /// <summary> /// 编号 /// </summary> public int Id { set { _id = value; } get { return _id; } } /// <summary> /// 招待费用 /// </summary> public decimal? EntertainAmount { set { _entertainamount = value; } get { return _entertainamount; } } /// <summary> /// 招待对象 /// </summary> public string EntertainObject { set { _entertainobject = value; } get { return _entertainobject; } } /// <summary> /// 经办人 /// </summary> public string Transactor { set { _transactor = value; } get { return _transactor; } } /// <summary> /// 招待日期 /// </summary> public DateTime? TransactDate { set { _transactdate = value; } get { return _transactdate; } } /// <summary> /// 用途 /// </summary> public string EntertainUse { set { _entertainuse = value; } get { return _entertainuse; } } /// <summary> /// 备注 /// </summary> public string Remark { set { _remark = value; } get { return _remark; } } /// <summary> /// 创建人 /// </summary> public string CreatePerson { set { _createperson = value; } get { return _createperson; } } /// <summary> /// 创建日期 /// </summary> public DateTime? CreateDate { set { _createdate = value; } get { return _createdate; } } /// <summary> /// 更新人 /// </summary> public string UpdatePerson { set { _updateperson = value; } get { return _updateperson; } } /// <summary> /// 更新日期 /// </summary> public DateTime? UpdateDate { set { _updatedate = value; } get { return _updatedate; } } /// <summary> /// 删除标志 /// </summary> public bool DeleteMark { set { _deletemark = value; } get { return _deletemark; } } #endregion Model } }
using stottle_shop_api.Products.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace stottle_shop_api.Products.Repositories { public interface IWriteProducts { Task InsertAsync(IEnumerable<Product> products); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TiendaCarros { class inicio { private string placas; private string marca; private string modelo; private string telefono; private string año; public string pla { get { return placas; } set { placas = value; } } public string mar { get { return marca; } set { marca = value; } } public string mo { get { return modelo; } set { modelo = value; } } public string tel { get { return telefono; } set { telefono = value; } } public string ano { get { return año; } set { año = value; } } } }
using System; using OpenTK; using OpenTK.Graphics.OpenGL4; namespace ShadowMap { public class FrameBufferManager { #region main framebuffer public int MainDepthMapBufferObject { get; set; } public int MainDepthMapBufferTextureId { get; set; } public int MainRenderBufferObject { get; set; } public int AttrVertexFrameLocation { get; set; } public int AttrTexcoordFrameLocation { get; set; } public int UniformTextureFrame { get; set; } public int vertexBufferForFrameAddress; public int texCoordsForFrameAddress; public int MainFrameBufferProgramId { get; set; } #endregion #region auxillary framebuffer public int SecondDepthMapBufferObject { get; set; } public int SecondDepthMapBufferTextureId { get; set; } public int SecondRenderBufferObject { get; set; } public int AttrVertexFrameSecondLocation { get; set; } public int AttrTexcoordFrameSecondLocation { get; set; } public int UniformTextureFrameSecond { get; set; } public int vertexBufferForFrameSecondAddress; public int texCoordsForFrameSecondAddress; public int SecondFrameBufferProgramId { get; set; } #endregion public int Width { get; set; } public int Height { get; set; } public bool DebugDepth { get; set; } public FrameBufferManager(RenderEngine mainRender) { Width = mainRender.Width; Height = mainRender.Height; var textureMgr = new TextureManager(); CreateMainFrameBuffer(mainRender, textureMgr); CreateSecondFrameBuffer(mainRender, textureMgr); } private void CreateMainFrameBuffer(RenderEngine mainRender, TextureManager textureMgr) { MainFrameBufferProgramId = mainRender.Shaders.FrameBufferProgramId; var frameBufDesc = textureMgr.GetMainFrameBuffer(Width, Height); MainDepthMapBufferObject = frameBufDesc.FramBufferObject; MainDepthMapBufferTextureId = frameBufDesc.TextureId; MainRenderBufferObject = frameBufDesc.RenderBufferObject; GL.UseProgram(MainFrameBufferProgramId); AttrVertexFrameLocation = GL.GetAttribLocation(MainFrameBufferProgramId, "vPosition"); AttrTexcoordFrameLocation = GL.GetAttribLocation(MainFrameBufferProgramId, "vTexCoordinate"); UniformTextureFrame = GL.GetUniformLocation(MainFrameBufferProgramId, "uTexture"); GL.GenBuffers(1, out texCoordsForFrameAddress); GL.GenBuffers(1, out vertexBufferForFrameAddress); } private FrameBufferDesc CreateSecondFrameBuffer(RenderEngine mainRender, TextureManager textureMgr) { FrameBufferDesc frameBufDesc = textureMgr.GetFrameBuffer(Width, Height); SecondDepthMapBufferObject = frameBufDesc.FramBufferObject; SecondDepthMapBufferTextureId = frameBufDesc.TextureId; SecondFrameBufferProgramId = mainRender.Shaders.CreateFrameBufferProgram(); GL.UseProgram(SecondFrameBufferProgramId); AttrVertexFrameLocation = GL.GetAttribLocation(SecondFrameBufferProgramId, "vPosition"); AttrTexcoordFrameLocation = GL.GetAttribLocation(SecondFrameBufferProgramId, "vTexCoordinate"); UniformTextureFrame = GL.GetUniformLocation(SecondFrameBufferProgramId, "uTexture"); GL.GenBuffers(1, out texCoordsForFrameSecondAddress); GL.GenBuffers(1, out vertexBufferForFrameSecondAddress); return frameBufDesc; } public void EnableAuxillaryFrameBuffer() { GL.BindFramebuffer(FramebufferTarget.Framebuffer, SecondDepthMapBufferObject); GL.Viewport(0, 0, Width, Height); } public void FlushAuxillaryFrameBuffer() { GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); } public void EnableMainFrameBuffer() { GL.BindFramebuffer(FramebufferTarget.Framebuffer, MainDepthMapBufferObject); GL.Viewport(0, 0, Width, Height); } public void FlushMainFrameBuffer() { GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); } public void DrawFinal() { GL.Disable(EnableCap.DepthTest); GL.ClearColor(1, 0f, 0f, 0); GL.Clear(ClearBufferMask.ColorBufferBit); GL.UseProgram(MainFrameBufferProgramId); GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferForFrameAddress); var points = GetFrameBufferVertices(); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(6 * Vector2.SizeInBytes), points, BufferUsageHint.StaticDraw); GL.VertexAttribPointer(AttrVertexFrameLocation, 2, VertexAttribPointerType.Float, false, 0, 0); GL.EnableVertexAttribArray(AttrVertexFrameLocation); GL.BindBuffer(BufferTarget.ArrayBuffer, texCoordsForFrameAddress); var texCoords = GetFrameBufferTextureCoords(); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(6 * Vector2.SizeInBytes), texCoords, BufferUsageHint.StaticDraw); GL.VertexAttribPointer(AttrTexcoordFrameLocation, 2, VertexAttribPointerType.Float, false, 0, 0); GL.EnableVertexAttribArray(AttrTexcoordFrameLocation); GL.ActiveTexture(TextureUnit.Texture0); GL.Uniform1(UniformTextureFrame, 0); if (DebugDepth) { GL.BindTexture(TextureTarget.Texture2D, SecondDepthMapBufferTextureId); } else { GL.BindTexture(TextureTarget.Texture2D, MainDepthMapBufferTextureId); } GL.DrawArrays(PrimitiveType.Triangles, 0, 6); GL.BindVertexArray(0); GL.Flush(); } private Vector2[] GetFrameBufferVertices() { return quadVertices; } private Vector2[] GetFrameBufferTextureCoords() { return textQuadIndices; } private readonly Vector2[] textQuadIndices = new[] { new Vector2(0.0f, 1.0f), new Vector2(0.0f, 0.0f), new Vector2(1.0f, 0.0f), new Vector2(0.0f, 1.0f), new Vector2(1.0f, 0.0f), new Vector2(1.0f, 1.0f) }; private readonly Vector2[] quadVertices = new[] { // Positions new Vector2(-1.0f, 1.0f), new Vector2(-1.0f, -1.0f), new Vector2(1.0f, -1.0f), new Vector2(-1.0f, 1.0f), new Vector2( 1.0f, -1.0f), new Vector2(1.0f, 1.0f), }; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; public class TileMapVisualiser : MonoBehaviour { [SerializeField] private Tilemap floorTileMap, wallTileMap; [SerializeField] private TileBase floorTile, wallTop; public void paintFloorTile(IEnumerable<Vector2Int> floorPos) { paintTiles(floorPos, floorTileMap, floorTile); } internal void PaintSingleBasicWall(Vector2Int position) { paintSingleTiles(wallTileMap, wallTop, position); } private void paintTiles(IEnumerable<Vector2Int> position, Tilemap tileMap, TileBase tile) { foreach (var positions in position) { paintSingleTiles(tileMap, tile, positions); } } private void paintSingleTiles(Tilemap tileMap, TileBase tile, Vector2Int position) { var tilePosition = tileMap.WorldToCell((Vector3Int)position); tileMap.SetTile(tilePosition, tile); } public void Clear() { floorTileMap.ClearAllTiles(); wallTileMap.ClearAllTiles(); } }
using System; using System.Collections.Generic; using System.Linq; namespace GenerateNorthwindDBContext { public class GenerateNorthwindDBContext { private const int ShippingYear = 1997; private const string ShippingCountry = "Canada"; #region Task3. // Task 03. Write a method that finds all customers who have orders made in 1997 and shipped to Canada. public static IQueryable<Customer> OrdersShippedToCanada(NorthwindEntities dbContext) { var customersCollection = dbContext.Orders .Where(o => o.ShipCountry == ShippingCountry && o.OrderDate.Value.Year == ShippingYear) .Select(o => o.Customer) .Distinct(); return customersCollection; } #endregion #region Task4. // Task 04. Implement previous by using native SQL query and executing it through the DbContext. public static List<string> OrdersShippedToCanadaNativeSql(NorthwindEntities dbContext) { string query = "SELECT DISTINCT c.ContactName " + "FROM Customers c " + "JOIN Orders o " + "ON o.CustomerID = c.CustomerID " + "WHERE YEAR(o.OrderDate) = {0} " + "AND o.ShipCountry = {1}"; string[] parameters = new string[] { ShippingYear.ToString(), ShippingCountry }; var resultingCustomers = dbContext.Database.SqlQuery<string>(query, parameters); return resultingCustomers.ToList(); } #endregion #region Task5. // Task 05. Write a method that finds all the sales by specified region and period (start / end dates). public static IQueryable<Order> SalesByRegionAndPeriod(NorthwindEntities dbContext, string region, DateTime startDate, DateTime endDate) { var ordersCollection = dbContext.Orders .Where(o => o.ShipRegion == region && o.OrderDate.Value >= startDate && o.OrderDate.Value <= endDate); return ordersCollection; } #endregion #region Task9. public static void AddOrders(NorthwindEntities dbContext, params Order[] orders) { using (var currentTransaction = dbContext.Database.BeginTransaction()) { try { foreach (var order in orders) { dbContext.Orders.Add(order); } dbContext.SaveChanges(); currentTransaction.Commit(); } catch(Exception ex) { Console.WriteLine(ex.Message); currentTransaction.Rollback(); } } } #endregion #region Task10. // Task 10. Create a stored procedures in the Northwind database for finding the total incomes // for given supplier name and period (start date, end date). // Implement a C# method that calls the stored procedure and returns the retuned record set. public static Nullable<decimal> GetTotalIncome(NorthwindEntities dbContext, string supplier, DateTime startDate, DateTime endDate) { var result = dbContext.GetTotalIncome(supplier, startDate, endDate); return result.FirstOrDefault(); } #endregion public static void Main() { using (NorthwindEntities dbContext = new NorthwindEntities()) { #region Task3. // Task 03. var customerCollection = OrdersShippedToCanada(dbContext); foreach (var customer in customerCollection) { Console.WriteLine(customer.ContactName); } #endregion Console.WriteLine("---------------------"); #region Task4. // Task 04. var customerCollectonNativeSql = OrdersShippedToCanadaNativeSql(dbContext); foreach (var customer in customerCollection) { Console.WriteLine(customer.ContactName); } #endregion Console.WriteLine("---------------------"); #region Task5. // Task 05. string region = "RJ"; DateTime startDate = new DateTime(1995, 01, 01); DateTime endDate = new DateTime(1998, 12, 31); var sales = SalesByRegionAndPeriod(dbContext, region, startDate, endDate); foreach (var sale in sales) { Console.WriteLine(sale.CustomerID); } #endregion Console.WriteLine("---------------------"); #region Task7. NorthwindEntities firstDbContext = new NorthwindEntities(); NorthwindEntities secondDbContext = new NorthwindEntities(); var firstDbCustomer = firstDbContext.Customers.FirstOrDefault(); var secondDbCustomer = secondDbContext.Customers.FirstOrDefault(); firstDbCustomer.ContactName = "Misho"; secondDbCustomer.ContactName = "Pesho"; firstDbContext.SaveChanges(); secondDbContext.SaveChanges(); #endregion #region Task9. Order firstOrder = new Order() { OrderDate = DateTime.Now, RequiredDate = DateTime.Now, ShippedDate = DateTime.Now, ShipName = "Santa Maria" }; Order secondOrder = new Order() { OrderDate = DateTime.Now, RequiredDate = DateTime.Now, ShippedDate = DateTime.Now, ShipName = "Santa Monica" }; AddOrders(dbContext, firstOrder, secondOrder); #endregion #region Task10. DateTime startDateTotalIncome = new DateTime(1900, 08, 08); var totalIncome = GetTotalIncome(dbContext, "Exotic Liquids", startDateTotalIncome, DateTime.Now); Console.WriteLine("Exotic Liquids total income: {0}", totalIncome); #endregion } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FakeDataAccess { public class DataAccess { List<Ogrenci> ogrenciListesi = new List<Ogrenci>(); public DataAccess() { //Bir listeye değerler doldursun Ogrenci ornek = new Ogrenci() { OgrenciAdi = "Fırat", OgrenciSoyadi = "Özcevahir", Sira = 1 }; ogrenciListesi.Add(ornek); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Ender", OgrenciSoyadi = "Kader", Sira = 2 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Leo", OgrenciSoyadi = "Öztürk", Sira = 3 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Merve", OgrenciSoyadi = "Özer", Sira = 4 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Tuğçe", OgrenciSoyadi = "Kökçü", Sira = 5 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Ziya", OgrenciSoyadi = "Çetin", Sira = 8 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Ali", OgrenciSoyadi = "Güven", Sira = 6 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Ercan", OgrenciSoyadi = "Tamer", Sira = 7 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Ali", OgrenciSoyadi = "Temel", Sira = 9 }); ogrenciListesi.Add(new Ogrenci() { OgrenciAdi = "Veli", OgrenciSoyadi = "Tekin", Sira = 10 }); } public List<Ogrenci> SelectAll() { return ogrenciListesi; } public Ogrenci Sorgula(int id) { Ogrenci sonuc = ogrenciListesi.FirstOrDefault(x => x.Sira == id); return sonuc; } public int Update(Ogrenci ogr) { Ogrenci sonuc = ogrenciListesi.FirstOrDefault(x => x.Sira == ogr.Sira); if (sonuc != null) { sonuc.OgrenciAdi = ogr.OgrenciAdi; sonuc.OgrenciSoyadi = ogr.OgrenciSoyadi; return 1; } else return 0; } public int Delete(int id) { Ogrenci sonuc = ogrenciListesi.FirstOrDefault(x => x.Sira == id); if (sonuc != null) { ogrenciListesi.Remove(sonuc); return 1; } else return 0; } public int Add(Ogrenci ogr) { ogrenciListesi.Add(ogr); return ogr.Sira; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Sokoban { public partial class Menu : Form { Ranking ranking; private CustomButton cbNewGame; private CustomButton cbRanking; private CustomButton cbExit; private Bitmap pngLogo; private PictureBox logo; SoundPlayer typewriter; public Menu() { //Enable full screen FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Maximized; this.DoubleBuffered = true; InitializeComponent(); logo = new PictureBox(); pngLogo = new Bitmap(@"Drawable\logoMenu.png"); logo.BackColor = Color.Transparent; logo.Image = pngLogo; logo.Width = pngLogo.Width; logo.Height = pngLogo.Height; logo.Location = new Point(250,20); cbNewGame = new CustomButton(@"Buttons\MenuButtons\NewGameNormal.png", @"Buttons\MenuButtons\NewGamePress.png", @"Buttons\MenuButtons\NewGameFocus.png", 450, 350, "NewGameTag"); cbRanking = new CustomButton(@"Buttons\MenuButtons\RankingNormal.png", @"Buttons\MenuButtons\RankingPress.png", @"Buttons\MenuButtons\RankingFocus.png", 480, 450, "RankingTag"); cbExit = new CustomButton(@"Buttons\MenuButtons\ExitNormal.png", @"Buttons\MenuButtons\ExitPress.png", @"Buttons\MenuButtons\ExitFocus.png", 540, 550, "ExitTag"); this.Controls.Add(logo); this.Controls.Add(cbNewGame); this.Controls.Add(cbRanking); this.Controls.Add(cbExit); this.BackgroundImage = new Bitmap(@"Drawable\Wall_Beige.png"); cbNewGame.MouseClick += new MouseEventHandler(mouseClick); cbRanking.MouseClick += new MouseEventHandler(mouseClick); cbExit.MouseClick += new MouseEventHandler(mouseClick); } private void mouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { switch(((CustomButton)sender).Tag.ToString()){ case "RankingTag": if(ranking == null){ ranking = new Ranking(); ranking.Tag = this; } ranking.Show(this); this.Hide(); break; case "ExitTag": Application.Exit(); break; case "NewGameTag": Game newGame = new Game(); newGame.Tag = this; newGame.Show(this); this.Hide(); break; } } } } }
using OpenQA.Selenium; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Applitools.Framework { public static class Extensions { public static bool Exists(this IWebDriver driver, By by) { return driver.FindElements(by).Count > 0; } public static bool Displayed(this IWebDriver driver, By by) { try { var element = driver.FindElement(by) ?? null; return (element.Displayed && (element.Size.Width > 0 && element.Size.Height > 0)); } catch { return false; } } public static void WaitForVisible(this IWebDriver driver, By by) { try { Stopwatch stopwatch = new Stopwatch(); while (!driver.Displayed(by)) { stopwatch.Start(); if (stopwatch.ElapsedMilliseconds > 2000) break; } stopwatch.Stop(); } catch { } } public static void Click(this IWebDriver driver, By by) { driver.WaitForVisible(by); var element = driver.FindElement(by); if (driver.Displayed(by)) element.Click(); } public static void SetValue(this IWebDriver driver, By by, string value) { driver.WaitForVisible(by); var element = driver.FindElement(by); //First check that element is able to be interacted with if (driver.Displayed(by)) { //Determine if the value to be set is boolean if (value.Equals("true") || value.Equals("false")) { bool toSelect = bool.Parse(value); //Check if element is selected and shouldn't be, or vice versa, and click if so if ((toSelect & !element.Selected) || (!toSelect & element.Selected)) driver.Click(by); } else element.SendKeys(value); } } //Verify elements retrieved with By locator contains only the strings provided public static bool ElementsContainText(this IWebDriver driver, By by, string[] values) { var elements = driver.FindElements(by); List<string> expected = values.ToList(); List<string> actual = elements.Select(ele => ele.Text).ToList(); string[] notFound = actual.Except(expected).ToArray(); if (notFound.Any()) return false; return true; } //Verify elements retrieved with By locator contains only the value provided public static bool ElementAttributeContainsValue(this IWebDriver driver, By by, string attribute, string[] values) { var elements = driver.FindElements(by); List<string> expected = values.ToList(); List<string> actual = elements.Select(ele => ele.GetAttribute(attribute)).ToList(); string[] notFound = actual.Except(expected).ToArray(); if (notFound.Any()) return false; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.AppServices.ConsoContracts.DomesticTicket.DataObjects { public class ConsoOrderCoordination { public int Id { get; set; } /// <summary> /// 协调日期 /// </summary> public DateTime AddDatetime { get; set; } /// <summary> /// 协调内容 /// </summary> public string Content { get; set; } /// <summary> /// 协调人 /// </summary> public string OperationPerson { get; set; } /// <summary> /// 协调类型 /// </summary> public string Type { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CXO.ProgrammingAssignments.ORM.Models { public class DefterosDbObject : DbObject { public DefterosDbObject(object obj) : base(obj) { } protected override string Decorator(string str) { return $"[{str}]"; } } }
using System; using System.Collections.Generic; namespace SingletonPattern.Models { public class RegisterNote { private static RegisterNote _registerNote = new RegisterNote(); public List<string> Histories { get; set; } = new List<string>(); // Make Constructor private private RegisterNote() { } public static RegisterNote GetInstance() => _registerNote; } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System.Collections.Generic; using Newtonsoft.Json; namespace Dnn.PersonaBar.SiteSettings.Services.Dto { [JsonObject] public class UpdateTransaltionsRequest { public int? PortalId { get; set; } public string Mode { get; set; } public string Locale { get; set; } public string ResourceFile { get; set; } public IList<LocalizationEntry> Entries { get; set; } } }
using LibSelection; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace RgxCTests { [TestClass] public class RegexTest { [TestMethod] public void Test1() { Selection s = new Selection("she said to slad the shed"); s.Replace((string input) => { return input.ToUpper() + "she said to slad the shed"; }); s.Matches(@"s(?<ac>\w*)d", RegexOptions.IgnoreCase)[0].Replace("$$1$1${1}1${ac}$&$$${0}$0");//fixed overload ambiguity Assert.AreEqual("SHE $1AIAI1AISAID$SAIDSAID TO SLAD THE SHEDshe said to slad the shed", s.Value); } [TestMethod] public void Test2() { Selection s = new Selection("{\n\"hello\":\"ylevol\"\n}"); s.Match(@"{\s*""(?<key>\w+)""\s*:\s*""(?<value>\w+)""\s*}").Replace(new string[] { null, "keyyay", "valyay" }); Assert.AreEqual("{\n\"keyyay\":\"valyay\"\n}", s.Value); s = new Selection("{\n\"hello\":\"ylevol\"\n}"); s.Match(@"{\s*""(?<key>\w+)""\s*:\s*""(?<value>\w+)""\s*}").Replace(new Dictionary<string, string>() { {"value","valyay"}, {"key","keyyay"} }); Assert.AreEqual("{\n\"keyyay\":\"valyay\"\n}", s.Value); s = new Selection("{\n\"hello\":\"ylevol\"\n}"); s.Match(@"{\s*""(?<key>\w+)""\s*:\s*""(?<value>\w+)""\s*}").Replace(new ReplaceDelegate[] { null, (string key) => { return key.ToUpper(); }, (string val) => { return new string(val.ToCharArray().Reverse().ToArray()); }}); Assert.AreEqual("{\n\"HELLO\":\"lovely\"\n}", s.Value); s = new Selection("{\n\"hello\":\"ylevol\"\n}"); s.Match(@"{\s*""(?<key>\w+)""\s*:\s*""(?<value>\w+)""\s*}").Replace(new Dictionary<string, ReplaceDelegate>() { {"value",(string val) => { return new string(val.ToCharArray().Reverse().ToArray()); }}, {"key",(string key) => { return key.ToUpper(); }} }); Assert.AreEqual("{\n\"HELLO\":\"lovely\"\n}", s.Value); } [TestMethod] public void Test3() { Regex r = new Regex(@"(((public|static)\s+)*)function\s+(\w+)"); Selection s = new Selection("public static function findObjId"); s.Match(r).Replace(new Dictionary<string, string>() { { "4", "methodName" }, { "3","unstatic" }, }); s.Sel(0, 6).Replace("unpublic"); Assert.AreEqual("unpublic unstatic function methodName",s.Value); s = new Selection("public static function findObjId"); s.Match(r).Replace(new Dictionary<string, string>() { { "3","unstatic" }, { "4", "methodName" }, }); s.Sel(0, 6).Replace("unpublic"); Assert.AreEqual("unpublic unstatic function methodName", s.Value); } [TestMethod] public void BehaviorTest() { //changing the root after having children Regex r = new Regex(@"(((\w+)\s+)*)function\s+(\w+)"); Selection s = new Selection("public static function findObjId"); RSelection s2 = s.Match(r); s2.Replace(new Dictionary<string, string>() { { "4", "methodName" }, { "3","unstatic" }, }); s.Sel(0, 6).Replace("unpublic");//changing root s2.Replace(new Dictionary<string, string>() { { "3","ee" }, //these pointers are now inaccurate+unpredictable because children are 'unlinked' from root { "4", "oo" }, }); Assert.AreEqual("public ee function oome", s.Value);//this result is unpredictable. This is what it produces atm (behavior) //this is what you should do instead: s = new Selection("public static function findObjId"); s2 = s.Match(r); s2.Replace(new Dictionary<string, string>() { { "4", "methodName" }, { "3","unstatic" }, }); s.Sel(0, 6).Replace("unpublic"); //after changing root... s.Commit(); //reset all pointers s2 = s.Match(r); //evaluate the pointers again s2.Replace(new Dictionary<string, string>() { { "3","ee" }, { "4", "oo" }, }); Assert.AreEqual("unpublic ee function oo", s.Value);//this is what we would have expected //or like this: s = new Selection("public static function findObjId"); s.Match(r).Replace(new Dictionary<string, string>() { { "4", "methodName" }, { "3","unstatic" }, }); s.Sel(0, 6).Replace("unpublic"); s.Match(r).Replace(new Dictionary<string, string>() //NB: pointers are being re-evaluated here { { "3","ee" }, { "4", "oo" }, }); Assert.AreEqual("unpublic ee function oo", s.Value); } } }
using System; using System.Linq; using Moq; using Selenite.Commands.Implementation; using Selenite.Services; using Selenite.Services.Implementation; using Xunit; using Xunit.Extensions; namespace Selenite.Tests.Services { public class TestCollectionServiceTests { public const string Test = @"{ ""Enabled"": true, ""DefaultDomain"": ""http://google.com/"", ""Tests"": [ { ""Enabled"": true, ""Name"": ""Basic"", ""Url"": """", ""Commands"": [ { ""Title"": ""Google"", ""IsCaseSensitive"": false, ""IsFalseExpected"": false, ""Name"": ""IsTitleEqual"" } ] } ] }"; public string WriteAllTextValue { get; private set; } private ITestCollectionService GetTestCollectionService(string name, string json) { var configurationService = new Mock<IConfigurationService>(); configurationService .SetupGet(p => p.TestScriptsPath) .Returns("C:\\"); var path = String.Format("C:\\{0}", name); var fileService = new Mock<IFileService>(); fileService .Setup(f => f.ReadAllText(path)) .Returns(json); fileService .Setup(f => f.WriteAllText(path, It.IsAny<string>())) .Callback<string, string>((p, c) => WriteAllTextValue = c); var commandService = new CommandService(); return new TestCollectionService(configurationService.Object, fileService.Object, commandService); } [Theory] [InlineData("Test.json", Test)] public void GetTestCollection(string name, string json) { var testCollectionService = GetTestCollectionService(name, json); var testCollection = testCollectionService.GetTestCollection(name); Assert.Equal(1, testCollection.Tests.Count); var test = testCollection.Tests.First(); Assert.Equal(1, test.Commands.Count); Assert.Equal(String.Empty, test.Url); Assert.Equal("http://google.com/", test.TestUrl); var command = (IsTitleEqualCommand) test.Commands.First(); Assert.Equal("IsTitleEqual", command.Name); Assert.Equal("Google", command.Title); Assert.Equal(false, command.IsCaseSensitive); } [Theory] [InlineData("Test.json", Test)] public void SaveTestCollection(string name, string json) { var testCollectionService = GetTestCollectionService(name, json); var testCollection = testCollectionService.GetTestCollection(name); testCollectionService.SaveTestCollection(testCollection); Assert.Equal(json, WriteAllTextValue); } } }
using Grupo5_Hotel.Datos; using Grupo5_Hotel.Entidades.Entidades; using Grupo5_Hotel.Entidades.Excepciones; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Grupo5_Hotel.Negocio { public static class HotelServicio { private static List<Hotel> cacheHoteles; static HotelServicio() { RefrescarCache(); } private static void RefrescarCache() { cacheHoteles = HotelMapper.TraerHoteles(); } public static List<Hotel> TraerHoteles() { return cacheHoteles; } public static void InsertarHotel(Hotel hotel) { if (ExisteHotel(hotel)) { throw new Exception("no se encontró el hotel"); } else { TransactionResult result = HotelMapper.Insert(hotel); if (!result.IsOk) { throw new ErrorServidorException(result.Error); } else { RefrescarCache(); } } } public static bool ExisteHotel(Hotel hotel) { return cacheHoteles.Any(h => h.Equals(hotel)); } public static Hotel TraerHotelPorId(int id) { return cacheHoteles.Find(h => h.Id == id); } public static int ProximoId() { return cacheHoteles.Max(hotel => hotel.Id) + 1; } } }
using bot_backEnd.DAL.Interfaces; using bot_backEnd.Data; using bot_backEnd.Models; using bot_backEnd.Models.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.DAL { public class UserDAL : IUserDAL { private readonly AppDbContext _context; public UserDAL(AppDbContext context) { _context = context; } public async Task<ActionResult<IEnumerable<User>>> GetAllUsers() { return await _context.User.Include(c => c.City).Include(c => c.ProfilePhoto).ToListAsync(); } public async Task<ActionResult<User>> AddUser(User user) { _context.User.Add(user); await _context.SaveChangesAsync(); return user; } public async Task<ActionResult<User>> GetUserByID(int id) { return await _context.User .Include(u => u.City) .Include(u => u.ProfilePhoto) .Include(u => u.AcceptedChallenges) .Include(u => u.Gender) .FirstOrDefaultAsync(p => p.Id == id); } public async Task<ActionResult<User>> UpdateUserInfo(UserVM userVM) { var userToEdit = await _context.User.FindAsync(userVM.Id); userToEdit.FirstName = userVM.FirstName; userToEdit.LastName = userVM.LastName; userToEdit.Email = userVM.Email; userToEdit.CityID = userVM.CityID; await _context.SaveChangesAsync(); return userToEdit; } public async Task<ActionResult<bool>> UpdateUserPassword(int userID, string oldPassword, string newPassword) { var userToEdit = await _context.User.FindAsync(userID); if (userToEdit == null) return false; var passCheck = SHA256.Verify256SHA(oldPassword, userToEdit.Password); if (!passCheck) return false; var password = SHA256.CreateSHA256Hash(newPassword); userToEdit.Password = password; await _context.SaveChangesAsync(); return true; } public async Task<ActionResult<bool>> CheckUserExistance(int userID) { var user = await _context.User.FindAsync(userID); if (user == null) return false; else return true; } } }