text
stringlengths
13
6.01M
using Application.Client.Constants; using Application.Client.Entities.Message; using System; using System.Collections; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine; using UnityEngine.UI; public class ClientSocket : MonoBehaviour { #region GUI private Text email; private Text password; #endregion #region private members private TcpClient socketConnection; private Thread clientReceiveThread; private Client me; #endregion // Use this for initialization void Start() { email = GameObject.Find("ThisIsTheUserEmail").GetComponent<Text>(); password = GameObject.Find("ThisIsTheUserPassword").GetComponent<Text>(); this.me = new Client(0, 0, String.Empty, String.Empty, String.Empty, DateTime.Now, String.Empty, "Hors ligne"); ConnectToTcpServer(); } // Update is called once per frame void Update() { if (this.me.statusUser != "Hors ligne") { if (Input.GetKeyDown(KeyCode.Space)) { SendMessage jump = new SendMessage("", "INPUT", new string[] { "MOVE", "JUMP" }); sendMessage(jump); } if (Input.GetKeyUp(KeyCode.Escape)) { SendMessage disconnect = new SendMessage("0", "DISCONNECTION", new string[] { me.getToken() }); sendMessage(disconnect); } } } public void connect() { SendMessage connect = new SendMessage("0", "CONNECTION", new string[] { email.text, password.text }); sendMessage(connect); } /// <summary> /// Setup socket connection. /// </summary> private void ConnectToTcpServer() { try { clientReceiveThread = new Thread(new ThreadStart(ListenForData)); clientReceiveThread.IsBackground = true; clientReceiveThread.Start(); } catch (Exception e) { Debug.Log("On client connect exception " + e); } } /// <summary> /// Runs in background clientReceiveThread; Listens for incomming data. /// </summary> private void ListenForData() { try { socketConnection = new TcpClient("127.0.0.1", 5757); //51.91.156.75 Byte[] bytes = new Byte[1024]; while (true) { // Get a stream object for reading using (NetworkStream stream = socketConnection.GetStream()) { int length; // Read incomming stream into byte arrary. while ((length = stream.Read(bytes, 0, bytes.Length)) != 0) { var incommingData = new byte[length]; Array.Copy(bytes, 0, incommingData, 0, length); // Convert byte array to string message. string serverMessage = Encoding.ASCII.GetString(incommingData); Debug.Log("Server send : " + serverMessage); // Client message filter and process RequestManager(serverMessage); } } } } catch (SocketException socketException) { Debug.Log("Socket exception: " + socketException); } } private void RequestManager(string clientMessage) { // Put the client string message into an object ClientMessage ReceivedMessage msg = new ReceivedMessage(clientMessage); // Client message is process depending on the ACTION send; switch (msg.action) { case ConstsActions.DISCONNECTION: this.me.statusUser = msg.data[0]; Debug.Log("You are now Offline."); break; case ConstsActions.CONNECTION: if (msg.data[0] == "SUCCESS") { this.me = new Client( int.Parse(msg.data[1]), int.Parse(msg.data[2]), msg.data[3], msg.data[4], msg.data[5], Convert.ToDateTime(msg.data[6]), msg.data[7], msg.data[8] ); Debug.Log("You are connected as " + this.me.getToken() + "."); } else if (msg.data[0] == "FAIL") { Debug.Log("Connection failed"); } break; default: break; } } /// <summary> /// Send message to server using socket connection. /// </summary> private void sendMessage(SendMessage serverMessage) { if (socketConnection == null) { return; } try { // Get a stream object for writing. NetworkStream stream = socketConnection.GetStream(); if (stream.CanWrite) { // Convert string message to byte array. byte[] clientMessageAsByteArray = Encoding.ASCII.GetBytes(serverMessage.getMessage()); // Write byte array to socketConnection stream. stream.Write(clientMessageAsByteArray, 0, clientMessageAsByteArray.Length); Debug.Log("You send : " + serverMessage.getMessage()); } } catch (SocketException socketException) { Debug.Log("Socket exception: " + socketException); } } }
namespace Whale.Shared.Models.Meeting { public class MeetingAndLink { public DAL.Models.Meeting Meeting { get; set; } public string Link { get; set; } } }
using TMPro; using UnityEngine; public class GameSession : MonoBehaviour { [SerializeField] TextMeshProUGUI scoreUI; [SerializeField] int score = 0; const string SCORE_PREFIX = "Score: "; const int pointsPerBlock = 10; private void Awake() { if (FindObjectsOfType<GameSession>().Length > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } } private void Start() { UpdateScoreText(); } public void UpdateScore() { score += pointsPerBlock; UpdateScoreText(); } public void UpdateScoreText() { scoreUI.text = SCORE_PREFIX + score.ToString(); } public void ResetGame() { Destroy(gameObject); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; using System.Threading.Tasks; namespace SolidabisChallenge.Api { class SentenceApiClient { private readonly HttpClient httpClient; public SentenceApiClient(HttpClient httpClient) { httpClient.BaseAddress = new Uri("https://koodihaaste-api.solidabis.com/"); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJidWxsc2hpdCI6ImJ1bGxzaGl0IiwiaWF0IjoxNTcyMTk1NzU5fQ.UIlv7j9VzWzInPp12lXvgC-zEh8z4FSUsr2Jkn_AjX4"); this.httpClient = httpClient; } public async Task<IEnumerable<string>> GetSentences() { using HttpResponseMessage response = await httpClient.GetAsync("bullshit"); response.EnsureSuccessStatusCode(); Stream responseContent = await response.Content.ReadAsStreamAsync(); Sentences sentences = await JsonSerializer.DeserializeAsync<Sentences>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); return sentences.Bullshits.Select(bs => bs.Message); } } }
using System; using System.Collections.Generic; using UnityEngine; using Verse; namespace Quests { public class StartQuestDef : Def { public List<QuestGiverType> questGiverTypes; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 shared; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thrift.Server; using Thrift.Transport; using tutorial; namespace CSharpAsyncTutorial.Server { class Program { static void Main(string[] args) { try { CalculatorHandler handler = new CalculatorHandler(); Calculator.Processor processor = new Calculator.Processor(handler); TServerTransport serverTransport = new TServerSocket(9090); TServer server = new TSimpleServer(processor, serverTransport,(str)=>Console.WriteLine($"Thrift Log:{str}")); // Use this for a multithreaded server // server = new TThreadPoolServer(processor, serverTransport); Console.WriteLine("Starting the server..."); server.Serve(); } catch (Exception x) { Console.WriteLine(x.StackTrace); } Console.WriteLine("done."); } } public class CalculatorHandler :Calculator.ISync { public CalculatorHandler() { } public void ping() { Console.WriteLine("ping()"); } public int add(int n1, int n2) { //Console.WriteLine("add({0},{1})", n1, n2); return n1 + n2; } public void zip() { Console.WriteLine("zip()"); throw new InvalidOperation(); } public int calculate(int logid, Work w) { var ex = new InvalidOperation(); ex.WhatOp =(int)Operation.ADD; ex.Why = "Invalid calculate"; throw ex; } public SharedStruct getStruct(int key) { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class moving : MonoBehaviour { public float velocity;//variable para establecer la velocidad de movimiento public float speed = 5f; void Update() { Movimiento(); MovimientoMovil(); } public void Movimiento () { if (Spawner.ganador == true) { if (Spawner.inGame == true) { if(Input.GetKey(KeyCode.D) && transform.position.x < 7f )//se obtiene la tecla para ir hacia la derecha y se crea una condicional para moverse { transform.position += Vector3.right * velocity;//se mueve hacia la derecha si se da la condicional anterior transform.Rotate(0,0,speed * Time.deltaTime); } if(Input.GetKey(KeyCode.A) && transform.position.x > -7f)//se obtiene la tecla para ir hacia la izquierda y se crea una condicional para moverse { transform.position -= Vector3.right * velocity;//se mueve hacia la izquierda si se da la condicional anterior transform.Rotate(0,0,-speed * Time.deltaTime); } } } } public void MovimientoMovil () { if (Spawner.ganador == true) { if (Spawner.inGame == true) { if (Input.touchCount >= 1) { if (Input.touches[0].position.x < (Screen.width / 2) && transform.position.x > -7f) { transform.position -= Vector3.right * velocity; } if (Input.touches[0].position.x > (Screen.width / 2) && transform.position.x < 7f) { transform.position += Vector3.right * velocity; } } } } } }
using AutoMapper; using RoboBank.Merchant.Application; using RoboBank.Merchant.Domain; using RoboBank.Merchant.Service.Models; namespace RoboBank.Merchant.Service { public static class AutoMapperConfig { public static void RegisterMappings() { Mapper.Initialize(cfg => { cfg.CreateMap<MerchantWebsiteModel, MerchantWebsiteInfo>(); cfg.CreateMap<MerchantWebsiteInfo, MerchantWebsiteModel>(); cfg.CreateMap<MerchantWebsite, MerchantWebsiteInfo>(); cfg.CreateMap<MerchantWebsiteInfo, MerchantWebsite>(); }); } } }
using System.Threading.Tasks; using Meziantou.Analyzer.Rules; using TestHelper; using Xunit; namespace Meziantou.Analyzer.Test.Rules; public sealed class UseStringEqualsAnalyzerTests { private static ProjectBuilder CreateProjectBuilder() { return new ProjectBuilder() .WithAnalyzer<UseStringEqualsAnalyzer>() .WithCodeFixProvider<UseStringEqualsFixer>(); } [Fact] public async Task Equals_StringLiteral_stringLiteral_ShouldReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test() { var a = [||]""a"" == ""v""; } }"; const string CodeFix = @" class TypeName { public void Test() { var a = string.Equals(""a"", ""v"", System.StringComparison.Ordinal); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ShouldReportDiagnosticWithMessage("Use string.Equals instead of Equals operator") .ShouldFixCodeWith(CodeFix) .ValidateAsync(); } [Fact] public async Task NotEquals_StringLiteral_stringLiteral_ShouldReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test() { var a = [||]""a"" != ""v""; } }"; const string CodeFix = @" class TypeName { public void Test() { var a = !string.Equals(""a"", ""v"", System.StringComparison.Ordinal); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ShouldReportDiagnosticWithMessage("Use string.Equals instead of NotEquals operator") .ShouldFixCodeWith(CodeFix) .ValidateAsync(); } [Fact] public async Task Equals_StringVariable_stringLiteral_ShouldReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test(string str) { var a = [||]str == ""v""; } }"; const string CodeFix = @" class TypeName { public void Test(string str) { var a = string.Equals(str, ""v"", System.StringComparison.Ordinal); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ShouldReportDiagnosticWithMessage("Use string.Equals instead of Equals operator") .ShouldFixCodeWith(CodeFix) .ValidateAsync(); } [Fact] public async Task Equals_ObjectVariable_stringLiteral_ShouldNotReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test() { object str = """"; var a = str == ""v""; } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task Equals_stringLiteral_null_ShouldNotReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test() { var a = ""a"" == null; var b = null == ""a""; } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task Equals_InIQueryableMethod_ShouldNotReportDiagnostic() { const string SourceCode = @"using System.Linq; class TypeName { public void Test() { IQueryable<string> query = null; query = query.Where(i => i == ""test""); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task Equals_EmptyString_ShouldNotReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test() { var a = """" == ""v""; } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task Equals_StringEmpty_ShouldNotReportDiagnostic() { const string SourceCode = @" class TypeName { public void Test() { var a = string.Empty == ""v""; } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task Replace_Meziantou_Framework_EqualsOrdinal() { const string SourceCode = @" class TypeName { public void Test() { var a = [|""a"" == ""b""|]; } }"; const string CodeFix = @" using Meziantou.Framework; class TypeName { public void Test() { var a = ""a"".EqualsOrdinal(""b""); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ShouldFixCodeWith(index: 2, CodeFix) .AddNuGetReference("Meziantou.Framework", "3.0.23", "lib/net6.0/") .ValidateAsync(); } [Fact] public async Task Replace_Meziantou_Framework_EqualsIgnoreCase() { const string SourceCode = @" class TypeName { public void Test() { var a = [|""a"" == ""b""|]; } }"; const string CodeFix = @" using Meziantou.Framework; class TypeName { public void Test() { var a = ""a"".EqualsIgnoreCase(""b""); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ShouldFixCodeWith(index: 3, CodeFix) .AddNuGetReference("Meziantou.Framework", "3.0.23", "lib/net6.0/") .ValidateAsync(); } }
using System; using System.IO; using zlib; namespace RO.Net { public class NetZlib { private static void CopyStream(Stream input, Stream output) { byte[] array = new byte[1024]; int num; while ((num = input.Read(array, 0, array.Length)) > 0) { output.Write(array, 0, num); } output.Flush(); } private static Stream DecompressStream(Stream sourceStream) { MemoryStream memoryStream = new MemoryStream(); ZOutputStream zOutputStream = new ZOutputStream(memoryStream); NetZlib.CopyStream(sourceStream, zOutputStream); zOutputStream.finish(); return memoryStream; } private static Stream CompressStream(Stream sourceStream) { MemoryStream memoryStream = new MemoryStream(); ZOutputStream zOutputStream = new ZOutputStream(memoryStream, -1); NetZlib.CopyStream(sourceStream, zOutputStream); zOutputStream.finish(); return memoryStream; } public static byte[] Compress(byte[] bytes, int offset = 0, int length = -1) { MemoryStream memoryStream = new MemoryStream(bytes, offset, (0 >= length) ? (bytes.Length - offset) : length); Stream stream = NetZlib.CompressStream(memoryStream); byte[] array = new byte[stream.get_Length()]; stream.set_Position(0L); stream.Read(array, 0, array.Length); stream.Close(); memoryStream.Close(); return array; } public static byte[] Decompress(byte[] bytes, int offset = 0, int length = -1) { MemoryStream memoryStream = new MemoryStream(bytes, offset, (0 >= length) ? (bytes.Length - offset) : length); Stream stream = NetZlib.DecompressStream(memoryStream); byte[] array = new byte[stream.get_Length()]; stream.set_Position(0L); stream.Read(array, 0, array.Length); stream.Close(); memoryStream.Close(); return array; } } }
using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Web; namespace GetLabourManager.Configuration { public class GangConfiguration:EntityTypeConfiguration<Gang> { public GangConfiguration() { Property(x => x.Code).IsRequired().HasMaxLength(25); Property(x => x.Description).IsRequired().HasMaxLength(30); Property(x => x.Status).IsOptional().HasMaxLength(15); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Meet_and_Copmete_Capstone.Models { public class Invite { [Key] public int Id { get; set; } public bool Accepted { get; set; } [ForeignKey("Event")] public int EventId { get; set; } public Event Event { get; set; } [ForeignKey("Eventee")] public int EventeeId { get; set; } public Eventee Eventee { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assets.Scripts.RobinsonCrusoe_Game.GameAttributes.Inventions_and_Terrain { public static class InventionStorage { private static Dictionary<Invention, bool> AvailableInventions; public static void CreateStorageSpace() { AvailableInventions = new Dictionary<Invention, bool>(); //Add all possible inventions to dictionary AvailableInventions.Add(Invention.Basket, false); AvailableInventions.Add(Invention.Bed, false); AvailableInventions.Add(Invention.Belt, false); AvailableInventions.Add(Invention.Bow, false); AvailableInventions.Add(Invention.Cellar, false); AvailableInventions.Add(Invention.Corral, false); AvailableInventions.Add(Invention.Diary, false); AvailableInventions.Add(Invention.Drums, false); AvailableInventions.Add(Invention.Fireplace, false); AvailableInventions.Add(Invention.Furnance, false); AvailableInventions.Add(Invention.Lantern, false); AvailableInventions.Add(Invention.Moat, false); AvailableInventions.Add(Invention.Pit, false); AvailableInventions.Add(Invention.Raft, false); AvailableInventions.Add(Invention.Sack, false); AvailableInventions.Add(Invention.Shield, false); AvailableInventions.Add(Invention.Shortcut, false); AvailableInventions.Add(Invention.Sling, false); AvailableInventions.Add(Invention.Snare, false); AvailableInventions.Add(Invention.Spear, false); AvailableInventions.Add(Invention.Wall, false); //Start Items AvailableInventions.Add(Invention.Knife, false); AvailableInventions.Add(Invention.Cure, false); AvailableInventions.Add(Invention.Dam, false); AvailableInventions.Add(Invention.Fire, false); AvailableInventions.Add(Invention.Map, false); AvailableInventions.Add(Invention.Pot, false); AvailableInventions.Add(Invention.Rope, false); AvailableInventions.Add(Invention.Shovel, false); AvailableInventions.Add(Invention.Brick, false); } public static void UnlockInvention(Invention invention) { AvailableInventions[invention] = true; } public static void LockInvention(Invention invention) { AvailableInventions[invention] = false; } public static bool IsAvailable(Invention invention) { return AvailableInventions[invention]; } } public enum Invention { Basket, Bed, Belt, Bow, Cellar, Corral, Diary, Drums, Fireplace, Furnance, Lantern, Moat, Pit, Raft, Sack, Shield, Shortcut, Sling, Snare, Spear, Wall, //Start Inventions: Knife, Cure, Dam, Fire, Map, Pot, Rope, Shovel, Brick, } }
/// <summary> /// Author: Joe Zachary /// Updated by: Jim de St. Germain /// /// Dates: (Original) 2012-ish /// (Updated for Core) 2020 /// /// Target: ASP Framework (and soon ASP CORE 3.1) /// /// This program is an example of how to create a GUI application for /// a spreadsheet project. /// /// It relies on a working Spreadsheet Panel class, but defines other /// GUI elements, such as the file menu (open and close operations). /// /// WARNING: with the current GUI designer, you will not be able to /// use the toolbox "Drag and Drop" to update this file. /// </summary> using System; using System.Windows.Forms; namespace SpreadsheetGUI { /// <summary> /// reworking the demo program skeleton /// </summary> class SpreadsheetApplicationContext : ApplicationContext { // Number of open forms private int formCount = 0; // Singleton ApplicationContext private static SpreadsheetApplicationContext appContext; /// <summary> /// Private constructor for singleton pattern /// </summary> private SpreadsheetApplicationContext() { } /// <summary> /// Returns the one DemoApplicationContext. /// </summary> public static SpreadsheetApplicationContext getAppContext() { if (appContext == null) { appContext = new SpreadsheetApplicationContext(); } return appContext; } /// <summary> /// Runs the form /// </summary> public void RunForm(Form form) { // One more form is running formCount++; // When this form closes, we want to find out form.FormClosed += (o, e) => { if (--formCount <= 0) ExitThread(); }; // Run the form form.Show(); } } class A6GUI { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Start an application context and run one form inside it SpreadsheetApplicationContext appContext = SpreadsheetApplicationContext.getAppContext(); appContext.RunForm(new SpreadsheetGUIForm()); Application.Run(appContext); } } }
using FileTransporter.FileSimpleSocket; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace FileTransporter.Panels { public partial class LoginPanel : UserControl { private TaskCompletionSource<ClientSocketHelper> tcsClient = new TaskCompletionSource<ClientSocketHelper>(); private TaskCompletionSource<ServerSocketHelper> tcsServer = new TaskCompletionSource<ServerSocketHelper>(); public LoginPanel() { if (Config.Instance.Login == null) { Config.Instance.Login = new LoginInfo(); } ViewModel = Config.Instance.Login; InitializeComponent(); DataContext = ViewModel; } public LoginInfo ViewModel { get; } public Task<ClientSocketHelper> WaitForClientOpenedAsync() { return tcsClient.Task; } public Task<ServerSocketHelper> WaitForServerOpenedAsync() { return tcsServer.Task; } private async void ClientButton_Click(object sender, RoutedEventArgs e) { (sender as Button).IsEnabled = false; Config.Instance.Save(); try { ClientSocketHelper helper = new ClientSocketHelper(); await helper.StartAsync(ViewModel.ClientConnectAddress, ViewModel.ClientPort, ViewModel.ClientPassword, ViewModel.ClientName); tcsClient.SetResult(helper); } catch (Exception ex) { await MainWindow.Current.ShowMessageAsync("连接失败:", ex); (sender as Button).IsEnabled = true; } } private async void ServerButton_Click(object sender, RoutedEventArgs e) { (sender as Button).IsEnabled = false; Config.Instance.Save(); try { ServerSocketHelper helper = new ServerSocketHelper(); helper.Start(ViewModel.ServerPort, ViewModel.ServerPassword); tcsServer.SetResult(helper); } catch (Exception ex) { await MainWindow.Current.ShowMessageAsync("启动失败:", ex); (sender as Button).IsEnabled = true; } } } }
using System.Threading.Tasks; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions; namespace Microsoft.Azure.Functions.Worker.Extensions.OpenApi.FunctionProviders { /// <summary> /// This represents the function provider entity for OpenAPI HTTP trigger that renders the Swagger document with the <see cref="AuthorizationLevel.User"/> access level. /// </summary> public class OpenApiTriggerRenderSwaggerDocumentFunctionProvider : IOpenApiTriggerRenderSwaggerDocumentFunctionProvider { private readonly IOpenApiTriggerFunction _function; /// <summary> /// Initializes a new instance of the <see cref="OpenApiTriggerRenderSwaggerDocumentFunctionProvider"/> class. /// </summary> /// <param name="function"><see cref="IOpenApiTriggerFunction"/> instance.</param> public OpenApiTriggerRenderSwaggerDocumentFunctionProvider(IOpenApiTriggerFunction function) { this._function = function.ThrowIfNullOrDefault(); } /// <inheritdoc/> [OpenApiIgnore] [Function(nameof(OpenApiTriggerRenderSwaggerDocumentFunctionProvider.RenderSwaggerDocument))] public async Task<HttpResponseData> RenderSwaggerDocument( [HttpTrigger(AuthorizationLevel.User, "GET", Route = "swagger.{extension}")] HttpRequestData req, string extension, FunctionContext ctx) { return await this._function.RenderSwaggerDocument(req, extension, ctx).ConfigureAwait(false); } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; using System.Collections; using System.Collections.Generic; namespace EnhancedEditor { /// <summary> /// <see cref="Tag"/>[] wrapper, used to reference multiple tags in a single group. /// <para/> /// Contains multiple utility methods to dynamically and safely manipulate its content. /// </summary> [Serializable] public class TagGroup : IEnumerable<Tag> { #region Global Members /// <summary> /// All <see cref="Tag"/> defined in this group. /// </summary> public Tag[] Tags = new Tag[] { }; /// <summary> /// Total amount of <see cref="Tag"/> defined in this group. /// </summary> public int Count { get { return Tags.Length; } } // ----------------------- /// <inheritdoc cref="TagGroup"/> public TagGroup() { } /// <param name="_tags">All <see cref="Tag"/> to encapsulate in this group.</param> /// <inheritdoc cref="TagGroup()"/> public TagGroup(Tag[] _tags) { Tags = _tags; } #endregion #region Operator public Tag this[int _index] { get => Tags[_index]; set => Tags[_index] = value; } #endregion #region IEnumerable public IEnumerator<Tag> GetEnumerator() { for (int i = 0; i < Count; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Management /// <summary> /// Adds a new <see cref="Tag"/> into this group. /// </summary> /// <param name="_tag">Tag to add.</param> public void AddTag(Tag _tag) { if (!Contains(_tag)) { ArrayUtility.Add(ref Tags, _tag); } } /// <summary> /// Removes a <see cref="Tag"/> from this group. /// </summary> /// <param name="_tag">Tag to remove.</param> public void RemoveTag(Tag _tag) { if (Contains(_tag, out int _index)) { ArrayUtility.RemoveAt(ref Tags, _index); } } /// <summary> /// Set the tags of this group. /// </summary> /// <param name="_group">Group to copy the tags from.</param> public void SetTags(TagGroup _group) { Tags = _group.Tags; } #endregion #region Utility [NonSerialized] private readonly List<TagData> data = new List<TagData>(); // ----------------------- /// <inheritdoc cref="Contains(Tag, out int)"/> public bool Contains(Tag _tag) { return ArrayUtility.Contains(Tags, _tag); } /// <summary> /// Does this group contain a specific tag? /// </summary> /// <param name="_tag"><see cref="Tag"/> to check presence in group.</param> /// <param name="_index">Index of the matching tag in group.</param> /// <returns>True if the group contains the specified tag, false otherwise.</returns> public bool Contains(Tag _tag, out int _index) { for (int _i = 0; _i < Tags.Length; _i++) { if (Tags[_i] == _tag) { _index = _i; return true; } } _index = -1; return false; } /// <summary> /// Get if this group contains all other tags. /// </summary> /// <param name="_tags">All tags to check.</param> /// <returns>True if this group contains all given tags, false otherwise.</returns> public bool ContainsAll(Tag[] _tags) { foreach (Tag _tag in _tags) { if (!Contains(_tag)) { return false; } } return true; } /// <summary> /// Does this group contain any tag in another group? /// </summary> /// <param name="_group">Group to check content.</param> /// <returns>True if this group contain any of the other group tag, false otherwise.</returns> public bool ContainsAny(TagGroup _group) { foreach (Tag _tag in _group.Tags) { if (Contains(_tag)) { return true; } } return false; } /// <summary> /// Get if this group contains all tags in another group. /// </summary> /// <param name="_group">Group to check the tags.</param> /// <returns>True if this group contains all tags of the other given group, false otherwise.</returns> public bool ContainsAll(TagGroup _group) { foreach (Tag _tag in _group.Tags) { if (!Contains(_tag)) { return false; } } return true; } /// <summary> /// Get all <see cref="TagData"/> referenced in this group (automatically cached and updated). /// </summary> /// <returns>All <see cref="TagData"/> referenced in this group (with null entries for each tag that could not be found). /// <br/> Using a <see cref="List{T}"/> allows to return a direct reference of the cached value instead of allocating a new array. /// Please copy its content to a new collection if you intend to modify it.</returns> public List<TagData> GetData() { data.Resize(Tags.Length); // Update data with all tag cached values. for (int _i = 0; _i < Count; _i++) { TagData _data = Tags[_i].GetData(); data[_i] = _data; } return data; } /// <summary> /// Sorts all tags in this group by their name. /// </summary> public void SortTagsByName() { Array.Sort(Tags, (a, b) => { return a.GetData().CompareNameTo(b.GetData()); }); } #endregion } }
using System; using System.Collections.Generic; using System.Data; using Ext.Net; using Ext.Net.Utilities; namespace Cool { public partial class Aspx_KilometrosRuta : System.Web.UI.Page { readonly UoMetodos _zMetodos = new UoMetodos(); private string _perfil = string.Empty; private string _usuario = string.Empty; protected void Page_Load(object sender, EventArgs e) { _perfil = Request.QueryString["param1"]; _usuario = Request.QueryString["param2"]; var zDtsCataloRutas = _zMetodos.ZMetConsultaClasificacionRuta(); z_str_ClasificacionRuta.DataSource = zDtsCataloRutas.Tables["CatalogRutas"]; try { switch (_perfil) { case "NISSAN_USUARIO": break; case "NISSAN_EJECUTIVO": break; case "NISSAN_USUARIO_REPORTES": break; default: Response.Redirect(@"~/AccesoNoAutorizado.html"); break; } } catch (Exception ex) { X.Msg.Show(new MessageBoxConfig { Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.ERROR, Title = "Error", Message = "No es posible conectarse al servidor, intente de nuevo" }); ResourceManager.AjaxSuccess = false; ResourceManager.AjaxErrorMessage = ex.Message; } } [DirectMethod] public string zMetConsultaKmRuta(string zparInicio, string zparFin, string zparClaveClasificacionRuta) { string z_varstrresultado = ""; try { var z_dtsKmRuta = _zMetodos.ZMetConsultaKmRuta(zparInicio, zparFin, zparClaveClasificacionRuta); if(!z_dtsKmRuta.IsNull()) { if (z_dtsKmRuta.Tables["KmRuta"].Rows.Count > 0) { if (z_dtsKmRuta.Tables["KmRuta"].Rows[0][1].ToString() != "SQL_ERROR") { z_strConsulta.DataSource = z_dtsKmRuta.Tables["KmRuta"]; z_strConsulta.DataBind(); var resultadoAnnio = new List<object>(); foreach (DataRow row in z_dtsKmRuta.Tables["KmRuta"].Rows) { var totalKilometros = 0; //foreach (var item in row.ItemArray) //{ for (var i = 3; i < 15; i++) { totalKilometros += ( DBNull.Value.Equals(row.ItemArray[i])) ? 0 : (int)row.ItemArray[i]; } resultadoAnnio.Add(new { Year = (string) row["Year"], Kilometros = totalKilometros }); // } } /* Chart1.RemoveAll(); z_str_grafiaAnnio.DataSource = resultadoAnnio; z_str_grafiaAnnio.DataBind();*/ z_varstrresultado = _zMetodos.JsonResulEjec(1, "SQL_OK", "Embarques", ""); } else { z_varstrresultado = _zMetodos.JsonResulEjec(0, "SQL_ERROR", "Embarques", "Error en ejecución SQL..."); } } else { z_varstrresultado = _zMetodos.JsonResulEjec(0, "SQL_VACIO", "Embarques", "Error en ejecución SQL..."); } } else { z_varstrresultado = _zMetodos.JsonResulEjec(0, "SQL_NULL", "Embarques", "Servidor de SQL no disponible..."); } } catch (Exception ex) { z_varstrresultado = _zMetodos.JsonResulEjec(0, "SQL_ERROR", "Embarques", "Error en ejecución SQL..."); } return z_varstrresultado; } } }
// Accord Imaging Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This file was contributed to the project by Diego Catalano, based // on the MATLAB implementation by Juan Manuel Perez Rua, distributed // under the BSD license. The original license terms are given below: // // Copyright © Juan Manuel Perez Rua, 2012 // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the distribution // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // namespace Accord.Imaging.Filters { using System.Collections.Generic; using System.Drawing.Imaging; using Accord.Imaging; using Accord.Imaging.Filters; /// <summary> /// White Patch filter for color normalization. /// </summary> /// /// <example> /// <code> /// Bitmap image = ... // Lena's famous picture /// /// // Create the White Patch filter /// var whitePatch = new WhitePatch(); /// /// // Apply the filter /// Bitmap result = grayWorld.Apply(image); /// /// // Show on the screen /// ImageBox.Show(result); /// </code> /// /// <para> /// The resulting image is shown below. </para> /// /// <img src="..\images\white-patch.png" /> /// </example> /// public class WhitePatch : BaseInPlaceFilter { Dictionary<PixelFormat, PixelFormat> formatTranslations; /// <summary> /// Format translations dictionary. /// </summary> /// public override Dictionary<PixelFormat, PixelFormat> FormatTranslations { get { return formatTranslations; } } /// <summary> /// Initializes a new instance of the <see cref="WhitePatch"/> class. /// </summary> /// public WhitePatch() { formatTranslations = new Dictionary<PixelFormat, PixelFormat>(); formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb; formatTranslations[PixelFormat.Format32bppArgb] = PixelFormat.Format32bppArgb; } /// <summary> /// Process the filter on the specified image. /// </summary> /// /// <param name="image">Source image data.</param> /// protected unsafe override void ProcessFilter(UnmanagedImage image) { int width = image.Width; int height = image.Height; int pixelSize = System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8; int stride = image.Stride; int offset = stride - image.Width * pixelSize; byte* src = (byte*)image.ImageData.ToPointer(); // Get maximum color image values int maxR = 0, maxG = 0, maxB = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (src[RGB.R] > maxR) maxR = src[RGB.R]; if (src[RGB.G] > maxG) maxG = src[RGB.G]; if (src[RGB.B] > maxB) maxB = src[RGB.B]; } } double kr = maxR > 0 ? (255.0 / maxR) : 0; double kg = maxG > 0 ? (255.0 / maxG) : 0; double kb = maxB > 0 ? (255.0 / maxB) : 0; src = (byte*)image.ImageData.ToPointer(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, src += pixelSize) { double r = kr * src[RGB.R]; double g = kg * src[RGB.G]; double b = kb * src[RGB.B]; src[RGB.R] = (byte)(r > 255 ? 255 : r); src[RGB.G] = (byte)(g > 255 ? 255 : g); src[RGB.B] = (byte)(b > 255 ? 255 : b); } src += offset; } } } }
using System; namespace Shango.Commands { using System.IO; using ConsoleProcessRedirection; using Shango.CommandProcessor; /// <summary> /// Summary description for CurrentDirCommand. /// </summary> public class CurrentDirCommand : MultiInstanceCommand { public CurrentDirCommand( ICommandProcessor ParentCommandProcessor, ITerminal Terminal ) : base ( ParentCommandProcessor, Terminal ) { } public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; string Output = Directory.GetCurrentDirectory() + "\n"; TermUtil.WriteText( _Terminal, Output ); return 0; } } }
using UnityEngine; using System.Collections; using Random = UnityEngine.Random; public class Wall : MonoBehaviour { public Sprite dmgSprite; public int hp = 3; public GameObject[] foodTiles; private SpriteRenderer spriteRenderer; void Awake() { spriteRenderer = GetComponent<SpriteRenderer>(); } /// <summary> /// Manage the damage that the wall can afford until destroy it /// </summary> /// <param name="loss"> Amount of damage </param> public void DamageWall(int loss) { spriteRenderer.sprite = dmgSprite; hp -= loss; if (hp <= 0) { /*if (Random.Range(0, 5) == 1) { GameObject food = foodTiles[Random.Range(0, foodTiles.Length)]; GameManager.instance.InstanceTile(transform.position, food, transform.parent); }*/ gameObject.SetActive(false); } } }
using DFe.Classes.Flags; using NFe.Classes.Informacoes.Detalhe; using NFe.Classes.Informacoes.Detalhe.Tributacao; using NFe.Classes.Informacoes.Detalhe.Tributacao.Estadual; using NFe.Classes.Informacoes.Detalhe.Tributacao.Federal; using NFe.Classes.Informacoes.Emitente; using PDV.CONTROLER.Funcoes; using PDV.CONTROLLER.FISCAL.Base.NFCe; using PDV.CONTROLLER.NFCE.Util; using PDV.DAO.Entidades; using PDV.DAO.Entidades.PDV; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.VIEW.FRENTECAIXA.MFe { public static class ImpostoProdutoMFe { public static det GetDetalhe(DAO.Entidades.PDV.Venda VENDA , ItemVenda Item, int i, CRT crt, ModeloDocumento modelo, Emitente EMITENTE) { List<TributoNFCe> ListaDeTributos = new List<TributoNFCe>(); Produto _Produto = FuncoesProduto.GetProduto(Item.IDProduto); _Produto.EAN = _Produto.EAN; Ncm NcmVigente = FuncoesNcm.GetItemTributoVigente(FuncoesNcm.GetNCM(_Produto.IDNCM).Codigo, string.IsNullOrEmpty(_Produto.EXTipi) ? null : (decimal?)Convert.ToDecimal(_Produto.EXTipi), VENDA.DataCadastro); if (NcmVigente == null) { throw new Exception(string.Format("O produto \"{0}\" não possui tributação vigênte. Verifique o cadastro do IBPT e tente novamente.", _Produto.Descricao)); } decimal ValorTributosNacional = (_Produto.ValorVenda * (NcmVigente.NacionalFederal / 100)) * Item.Quantidade; decimal ValorTributosEstadual = (_Produto.ValorVenda * (NcmVigente.Estadual / 100)) * Item.Quantidade; decimal ValorTributosMunicipal = (_Produto.ValorVenda * (NcmVigente.Municipal / 100)) * Item.Quantidade; ListaDeTributos.Add(new TributoNFCe() { IDProduto = _Produto.IDProduto, PercentualEstadual = ValorTributosEstadual, PercentualFederal = ValorTributosNacional, PercentualMunicipal = ValorTributosMunicipal, NCM = NcmVigente }); if (!_Produto.IDIntegracaoFiscalNFCe.HasValue) { throw new Exception("Produto sem Integração Fiscal NFC-e configurada. Verifique e tente novamente."); } IntegracaoFiscal Integ = FuncoesIntegracaoFiscal.GetIntegracao(_Produto.IDIntegracaoFiscalNFCe.Value); decimal BaseCalculo = (Item.Subtotal - Item.DescontoValor); prod Prod = Produtos.GetProduto(_Produto.Descricao, _Produto.IDProduto, _Produto.EAN, FuncoesNcm.GetNCM(_Produto.IDNCM).Codigo.ToString(), Convert.ToInt32(FuncoesCFOP.GetCFOP(FuncoesIntegracaoFiscal.GetIntegracao(_Produto.IDIntegracaoFiscalNFCe.Value).IDCFOP).Codigo), FuncoesUnidadeMedida.GetUnidadeMedida(_Produto.IDUnidadeDeMedida).Sigla, Item.Quantidade, Item.ValorUnitarioItem, Item.DescontoValor, _Produto.CEST, _Produto.EXTipi); det Det = Detalhe.GetDetalhe(Prod, new imposto { vTotTrib = ValorTributosNacional + ValorTributosEstadual + ValorTributosMunicipal, //ICMSUFDest = new ICMSUFDest() //{ // pFCPUFDest = 0, // pICMSInter = 0, // pICMSInterPart = 0, // pICMSUFDest = 0, // vBCUFDest = 0, // vFCPUFDest = 0, // vICMSUFDest = 0, // vICMSUFRemet = 0 //}, ICMS = new ICMS { TipoICMS = Imposto.GetICMS(Convert.ToInt32(FuncoesCst.GetCSTIcmsPorID(Integ.IDCSTIcms).CSTCSOSN), Convert.ToInt32(FuncoesOrigemProduto.GetOrigemProduto(_Produto.IDOrigemProduto).Codigo), BaseCalculo, Integ.ICMS == 0 ? 0 : (Integ.ICMS_CDIFERENCIADO == 1 ? FuncoesUF.GetUnidadesFederativaComAliquotasICMS(EMITENTE.IDEmitente).AliquotaIntra : Integ.ICMS_DIFERENCIADO), Integ.ICMS_RED == 1 ? _Produto.Trib_RedBCICMS : 0, Integ.ICMS_DIF == 1 ? _Produto.Trib_AliqICMSDif : 0) } }, ValorTributosNacional, ValorTributosEstadual, ValorTributosMunicipal, NcmVigente.Chave, i + 1); // Det.imposto.ICMSUFDest.pICMSInter = 0; // Det.imposto.ICMSUFDest.pICMSInterPart = 0; switch (crt) { case CRT.RegimeNormal: case CRT.SimplesNacionalExcessoSublimite: Det.imposto.COFINS = new COFINS { TipoCOFINS = Imposto.GetCofins(Convert.ToInt32(FuncoesCst.GetCSTCofins(Integ.IDCSTCofins).CST), BaseCalculo, _Produto.Trib_AliqCOFINS) }; Det.imposto.PIS = new PIS { TipoPIS = Imposto.GetPis(Convert.ToInt32(FuncoesCst.GetCSTCofins(Integ.IDCSTPis).CST), BaseCalculo, _Produto.Trib_AliqPIS) }; // IPI Não Envia na NFC-e break; } return Det; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Migration_0_CreateRawQueue.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Telemetry.StorageModel { using System; using FluentMigrator; /// <summary> /// The migration that adds the diagnostics tables. /// </summary> [Migration(MigrationVersion.CreateRawQueueSchema, TransactionBehavior.None)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Improves readability.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Spelling/name is correct.")] public class Migration_0_CreateRawQueue : Migration { /// <inheritdoc /> public override void Up() { this.Create.Table(RawQueueSchema.TableName) .WithColumn(RawQueueSchema.Id).AsGuid().PrimaryKey().NotNullable() .WithColumn(RawQueueSchema.SampledUtc).AsDateTime().NotNullable() .WithColumn(RawQueueSchema.TelemetryObjectDescribedSerializationJson).AsString(int.MaxValue).NotNullable() .WithColumn(RawQueueSchema.LogItemKindJson).AsString(int.MaxValue).NotNullable() .WithColumn(RawQueueSchema.LogItemContextJson).AsString(int.MaxValue).NotNullable() .WithColumn(RawQueueSchema.LogItemCorrelationsJson).AsString(int.MaxValue).NotNullable() .WithColumn(RawQueueSchema.RowCreatedUtc).AsDateTime().NotNullable().WithDefault(SystemMethods.CurrentUTCDateTime); } /// <inheritdoc /> public override void Down() { throw new NotImplementedException("Down migration not supported for this schema"); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework.Input; namespace InputHandlers.Keyboard { internal class KeyDelta { private readonly IList<Keys> _unmanagedKeys; private Keys[] _lastKeyList; private Keys[] _newKeyList; private bool _requiresUpdate; public Keys FocusKey { get; private set; } public bool TreatModifiersAsKeys { get; set; } public KeyboardModifier LastModifiers { get; private set; } public Keys[] NewKeyList { get { return _newKeyList; } } public IList<Keys> NewKeyDelta { get; private set; } public KeyboardModifier NewModifiers { get; private set; } public KeyDelta(IList<Keys> unmanagedKeys) { _lastKeyList = new Keys[0]; _newKeyList = new Keys[0]; NewKeyDelta = new List<Keys>(); FocusKey = Keys.None; TreatModifiersAsKeys = false; _unmanagedKeys = unmanagedKeys; } public void Stop() { _requiresUpdate = false; } public void Update(KeyboardState currentKeyboardState) { if (_requiresUpdate) { _lastKeyList = _newKeyList; _newKeyList = currentKeyboardState.GetPressedKeys(); StripUnmanagedKeys(ref _newKeyList); if (!TreatModifiersAsKeys) { LastModifiers = NewModifiers; NewModifiers = _newKeyList.GetModifiers(); StripModifiers(ref _newKeyList); } NewKeyDelta = _newKeyList.Except(_lastKeyList).ToList(); if (NewKeyDelta.Any()) FocusKey = NewKeyDelta.First(); else if (_lastKeyList.Except(_newKeyList).Any()) FocusKey = Keys.None; } } public void Start(KeyboardState currentKeyboardState) { _requiresUpdate = true; _lastKeyList = currentKeyboardState.GetPressedKeys(); StripUnmanagedKeys(ref _lastKeyList); if (!TreatModifiersAsKeys) { LastModifiers = _lastKeyList.GetModifiers(); StripModifiers(ref _lastKeyList); } NewKeyDelta.Clear(); FocusKey = Keys.None; } public bool AreKeysLost { get { return _newKeyList.Length < _lastKeyList.Length; } } public bool HasNoAddedKeys { get { return !NewKeyDelta.Any(); } } public bool HasAddedKeys { get { return NewKeyDelta.Any(); } } public bool HasNoKeysPressed { get { return !_newKeyList.Any(); } } private bool IsUnmanagedKey(Keys key) { return _unmanagedKeys.Contains(key); } private void StripUnmanagedKeys(ref Keys[] keyList) { if (!_unmanagedKeys.Any()) return; var keyListUpdateIndex = 0; StripKeys(key => !IsUnmanagedKey(key), ref keyList, keyListUpdateIndex); } private void StripModifiers(ref Keys[] keyList) { var keyListUpdateIndex = 0; StripKeys(key => !key.IsModifierKey(), ref keyList, keyListUpdateIndex); } private void StripKeys(Func<Keys, bool> keepKeyFunc, ref Keys[] keyList, int keyListUpdateIndex) { int keyListIndex; for (keyListIndex = 0; keyListIndex < keyList.Length; keyListIndex++) { if (keepKeyFunc(keyList[keyListIndex])) { keyList[keyListUpdateIndex] = keyList[keyListIndex]; keyListUpdateIndex++; } } if (keyListUpdateIndex < keyList.Length) { keyList = keyList.Take(keyListUpdateIndex).ToArray(); } } } }
namespace UserVoiceSystem.Web.ViewModels.Comments { using System.Collections.Generic; public class CommentsListViewModel { public IEnumerable<CommentGetViewModel> Comments { get; set; } public int? TotalPages { get; set; } public int? CurrentPage { get; set; } public string Url { get; set; } } }
using UnityEngine; public enum ITEM_TYPE { UNKNOWN = 0, WEAPON = 1, ARMOR = 2, USABLE = 3 }; public enum ARMOR_SLOT { UNKNOWN = 0, HEAD = 1, ARMS = 2, BODY = 3, LEGS = 4, FEET = 5 }; public class Item { public ITEM_TYPE ItemType { get; set; } //Identifies the type of item it is in a more general sense. public int ID { get; set; } //Uniquely identifies the type of this item. public string Name { get; set; } //The name of the item. public string Slug { get; set; } //The name with underscores. public string Description { get; set; } //A description of the item that better explains what it is. public int Rarity { get; set; } //Rarity of the item: 0 = junk, 1 = common, 2 = uncommon, 3 = rare, 4 = epic, 5 = legendary. public int Value { get; set; } //Monetary value of the item. public bool Stackable { get; set; } //Can this item be stacked with items of the same type. public int StackLimit { get; set; } //If this item is stackable, then this variable will set a limit to the amount of items that can be stacked. If not stackable, this variable matters not. public Sprite Sprite { get; set; } //Image that represents the item. public Item() { this.ItemType = ITEM_TYPE.UNKNOWN; this.ID = -1; this.Name = "Default Name"; this.Slug = "default_slug"; this.Description = "Default Description"; this.Rarity = -1; this.Value = -1; this.Stackable = false; this.StackLimit = -1; this.Sprite = Resources.Load<Sprite>("Sprites/Items/" + Slug); } public Item(ITEM_TYPE itemType, int id, string name, string slug, string description, int rarity, int value, bool stackable, int stackLimit) { this.ItemType = itemType; this.ID = id; this.Name = name; this.Slug = slug; this.Description = description; this.Rarity = rarity; this.Value = value; this.Stackable = stackable; this.StackLimit = stackLimit; this.Sprite = Resources.Load<Sprite>("Sprites/Items/" + Slug); } } public class ItemWeapon : Item { public int Damage; public ItemWeapon() : base() { this.Damage = 0; } public ItemWeapon(ITEM_TYPE itemType, int id, string name, string slug, string description, int rarity, int value, bool stackable, int stackLimit, int damage) : base(itemType, id, name, slug, description, rarity, value, stackable, stackLimit) { this.Damage = damage; } } public class ItemArmor : Item { public int Armor; public ARMOR_SLOT ArmorSlot; public ItemArmor() : base() { this.Armor = 0; this.ArmorSlot = ARMOR_SLOT.UNKNOWN; } public ItemArmor(ITEM_TYPE itemType, int id, string name, string slug, string description, int rarity, int value, bool stackable, int stackLimit, int armor, ARMOR_SLOT armorSlot) : base(itemType, id, name, slug, description, rarity, value, stackable, stackLimit) { this.Armor = armor; this.ArmorSlot = armorSlot; } }
namespace AjLisp.Primitives { using System; using System.Collections.Generic; using System.Text; using AjLisp.Language; public abstract class FSubr : IFunction { public abstract object Execute(List arguments, ValueEnvironment environment); public object Apply(List arguments, ValueEnvironment environment) { return this.Execute(arguments, environment); } } }
using Sitecore.XConnect; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace XcExport.Cortex.Workers { public class ExportContactsToMsSql : Sitecore.Processing.Engine.Abstractions.IDistributedWorker<Sitecore.XConnect.Contact> { private readonly Sitecore.XConnect.IXdbContext _xdbContext; public ExportContactsToMsSql(Sitecore.XConnect.IXdbContext xdbContext, IReadOnlyDictionary<string, string> options) { _xdbContext = xdbContext; } public void Dispose() => _xdbContext.Dispose(); public async Task ProcessBatchAsync(IReadOnlyList<Contact> batch, CancellationToken token) { var contacts = new List<MsSqlStorage.Model.ContactEntity>(); // Selected data is alrteady in batch collection foreach (var contact in batch) { var contactEmails = contact.GetFacet<Sitecore.XConnect.Collection.Model.EmailAddressList>(); var contactPersonalInformation = contact.GetFacet<Sitecore.XConnect.Collection.Model.PersonalInformation>(); var c = new MsSqlStorage.Model.ContactEntity() { Email = contactEmails == null ? "N/A" : contactEmails.PreferredEmail.SmtpAddress, ContactId = contact.Id, FirstName = contactPersonalInformation == null ? "N/A" : contactPersonalInformation.FirstName, LastName = contactPersonalInformation == null ? "N/A" : contactPersonalInformation.LastName, Interactions = new List<MsSqlStorage.Model.InteractionEntity>() }; var interactions = contact.Interactions; foreach (var interaction in interactions) { var ipAddress = interaction.GetFacet<Sitecore.XConnect.Collection.Model.IpInfo>(); c.Interactions.Add( new MsSqlStorage.Model.InteractionEntity( string.IsNullOrEmpty(interaction.UserAgent) ? string.Empty : interaction.UserAgent, interaction.Duration, interaction.Id, interaction.Contact.Id, interaction.StartDateTime, ipAddress == null || string.IsNullOrEmpty(ipAddress.IpAddress) ? string.Empty : ipAddress.IpAddress, ipAddress == null || string.IsNullOrEmpty(ipAddress.City) ? string.Empty : ipAddress.City ) ); } contacts.Add(c); } Storage.MsSqlStorage.WriteContacts(contacts); await Task.FromResult(1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using ItlaSocial.Models; namespace ItlaSocial.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<ProfilePhoto> ProfilePhotos { get; set; } public DbSet<Friendship> Friendships { get; set; } public DbSet<Publication> Publications { get; set; } public DbSet<PublicationLike> PublicationLikes { get; set; } public DbSet<PublicationMedia> PublicationMedias { get; set; } public DbSet<Comment> Comments { get; set; } public DbSet<CommentLike> CommentLikes { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } public DbSet<ItlaSocial.Models.ApplicationUser> ApplicationUser { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HCL.Academy.Model { public class TrainingCompletionRequest:RequestBase { public List<string> trainingDetails { get; set; } public string AdminApprovalStatus { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace Planning { static class ExternalPlanners { public static List<string> FFPlan(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; MemoryStream msDomain = d.WriteSimpleDomain(); MemoryStream problem_M_S = p.WriteSimpleProblem(curentState); //StreamWriter swDomainFile = new StreamWriter(@"D:\Dropbox-users\shanigu\Dropbox\Dropbox\privacyPreserving\Competition\all\factored\testd.pddl"); // StreamReader srDomain = new StreamReader(msDomain); // swDomainFile.Write(srDomain.ReadToEnd()); // swDomainFile.Close(); // StreamWriter swProblemFile = new StreamWriter(@"D:\Dropbox-users\shanigu\Dropbox\Dropbox\privacyPreserving\Competition\all\factored\testp.pddl"); // StreamReader srProblem = new StreamReader(problem_M_S); // swProblemFile.Write(srProblem.ReadToEnd()); // swProblemFile.Close(); problem_M_S.Position = 0; msDomain.Position = 0; Process planer = new Process(); //planer.StartInfo.WorkingDirectory = @"C:\project\Planning 2 new\PDDLTEST\temp"; planer.StartInfo.FileName = "ff.exe"; //planer.StartInfo.Arguments += "-o dT.pddl -f pT.pddl"; FFOutput = ""; planer.StartInfo.UseShellExecute = false; planer.StartInfo.RedirectStandardInput = true; planer.StartInfo.RedirectStandardOutput = true; planer.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); planer.Start(); planer.BeginOutputReadLine(); StreamReader srOps = new StreamReader(msDomain); string domain = srOps.ReadToEnd(); planer.StandardInput.Write(domain); srOps.Close(); BinaryWriter b = new BinaryWriter(planer.StandardInput.BaseStream); b.Write('\0'); StreamReader srFct = new StreamReader(problem_M_S); string problem = srFct.ReadToEnd(); planer.StandardInput.Write(problem); srFct.Close(); b.Write('\0'); //planer.StandardInput.Flush(); planer.StandardInput.Close(); if (cMaxMilliseconds != -1) { if (!planer.WaitForExit(cMaxMilliseconds))//2 minutes max { planer.Kill(); bUnsolvable = false; return null; } } else planer.WaitForExit(); planer.Close(); //string sOutput = planer.StandardOutput.ReadToEnd(); Thread.Sleep(10); // Console.Write("*"); string sOutput = FFOutput; //throw new NotImplementedException(); //Console.WriteLine(sOutput); MemoryStream planMs = new MemoryStream(); if (sOutput.Contains("found legal plan as follows")) { string sPlan = sOutput.Substring(sOutput.IndexOf("found legal plan as follows")); sPlan = sPlan.Replace("found legal plan as follows", "").Trim(); string[] asPlan = sPlan.Split('\n'); string sFinalPlan = ""; for (int i = 0; i < asPlan.Length; i++) { if (!asPlan[i].Contains(":")) break; if (asPlan[i].Contains("time spent:")) break; sFinalPlan += asPlan[i].Substring(asPlan[i].IndexOf(':') + 2).Trim() + "\n"; } StreamWriter sw = new StreamWriter(planMs); sw.WriteLine(sFinalPlan); sw.Close(); bUnsolvable = false; } else { if (sOutput.Contains("goal can be simplified to TRUE")) { ffLplan = new List<string>(); bUnsolvable = false; return ffLplan; } else if (sOutput.Contains("goal can be simplified to FALSE")) { ffLplan = null; bUnsolvable = true; return null; } else { ffLplan = null; bUnsolvable = false; return null; } } lPlan = ReadPlan(new MemoryStream(planMs.ToArray())); ffLplan = lPlan; return lPlan; } public static List<string> PdbFFPlan(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; MemoryStream msDomain = d.WriteSimpleDomain(); MemoryStream problem_M_S = p.WriteSimpleProblem(curentState); //StreamWriter swDomainFile = new StreamWriter(@"D:\Dropbox-users\shanigu\Dropbox\Dropbox\privacyPreserving\Competition\all\factored\testd.pddl"); // StreamReader srDomain = new StreamReader(msDomain); // swDomainFile.Write(srDomain.ReadToEnd()); // swDomainFile.Close(); // StreamWriter swProblemFile = new StreamWriter(@"D:\Dropbox-users\shanigu\Dropbox\Dropbox\privacyPreserving\Competition\all\factored\testp.pddl"); // StreamReader srProblem = new StreamReader(problem_M_S); // swProblemFile.Write(srProblem.ReadToEnd()); // swProblemFile.Close(); problem_M_S.Position = 0; msDomain.Position = 0; Process planer = new Process(); //planer.StartInfo.WorkingDirectory = @"C:\project\Planning 2 new\PDDLTEST\temp"; planer.StartInfo.FileName = "ff.exe"; //planer.StartInfo.Arguments += "-o dT.pddl -f pT.pddl"; FFOutput = ""; planer.StartInfo.UseShellExecute = false; planer.StartInfo.RedirectStandardInput = true; planer.StartInfo.RedirectStandardOutput = true; planer.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); planer.Start(); planer.BeginOutputReadLine(); StreamReader srOps = new StreamReader(msDomain); string domain = srOps.ReadToEnd(); planer.StandardInput.Write(domain); srOps.Close(); BinaryWriter b = new BinaryWriter(planer.StandardInput.BaseStream); b.Write('\0'); StreamReader srFct = new StreamReader(problem_M_S); string problem = srFct.ReadToEnd(); planer.StandardInput.Write(problem); srFct.Close(); b.Write('\0'); //planer.StandardInput.Flush(); planer.StandardInput.Close(); if (cMaxMilliseconds != -1) { if (!planer.WaitForExit(cMaxMilliseconds))//2 minutes max { planer.Kill(); bUnsolvable = false; return null; } } else planer.WaitForExit(); planer.Close(); //string sOutput = planer.StandardOutput.ReadToEnd(); Thread.Sleep(50); string sOutput = FFOutput; //throw new NotImplementedException(); //Console.WriteLine(sOutput); MemoryStream planMs = new MemoryStream(); if (sOutput.Contains("found legal plan as follows")) { string sPlan = sOutput.Substring(sOutput.IndexOf("found legal plan as follows")); sPlan = sPlan.Replace("found legal plan as follows", "").Trim(); string[] asPlan = sPlan.Split('\n'); string sFinalPlan = ""; for (int i = 0; i < asPlan.Length; i++) { if (!asPlan[i].Contains(":")) break; if (asPlan[i].Contains("time spent:")) break; sFinalPlan += asPlan[i].Substring(asPlan[i].IndexOf(':') + 2).Trim() + "\n"; } StreamWriter sw = new StreamWriter(planMs); sw.WriteLine(sFinalPlan); sw.Close(); bUnsolvable = false; } else { if (sOutput.Contains("goal can be simplified to TRUE")) { ffLplan = new List<string>(); bUnsolvable = false; return ffLplan; } else if (sOutput.Contains("goal can be simplified to FALSE")) { ffLplan = null; bUnsolvable = true; return null; } else { ffLplan = null; bUnsolvable = false; return null; } } lPlan = ReadPlan(new MemoryStream(planMs.ToArray())); ffLplan = lPlan; return lPlan; } static string FFOutput = ""; private static void FFOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { if (!String.IsNullOrEmpty(outLine.Data)) { FFOutput += outLine.Data + Environment.NewLine; } } private static string FDOutput; private static void FDOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { if (!String.IsNullOrEmpty(outLine.Data)) { FDOutput += outLine.Data + Environment.NewLine; } } public static bool RunProcess(Process p, int cMaxMilliseconds) { p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); p.Start(); p.BeginOutputReadLine(); //p.WaitForExit(); if (!p.WaitForExit(cMaxMilliseconds)) { p.Kill(); return false; } p.Close(); return true; } public static bool RunFD(string sPath, int cMaxMilliseconds) { Process p = new Process(); p.StartInfo.WorkingDirectory = sPath; //p.StartInfo.FileName = Program.BASE_PATH + @"\PDDL\Planners\ff.exe"; p.StartInfo.FileName = @"D:\cygwin\bin\bash.exe"; p.StartInfo.Arguments = @"D:\cygwin\home\shanigu\FastDownward\src\plan"; p.StartInfo.Arguments += @" dFD.pddl pFD.pddl"; p.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; //p.StartInfo.Arguments += " --heuristic \"hFF=ff(cost_type=1)\" " + // " --search \"lazy_greedy(hff, preferred=hff)\" "; if (!RunProcess(p, cMaxMilliseconds)) return false; return true; } public static List<string> FDPlan(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); File.Delete("plan.txt"); File.Delete("sas_plan"); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; MemoryStream msDomain = d.WriteSimpleDomain(); MemoryStream problem_M_S = p.WriteSimpleProblem(curentState); //for now, saving files in the working directory StreamWriter swDomainFile = new StreamWriter("dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter("pFD.pddl"); StreamReader srProblem = new StreamReader(problem_M_S); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); problem_M_S.Position = 0; msDomain.Position = 0; bUnsolvable = false; if (RunFD("./", cMaxMilliseconds)) return ReadPlan("./"); return null; } private static List<string> ReadPlan(string sPath) { List<string> lPlan = new List<string>(); string sPlanFile = "plan.txt"; if (File.Exists(sPath + sPlanFile)) { StreamReader sr = new StreamReader(sPath + sPlanFile); while (!sr.EndOfStream) { string sAction = sr.ReadLine().Trim().ToLower(); if (sAction != "") lPlan.Add(sAction); } sr.Close(); } else if (File.Exists(sPath + "mipsSolution.soln")) { StreamReader sr = new StreamReader(sPath + "mipsSolution.soln"); while (!sr.EndOfStream) { string sLine = sr.ReadLine().Trim().ToLower(); if (sLine.Count() > 0 && !sLine.StartsWith(";")) { int iStart = sLine.IndexOf("("); int iEnd = sLine.IndexOf(")"); sLine = sLine.Substring(iStart + 1, iEnd - iStart - 1).Trim(); lPlan.Add(sLine); } } sr.Close(); } else if (File.Exists(sPath + "sas_plan")) { StreamReader sr = new StreamReader(sPath + "sas_plan"); while (!sr.EndOfStream) { string sLine = sr.ReadLine().Trim().ToLower(); sLine = sLine.Replace("(", ""); sLine = sLine.Replace(")", ""); if (sLine.Count() > 0 && !sLine.StartsWith(";")) { int iStart = sLine.IndexOf("("); sLine = sLine.Substring(iStart + 1).Trim(); lPlan.Add(sLine); } } sr.Close(); } else { return null; } List<string> lFilteredPlan = new List<string>(); foreach (string sAction in lPlan) { if (sAction.Contains("-remove") || sAction.Contains("-translate")) continue; if (sAction.Contains("-add")) lFilteredPlan.Add(sAction.Replace("-add", "")); else lFilteredPlan.Add(sAction); } return lFilteredPlan; } public static List<string> ReadPlan(MemoryStream ms) { List<string> lPlan = new List<string>(); StreamReader sr = new StreamReader(ms); while (!sr.EndOfStream) { string sAction = sr.ReadLine().Trim().ToLower(); if (sAction != "") lPlan.Add(sAction); } sr.Close(); return lPlan; List<string> lFilteredPlan = new List<string>(); foreach (string sAction in lPlan) { if (sAction.Contains("-remove") || sAction.Contains("-translate")) continue; if (sAction.Contains("-add")) lFilteredPlan.Add(sAction.Replace("-add", "")); else lFilteredPlan.Add(sAction); } return lFilteredPlan; } public static List<string> ManualSolve(Problem p, Domain d) { List<string> lPlan = new List<string>(); State sStart = new State(p); foreach (GroundedPredicate gp in p.Known) sStart.AddPredicate(gp); State sCurrent = null, sNext = null; Dictionary<State, Action> dMapStateToGeneratingAction = new Dictionary<State, Action>(); dMapStateToGeneratingAction[sStart] = null; Dictionary<State, State> dParents = new Dictionary<State, State>(); dParents[sStart] = null; int cProcessed = 0; List<string> lActionNames = new List<string>(); sCurrent = sStart; while (!p.IsGoalState(sCurrent)) { List<Action> lActions = new List<Action>(d.GroundAllActions(sCurrent.Predicates, false)); Console.WriteLine("Available actions:"); for (int i = 0; i < lActions.Count; i++) { Console.WriteLine(i + ") " + lActions[i].Name); } Console.Write("Choose action number: "); int iAction = int.Parse(Console.ReadLine()); Action a = lActions[iAction]; sNext = sCurrent.Apply(a); lPlan.Add(a.Name); foreach (Predicate pNew in sNext.Predicates) if (!sCurrent.Predicates.Contains(pNew)) Console.WriteLine(pNew); if (!dParents.Keys.Contains(sNext)) { dParents[sNext] = sCurrent; dMapStateToGeneratingAction[sNext] = a; } sCurrent = sNext; cProcessed++; } return lPlan; //return GeneratePlan(sCurrent, null, dParents, dMapStateToGeneratingAction); } } }
using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Text; namespace Archivist.Models { public class ListItem { [BsonId, BsonElement("AdvertID")] public Guid ItemID { get; set; } [BsonElement("DayImage")] public byte[] Image { get; set; } [BsonElement("PublisherEmail")] public string PublisherEmail { get; set; } [BsonElement("Type")] public string Type { get; set; } [BsonElement("ItemName")] public string ItemName { get; set; } [BsonElement("Date")] public DateTime Date { get; set; } [BsonElement("Point")] public int Point { get; set; } [BsonElement("Description")] public string Description { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Windows; using AthleteBuilder.Model; using CsvHelper; using Microsoft.Win32; namespace AthleteBuilder { public partial class MainWindow : Window { public string FileName { get; private set; } public IList<Athlete> Athletes { get; } = new List<Athlete>(); public MainWindow() { InitializeComponent(); } private void OpenDialog(object sender, RoutedEventArgs e) { var openFileDialog = new OpenFileDialog { Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml" }; if (openFileDialog.ShowDialog() == true) { FileName = openFileDialog.FileName; } using var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var sr = new StreamReader(stream); using var csv = new CsvReader(sr, CultureInfo.InvariantCulture); csv.Configuration.PrepareHeaderForMatch = (header, index) => header.ToLower(); var record = new Record(); var records = csv.EnumerateRecords(record); foreach (var r in records) { var newAthlete = false; Athlete currentAthlete; if (!Athletes.Any(p => p.FirstName == r.FirstName && p.LastName == r.LastName)) { currentAthlete = new Athlete { BirthYear = r.BirthYear, Club = r.Club, FirstName = r.FirstName, LastName = r.LastName, Malus = r.Malus, Sexe = r.Sexe, }; newAthlete = true; } else { currentAthlete = Athletes.FirstOrDefault(p => p.FirstName == r.FirstName && p.LastName == r.LastName); } var rank = CalculateRank(r); if (currentAthlete == null) throw new Exception(); MapDisciplinePoint(r, currentAthlete, rank); if (newAthlete) Athletes.Add(currentAthlete); } foreach (var athlete in Athletes) { //TODO : Add malus (-10 pts) var champVsIndoor = new List<int> { athlete.ChampVsIndoor.FiftyMeterHurdlePoints, athlete.ChampVsIndoor.FiftyMeterPoints, athlete.ChampVsIndoor.HighJumpPoints, athlete.ChampVsIndoor.LongJumpPoints, athlete.ChampVsIndoor.PolePoints, athlete.ChampVsIndoor.ShotPutPoints }; athlete.ChampVsIndoor.ChampVsIndoorTotal = CalculateMax4Discipline(champVsIndoor); var champVsOutdoor = new List<int> { athlete.ChampVsOutdoor.HighJumpPoints, athlete.ChampVsOutdoor.PolePoints, athlete.ChampVsOutdoor.LongJumpPoints, athlete.ChampVsOutdoor.DiscusPoints, athlete.ChampVsOutdoor.EighthyMeterPoints, athlete.ChampVsOutdoor.HundredMeterHurdlePoints, athlete.ChampVsOutdoor.JavelinPoints, athlete.ChampVsOutdoor.ShotPutPoints, athlete.ChampVsOutdoor.SixHundredMeterPoints, athlete.ChampVsOutdoor.TwoThousandMeterPoints }; athlete.ChampVsOutdoor.ChampVsOutdoorTotal = CalculateMax4Discipline(champVsOutdoor); } lvUsers.ItemsSource = Athletes.OrderByDescending(p => p.ChampVsIndoor.ChampVsIndoorTotal); } private static int CalculateMax4Discipline(IEnumerable<int> allPoints) { return allPoints.OrderByDescending(p => p).Take(4).Sum(); } private int CalculateRank(Record r) { return r.Discipline switch { 201 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsIndoor.FiftyMeterPoints > 0), 202 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsIndoor.FiftyMeterHurdlePoints > 0), 203 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsIndoor.HighJumpPoints > 0), 204 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsIndoor.LongJumpPoints > 0), 205 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsIndoor.ShotPutPoints > 0), 206 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsIndoor.PolePoints > 0), 100 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsMultiple.ChampVsMultipleTotal > 0), 300 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.TourneeCross.TourneeCrossTotal > 0), 400 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.FinaleSprint.FinaleSprintTotal > 0), 500 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.FinaleGruyere.FinaleGruyereTotal > 0), 601 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.EighthyMeterPoints > 0), 602 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.HundredMeterHurdlePoints > 0), 603 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.SixHundredMeterPoints > 0), 604 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.TwoThousandMeterPoints > 0), 605 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.HighJumpPoints > 0), 606 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.PolePoints > 0), 607 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.LongJumpPoints > 0), 608 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.ShotPutPoints > 0), 609 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.JavelinPoints > 0), 610 => Athletes.Count(p => p.BirthYear == r.BirthYear && p.ChampVsOutdoor.DiscusPoints > 0), _ => 0 }; } private static void MapDisciplinePoint(Record record, Athlete currentAthlete, int rank) { switch (record.Discipline) { case 100: currentAthlete.ChampVsMultiple.ChampVsMultipleTotal = currentAthlete.ChampVsMultiple.MaxPoints - rank; break; case 201: currentAthlete.ChampVsIndoor.FiftyMeterPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 202: currentAthlete.ChampVsIndoor.FiftyMeterHurdlePoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 203: currentAthlete.ChampVsIndoor.HighJumpPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 204: currentAthlete.ChampVsIndoor.LongJumpPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 205: currentAthlete.ChampVsIndoor.ShotPutPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 206: currentAthlete.ChampVsIndoor.PolePoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 300: currentAthlete.TourneeCross.TourneeCrossTotal = currentAthlete.TourneeCross.MaxPoints - rank; break; case 400: currentAthlete.FinaleSprint.FinaleSprintTotal = currentAthlete.FinaleSprint.MaxPoints - rank; break; case 500: currentAthlete.FinaleGruyere.FinaleGruyereTotal = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 601: currentAthlete.ChampVsOutdoor.EighthyMeterPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 602: currentAthlete.ChampVsOutdoor.HundredMeterHurdlePoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 603: currentAthlete.ChampVsOutdoor.SixHundredMeterPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 604: currentAthlete.ChampVsOutdoor.TwoThousandMeterPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 605: currentAthlete.ChampVsOutdoor.HighJumpPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 606: currentAthlete.ChampVsOutdoor.PolePoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 607: currentAthlete.ChampVsOutdoor.LongJumpPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 608: currentAthlete.ChampVsOutdoor.ShotPutPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 609: currentAthlete.ChampVsOutdoor.JavelinPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; case 610: currentAthlete.ChampVsOutdoor.DiscusPoints = currentAthlete.ChampVsIndoor.MaxPoints - rank; break; } } private void ExportCsv(object sender, RoutedEventArgs e) { using var writer = new StreamWriter(@"C:\temp\athlete.csv"); using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture); csv.WriteRecords(Athletes); writer.Flush(); MessageBox.Show("Exported as CSV"); } } }
using HashCodeEqualsPersonalizado.Entidades; using System; namespace HashCodeEqualsPersonalizado { class Program { static void Main(string[] args) { Cliente a = new Cliente("Mateus", "m@email.com"); Cliente a2 = new Cliente("Mateus", "m@email.com"); Cliente b = new Cliente("Altair", "a@email.com"); Console.WriteLine(a.Equals(a2)); Console.WriteLine(a.GetHashCode()); Console.WriteLine(b.GetHashCode()); if (a.GetHashCode() == b.GetHashCode()) { Console.WriteLine("IGUAIS"); } else { Console.WriteLine("DIFERENTES"); } if (a.GetHashCode() == a2.GetHashCode()) { Console.WriteLine("IGUAIS"); } else { Console.WriteLine("DIFERENTES"); } } } }
using System; using System.Collections.Generic; using System.Text; using Telegram.Bot; using Telegram.Bot.Types; namespace EchoBotForTest.Command.Commands { class Bullshit : EchoBotForTest.Commands.Command { public override string[] Names { get; set; } = {"Ай фак ю буллщит", "Ай фак ю булщит"}; public override async void Execute(Message message, TelegramBotClient client) { await client.SendTextMessageAsync(message.Chat, "щит"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TradingCompany.Contracts; using TradingCompany.Logic.Entities; namespace TradingCompany.Logic.DataContext { public interface IContext : IDisposable { Task<int> CountAsync<I, E>() where I : IIdentifiable where E : IdentityObject, I; Task<E> CreateAsync<I, E>() where I : IIdentifiable where E : IdentityObject, ICopyable<I>, I, new(); Task<E> InsertAsync<I, E>(E entity) where I : IIdentifiable where E : IdentityObject, ICopyable<I>, I, new(); Task<E> UpdateAsync<I, E>(E entity) where I : IIdentifiable where E : IdentityObject, ICopyable<I>, I, new(); Task<E> DeleteAsync<I, E>(int id) where I : IIdentifiable where E : IdentityObject, I; Task SaveAsync(); } }
using CheckMySymptoms.Forms.View.Common; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace CheckMySymptoms.Forms.View.Input { public class InputFormView : ViewBase, IValidatableObject { #region Constants #endregion Constants #region FormData public string Title { get; set; } public Dictionary<string, Dictionary<string, string>> ValidationMessages { get; set; } public Dictionary<string, List<DirectiveView>> ConditionalDirectives { get; set; } public string Icon { get; set; } #endregion FormData public ICollection<InputRowView> Rows { get; set; } public override void UpdateFields(object fields) { if (!(fields is object[] list)) return; this.UpdateAllQuestions(list.Aggregate(new Dictionary<int, object>(), (dic, next) => { if (next is KeyValuePair<int, object> kvp) dic.Add(kvp.Key, kvp.Value); return dic; })); } public KeyValuePair<int, object>[] GetFields() { return this.GetAllQuestions() .Select(q => new KeyValuePair<int, object>(q.Id, q.GetInputResponse()?.Answer)) .ToArray(); } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { return this.GetAllQuestions().Aggregate(new List<ValidationResult>(), (resultList, next) => { next.Validate(this.ValidationMessages); if (next.HasErrors) { resultList.AddRange ( next .Errors .Select(err => new ValidationResult(err, new string[] { next.VariableId })) ); } return resultList; }); } public override bool Equals(object obj) { if (obj == null) return false; if (obj.GetType() != typeof(InputFormView)) return false; InputFormView other = (InputFormView)obj; return other.Title == this.Title && other.Icon == this.Icon; } public override int GetHashCode() => (this.Title ?? string.Empty).GetHashCode(); } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class GoToTitle : MonoBehaviour { public void go() { SceneManager.LoadScene("titleScreen"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Task 7 namespace OccurrencesInArray { class Program { static void Main(string[] args) { int[] occurrencesArray = new int[1001]; int[] numbersArray = { 2, 4, 5, 3, 2, 6, 4, 7, 1, 2, 7, 9, 4, 8, 8, 3, 11 }; for (int i = 0; i < numbersArray.Length; i++) { occurrencesArray[numbersArray[i]]++; } for (int i = 0; i < occurrencesArray.Length; i++) { if (occurrencesArray[i] != 0) { if (occurrencesArray[i] == 1) { Console.WriteLine("Number: {0} - {1} time", i, occurrencesArray[i]); } else { Console.WriteLine("Number: {0} - {1} times", i, occurrencesArray[i]); } } } } } }
using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Support.UI; using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace ToolViewYoutubePro { class ToolViewYoutubePro { IWebDriver driver; public ToolViewYoutubePro() { // can them profile cho that try { FirefoxOptions options = new FirefoxOptions(); FirefoxProfile profile = new FirefoxProfile(); string userAgent = randomUserAgent(); profile.SetPreference("general.useragent.override", userAgent); if(ToolConfig.ui != true) { options.AddArguments("--headless"); } options.Profile = profile; driver = new FirefoxDriver(options); ToolLog.writeLog("User Agent:"+ userAgent); } catch(Exception ex) { ToolLog.showError(ex); } } public void gotoGoogle() { try { waitBrowser(3); driver.Navigate().GoToUrl(ToolConfig.urlGoogle); ToolLog.writeLog("tao user moi"); waitBrowser(3); // nhap vao khung tim kiem driver.FindElement(By.Name(ToolConfig.elementSearch)).SendKeys(ToolConfig.keySearchGoogle); Thread.Sleep(ToolConfig.timeWait); driver.FindElement(By.Name(ToolConfig.elementSearch)).SendKeys(Keys.Enter); ToolLog.writeLog("tao thong tin trinh duyet moi"); waitBrowser(ToolConfig.timeWait); } catch (Exception ex) { ToolLog.showError(ex); } } public void gotoYoutube() { try { Thread.Sleep(ToolConfig.timeWait); driver.FindElement(By.CssSelector("[href*='" + ToolConfig.urlYoutube + "']")).SendKeys(Keys.Enter); waitBrowser(ToolConfig.timeWait); ToolLog.writeLog("da vao youtube"); waitBrowser(ToolConfig.timeWait); driver.FindElement(By.Name(ToolConfig.elementSearchYoutube)).SendKeys(ToolConfig.keySearchYoutube); waitBrowser(ToolConfig.timeWait); driver.FindElement(By.Name(ToolConfig.elementSearchYoutube)).SendKeys(Keys.Enter); ToolLog.writeLog("tim kiem" + ToolConfig.keySearchYoutube); waitBrowser(ToolConfig.timeWait); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); var element = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("[href*='" + ToolConfig.idVideo + "']"))); Actions action = new Actions(driver); ToolLog.writeLog("hover chuot" + " vào video chứa url video"); action.MoveToElement(element).Perform(); waitBrowser(ToolConfig.timeWait); driver.FindElement(By.CssSelector("[href*='" + ToolConfig.idVideo + "']")).Click(); ToolLog.writeLog("click vao video"); ToolLog.writeLog("đang xem: " + ToolConfig.idVideo); Thread.Sleep(ToolConfig.timeVideo * 1000); ToolLog.writeLog("đã xem " + ToolConfig.timeVideo + "s"); } catch (Exception ex) { ToolLog.showError(ex); } } public void waitBrowser(int second) { ToolLog.writeLog("dang cho "+second+"s"); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(second); Thread.Sleep(second * 1000); } public void openNewTab() { try { ((IJavaScriptExecutor)driver).ExecuteScript("window.open();"); ToolLog.writeLog("mở tab mới"); waitBrowser(2); } catch (Exception ex) { ToolLog.showError(ex); } } public void closeNewTab(int index=0) { try { driver.SwitchTo().Window(driver.WindowHandles[index]); driver.Close(); ToolLog.writeLog("close tab " + index); //((IJavaScriptExecutor)driver).ExecuteScript("window.close();"); driver.SwitchTo().Window(driver.WindowHandles[index]); ToolLog.writeLog("swich tab " + index); waitBrowser(3); } catch (Exception ex) { ToolLog.showError(ex); } } public void closeBrowser() { try { waitBrowser(2); driver.Quit(); waitBrowser(2); } catch (Exception ex) { ToolLog.showError(ex); } } public string randomUserAgent() { ArrayList usetAgents = new ArrayList() { "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2919.83 Safari/537.36", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2866.71 Safari/537.36", "Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2820.59 Safari/537.36", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2762.73 Safari/537.36", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2656.18 Safari/537.36", //"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/44.0.2403.155 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36", //"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:77.0) Gecko/20190101 Firefox/77.0", //"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:77.0) Gecko/20100101 Firefox/77.0", "Mozilla/5.0 (X11; Linux ppc64le; rv:75.0) Gecko/20100101 Firefox/75.0", //"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/75.0", //"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:75.0) Gecko/20100101 Firefox/75.0", "Mozilla/5.0 (X11; Linux; rv:74.0) Gecko/20100101 Firefox/74.0", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/73.0", //"Mozilla/5.0 (X11; OpenBSD i386; rv:72.0) Gecko/20100101 Firefox/72.0", //"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:71.0) Gecko/20100101 Firefox/71.0", //"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:70.0) Gecko/20191022 Firefox/70.0", //"Mozilla/5.0 (Windows NT 6.1; WOW64; rv: 70.0) Gecko / 20190101 Firefox / 70.0", "Mozilla/ 5.0(Windows; U; Windows NT 9.1; en - US; rv: 12.9.1.11) Gecko / 20100821 Firefox / 70", //"Mozilla/5.0 (X11; Linux i686; rv:64.0) Gecko/20100101 Firefox/64.0", //"Mozilla/5.0 (Windows NT 6.1; WOW64; rv: 64.0) Gecko / 20100101 Firefox / 64.0", //"Mozilla/5.0 (X11; Linux i586; rv:63.0) Gecko/20100101 Firefox/63.0", //"Mozilla/5.0 (Windows NT 6.2; WOW64; rv: 63.0) Gecko / 20100101 Firefox / 63.0", //"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:62.0) Gecko/20100101 Firefox/62.0", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv: 10.0) Gecko / 20100101 Firefox / 62.0", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.13+ (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2", //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10", //"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; de-at) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1", //"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; da-dk) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1", //"Mozilla/5.0 (Windows; U; Windows NT 6.1; tr-TR) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27", //"Mozilla/5.0 (Windows; U; Windows NT 6.1; ko - KR) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Windows; U; Windows NT 6.1; fr - FR) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Windows; U; Windows NT 6.1; en - US) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Windows; U; Windows NT 6.1; cs - CZ) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Windows; U; Windows NT 6.0; ja - JP) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Windows; U; Windows NT 6.0; en - US) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; PPC Mac OS X 10_5_8; zh - cn) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; PPC Mac OS X 10_5_8; ja - jp) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_7; ja - jp) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; zh - cn) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; sv - se) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; ko - kr) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; ja - jp) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; it - it) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; fr - fr) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; es - es) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; en - us) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; en - gb) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; de - de) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.4 Safari / 533.20.27", //"Mozilla/5.0 (Windows; U; Windows NT 6.1; sv-SE) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4", //"Mozilla/5.0 (Windows; U; Windows NT 6.1; ja - JP) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 6.1; de - DE) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 6.0; hu - HU) AppleWebKit / 533.19.4(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 6.0; en - US) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 6.0; de - DE) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 5.1; ru - RU) AppleWebKit / 533.19.4(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 5.1; ja - JP) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 5.1; it - IT) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Windows; U; Windows NT 5.1; en - US) AppleWebKit / 533.20.25(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_7; en - us) AppleWebKit / 534.16 + (KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_6; fr - ch) AppleWebKit / 533.19.4(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_5; de - de) AppleWebKit / 534.15 + (KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", //"Mozilla / 5.0(Macintosh; U; Intel Mac OS X 10_6_5; ar) AppleWebKit / 533.19.4(KHTML, like Gecko) Version / 5.0.3 Safari / 533.19.4", }; int idAgent = new Random().Next(usetAgents.Count); return usetAgents[idAgent].ToString(); } } class ToolLog { public static void writeLog(string mess = "") { StringBuilder sb = new StringBuilder(); sb.Append("\r\n" + DateTime.Now + " " + mess); File.AppendAllText(ToolConfig.filePath + "log.txt", sb.ToString()); Console.WriteLine(sb.ToString()); } public static void showError(Exception ex) { //Console.WriteLine(ex.Message); writeLog(ex.Message); } } class ToolConfig { public static int timeWait = Int32.Parse(ConfigurationManager.AppSettings["timeWait"]);//seconds public static string filePath = string.Empty; public static string fileLogName = "logs.txt"; public static string urlGoogle = @"https://www.google.com/"; public static string urlYoutube = @"https://www.youtube.com/"; public static string keySearchYoutube = ConfigurationManager.AppSettings["keySearchYoutube"]; public static string keySearchGoogle = "youtube"; public static string elementSearch = "q"; public static string elementSearchYoutube = "search_query"; public static string idVideo = ConfigurationManager.AppSettings["idVideo"]; public static int timeVideo = Int32.Parse(ConfigurationManager.AppSettings["timeVideo"]);//seconds public static bool ui = ConfigurationManager.AppSettings["ui"].Contains("true"); } }
using System.Collections.Generic; using System.Windows.Input; using Caliburn.Micro; using Frontend.Core.Commands; using Frontend.Core.Events.EventArgs; using Frontend.Core.Navigation; using Frontend.Core.ViewModels.Interfaces; namespace Frontend.Core.ViewModels { public class FrameViewModel : StepConductorBase, IFrameViewModel { public FrameViewModel(IEventAggregator eventAggregator) : base(eventAggregator) { EventAggregator.Subscribe(this); } public void Handle(PreferenceStepOperationArgs message) { switch (message.Operation) { case PreferenceOperation.AddSteps: AddPreferenceSteps(message.NewSteps); break; case PreferenceOperation.Clear: RemoveConverterSpecificSteps(); break; } } private void AddPreferenceSteps(IList<IStep> newSteps) { var oldCount = Steps.Count; foreach (var step in newSteps) { Steps.Add(step); } } private void RemoveConverterSpecificSteps() { var oldCount = Steps.Count; var removedCount = 0; // Assumption: The first two steps are: // * The welcome view // * The path picker view // So we remove everything else. while (Steps.Count > 2) { Steps.RemoveAt(2); removedCount++; } } #region [ Fields ] private ILogViewModel logViewModel; private ICommand moveCommand; #endregion #region [ Properties ] public ILogViewModel Log { get { return logViewModel ?? (logViewModel = new LogViewModel(EventAggregator)); } } public ICommand MoveCommand { get { return moveCommand ?? (moveCommand = new MoveCommand(EventAggregator, this)); } } #endregion } }
using Accounting.DataAccess; using Accounting.Utility; using AccSys.Web.WebControls; using System; using System.Web.UI.WebControls; using Tools; namespace AccSys.Web { public partial class FiscalYear : BasePage { protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { var companyId = GlobalFunctions.isNull(Session["CompanyID"], 0); LoadFiscalYears(); } } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } private void LoadFiscalYears() { gvData.DataSourceID = "odsCommon"; odsCommon.SelectParameters["SelectedColumns"].DefaultValue = @" FiscalYearID, Title, StartDate, EndDate, CompanyID, CAST(CASE WHEN EndDate IS NULL THEN 1 ELSE 0 END AS BIT) AS [Current] "; odsCommon.SelectParameters["FromTable"].DefaultValue = @" FiscalYear "; odsCommon.SelectParameters["Where"].DefaultValue = string.Format(" CompanyID={0} ", Session["CompanyID"] ?? 1); ; odsCommon.SelectParameters["OrderBy"].DefaultValue = " StartDate DESC "; gvData.PageIndex = 0; gvData.DataBind(); } protected void btnStart_Click(object sender, EventArgs e) { try { int companyId = GlobalFunctions.isNull(Session["CompanyID"], 0); DateTime startDate = Tools.Utility.GetDateValue(txtStartDate.Text.Trim(), DateNumericFormat.YYYYMMDD); DaFiscalYear.StartFiscalYear(txtTitle.Text.Trim(), startDate, companyId, 1); lblMsg.Text = UIMessage.Message2User("Successfully Started", UserUILookType.Success); Reset(); LoadFiscalYears(); } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } private void Reset() { txtTitle.Text = ""; txtTitle.Enabled = true; txtStartDate.Text = DateTime.Now.ToString("yyyy-MM-dd"); txtStartDate.Enabled = true; txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd"); txtEndDate.Visible = false; lblEndDate.Visible = false; btnStart.Visible = true; btnEnd.Visible = false; lblFYId.Text = "0"; } protected void btnEnd_Click(object sender, EventArgs e) { try { int id = lblFYId.Text.ToInt(); DateTime endDate = Tools.Utility.GetDateValue(txtEndDate.Text.Trim(), DateNumericFormat.YYYYMMDD); DaFiscalYear.EndFiscalYear(id, endDate); lblMsg.Text = UIMessage.Message2User("Successfully Ended", UserUILookType.Success); Reset(); LoadFiscalYears(); } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } protected void lbtnDelete_Click(object sender, EventArgs e) { Label lblRowId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblId"); int id = lblRowId.Text.ToInt(); try { new DaFiscalYear().DeleteFiscalYear(ConnectionHelper.getConnection(), id); lblMsg.Text = UIMessage.Message2User("Successfully deleted", UserUILookType.Success); LoadFiscalYears(); } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } protected void lbtnEdit_Click(object sender, EventArgs e) { try { Label lblRowId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblId"); lblFYId.Text = lblRowId.Text; Label lblTitle = (Label)((LinkButton)sender).NamingContainer.FindControl("lblTitle"); txtTitle.Text = lblTitle.Text; txtTitle.Enabled = true; Label lblStartDate = (Label)((LinkButton)sender).NamingContainer.FindControl("lblStartDate"); string date = lblStartDate.Text; txtStartDate.Text = Tools.Utility.GetDateValue(date, DateNumericFormat.DDMMYYYY).ToString("yyyy-MM-dd"); txtStartDate.Enabled = true; lblEndDate.Visible = false; txtEndDate.Visible = false; btnEnd.Visible = false; btnStart.Visible = true; lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } protected void lbtnEnd_Click(object sender, EventArgs e) { try { Label lblRowId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblId"); lblFYId.Text = lblRowId.Text; Label lblTitle = (Label)((LinkButton)sender).NamingContainer.FindControl("lblTitle"); txtTitle.Text = lblTitle.Text; txtTitle.Enabled = false; Label lblStartDate = (Label)((LinkButton)sender).NamingContainer.FindControl("lblStartDate"); string date = lblStartDate.Text; txtStartDate.Text = Tools.Utility.GetDateValue(date, DateNumericFormat.DDMMYYYY).ToString("yyyy-MM-dd"); txtStartDate.Enabled = false; lblEndDate.Visible = true; txtEndDate.Visible = true; btnEnd.Visible = true; btnStart.Visible = false; lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } } }
// Copyright 2021 Google LLC. 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 NtApiDotNet.Security; using System; namespace NtApiDotNet.Net.Firewall { /// <summary> /// Abstract class to represent a firewall object. /// </summary> public abstract class FirewallObject : INtObjectSecurity { private readonly Lazy<SecurityDescriptor> _get_sd_default; private readonly Func<SecurityInformation, bool, NtResult<SecurityDescriptor>> _get_sd; private protected readonly FirewallEngine _engine; /// <summary> /// The object's key. /// </summary> public Guid Key { get; } /// <summary> /// The object's name. /// </summary> public string Name { get; } /// <summary> /// The object's description. /// </summary> public string Description { get; } /// <summary> /// The object's key name. /// </summary> public string KeyName { get; } /// <summary> /// The object's security descriptor. /// </summary> public SecurityDescriptor SecurityDescriptor => _get_sd_default.Value; /// <summary> /// Get the security descriptor specifying which parts to retrieve /// </summary> /// <param name="security_information">What parts of the security descriptor to retrieve</param> /// <returns>The security descriptor</returns> /// <remarks>The firewall engine object must still be open.</remarks> public SecurityDescriptor GetSecurityDescriptor(SecurityInformation security_information) { return ((INtObjectSecurity)this).GetSecurityDescriptor(security_information, true).Result; } /// <summary> /// Get the security descriptor specifying which parts to retrieve /// </summary> /// <param name="security_information">What parts of the security descriptor to retrieve</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The security descriptor</returns> /// <remarks>The firewall engine object must still be open.</remarks> public NtResult<SecurityDescriptor> GetSecurityDescriptor(SecurityInformation security_information, bool throw_on_error) { return _get_sd(security_information, throw_on_error); } string INtObjectSecurity.ObjectName => Name; NtType INtObjectSecurity.NtType => FirewallUtils.FirewallType; bool INtObjectSecurity.IsContainer => false; bool INtObjectSecurity.IsAccessMaskGranted(AccessMask access) { return true; } void INtObjectSecurity.SetSecurityDescriptor(SecurityDescriptor security_descriptor, SecurityInformation security_information) { throw new NotImplementedException(); } NtStatus INtObjectSecurity.SetSecurityDescriptor(SecurityDescriptor security_descriptor, SecurityInformation security_information, bool throw_on_error) { throw new NotImplementedException(); } private protected FirewallObject(Guid key, FWPM_DISPLAY_DATA0 display_data, NamedGuidDictionary key_to_name, FirewallEngine engine, Func<SecurityInformation, bool, NtResult<SecurityDescriptor>> get_sd) { Key = key; Name = display_data.name ?? string.Empty; Description = display_data.description ?? string.Empty; KeyName = key_to_name.GetName(key); _engine = engine; _get_sd = get_sd; _get_sd_default = new Lazy<SecurityDescriptor>(() => ((INtObjectSecurity)this).GetSecurityDescriptor(SecurityInformation.Owner | SecurityInformation.Group | SecurityInformation.Dacl)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.WindowsAPICodePack.Dialogs; using static System.Windows.Forms.ListViewItem; namespace GITRepoManager { public partial class SettingsViewFRM : Form { private string Clone_Path { get; set; } private int Store_Count { get; set; } public static MainViewFRM Caller { get; set; } public SettingsViewFRM(MainViewFRM caller = null) { InitializeComponent(); if(caller != null) { Caller = caller; } } #region Events #region Form #region Load private void SettingsViewFRM_Load(object sender, EventArgs e) { FileInfo ConfigInfo = new FileInfo(Properties.Settings.Default.ConfigPath); MainViewFRM.Settings_Changed = false; if (ConfigInfo.Exists) { ConfigPathTB.Text = Properties.Settings.Default.ConfigPath; Populate_Stores(); if (!string.IsNullOrEmpty(Properties.Settings.Default.CloneLocalSourcePath) || !string.IsNullOrWhiteSpace(Properties.Settings.Default.CloneLocalSourcePath)) { CloneDestinationTB.Text = Properties.Settings.Default.CloneLocalSourcePath; } } Clone_Path = CloneDestinationTB.Text; Store_Count = StoreLocationLV.Items.Count; if (Properties.Settings.Default.LogParseMethod == 0) { SingleParseRB.Checked = true; } else { DynamicParseRB.Checked = true; } if(Properties.Settings.Default.AutoChangeRate > 0) { AutoChangeCB.Checked = true; AutoChangeRateTB.Text = Properties.Settings.Default.AutoChangeRate.ToString(); } } #endregion #region Closing private void SettingsViewFRM_FormClosing(object sender, FormClosingEventArgs e) { } #endregion #endregion Form #region Mouse #region Click #region BrowseBT private void BrowseBT_Click(object sender, EventArgs e) { SaveMessageLB.Text = string.Empty; CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = @"C:\", IsFolderPicker = true }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { if (string.IsNullOrEmpty(dialog.FileName) || string.IsNullOrWhiteSpace(dialog.FileName)) { MessageBox.Show("Path to add cannot be empty.", "Empty Path", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { DirectoryInfo dirInfo = new DirectoryInfo(dialog.FileName); if (dirInfo.Exists) { ListViewItem Main = new ListViewItem { Name = dirInfo.Name, Text = dirInfo.Name, }; ListViewItem.ListViewSubItem Sub = new ListViewItem.ListViewSubItem { Name = dirInfo.FullName, Text = dirInfo.FullName }; Main.SubItems.Add(Sub); StoreLocationLV.Items.Add(Main); } else { MessageBox.Show("Could not find " + dialog.FileName); } } } } #endregion #region SaveSettingsBT private void SaveSettingsBT_Click(object sender, EventArgs e) { bool changed = false; SaveMessageLB.Text = string.Empty; if (!string.IsNullOrEmpty(CloneDestinationTB.Text) && !string.IsNullOrWhiteSpace(CloneDestinationTB.Text)) { if (CloneDestinationTB.Text != Properties.Settings.Default.CloneLocalSourcePath) { Properties.Settings.Default.CloneLocalSourcePath = CloneDestinationTB.Text; changed = true; } } if (Store_List_Changed()) { changed = true; MainViewFRM.Settings_Changed = true; // Add new items foreach (ListViewItem lvi in StoreLocationLV.Items) { if (!ManagerData.Stores.Keys.Contains(lvi.Name)) { StoreCell temp = null; temp = new StoreCell(lvi.SubItems[1].Name); temp._Repos = Get_Repos(new DirectoryInfo(lvi.SubItems[1].Name)); if (temp != null) { DirectoryInfo tempInfo = new DirectoryInfo(temp._Path); ManagerData.Stores.Add(tempInfo.Name, temp); } } } List<string> DeletedKeys = new List<string>(); foreach (string key in ManagerData.Stores.Keys) { if (StoreLocationLV.Items.Count > 0) { bool removeKey = true; foreach (ListViewItem lvi in StoreLocationLV.Items) { if (lvi.Name == key) { removeKey = false; } } if (removeKey) { DeletedKeys.Add(key); } } } if (StoreLocationLV.Items.Count == 0 && ManagerData.Stores.Count != 0) { ManagerData.Stores.Clear(); } else { foreach (string key in DeletedKeys) { ManagerData.Stores.Remove(key); } } } // Singular Parse int selected = 0; if (DynamicParseRB.Checked) { // Dynamic Parse selected = 1; } if (selected != Properties.Settings.Default.LogParseMethod) { Properties.Settings.Default.LogParseMethod = selected; changed = true; } // Auto Check For Changes Int32 changeRate = Convert.ToInt32(AutoChangeRateTB.Text); if (Properties.Settings.Default.AutoChangeRate == -1 && changeRate > 0) { changed = true; Properties.Settings.Default.AutoChangeRate = changeRate; } else if(Properties.Settings.Default.AutoChangeRate != -1 && Properties.Settings.Default.AutoChangeRate != changeRate) { changed = true; Properties.Settings.Default.AutoChangeRate = changeRate; } else if(changeRate <= 0) { Properties.Settings.Default.AutoChangeRate = -1; } if (changed) { changed = false; Configuration.Helpers.Serialize_Condensed_All(Properties.Settings.Default.ConfigPath); Properties.Settings.Default.Save(); Properties.Settings.Default.Upgrade(); Properties.Settings.Default.Reload(); SaveMessageLB.Text = "Settings successfully saved."; } } #endregion #region BrowseClonePathBT private void BrowseClonePathBT_Click(object sender, EventArgs e) { SaveMessageLB.Text = string.Empty; CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = @"C:\", IsFolderPicker = true }; if (dialog.ShowDialog() == CommonFileDialogResult.Ok) { CloneDestinationTB.Text = dialog.FileName; } } #endregion #region DeleteLocationBT private void DeleteLocationBT_Click(object sender, EventArgs e) { SaveMessageLB.Text = string.Empty; ListViewItem selected = StoreLocationLV.SelectedItems[0]; StoreLocationLV.SelectedItems.Clear(); StoreLocationLV.Items.Remove(selected); } #endregion #region AddPathBT private void AddPathBT_Click(object sender, EventArgs e) { } #endregion #region ConfigPathTB private void ConfigPathTB_Click(object sender, EventArgs e) { ConfigPathTB.SelectAll(); } #endregion #endregion Click #region Enter #region BrowseBT private void BrowseBT_MouseEnter(object sender, EventArgs e) { BrowseBT.BackgroundImage = Properties.Resources.Add_Tag_Icon_Hover; SettingsInfoSSSL.Text = "Browse to a store location."; } #endregion #region SaveSettingsBT private void SaveSettingsBT_MouseEnter(object sender, EventArgs e) { SaveSettingsBT.BackgroundImage = Properties.Resources.Save_Settings_Icon_Hover; SettingsInfoSSSL.Text = "Save this configuration."; } #endregion #region DeleteLocationBT private void DeleteLocationBT_MouseEnter(object sender, EventArgs e) { DeleteLocationBT.BackgroundImage = Properties.Resources.DeleteIcon_Hover; SettingsInfoSSSL.Text = "Remove the selected store from the configuration."; } #endregion #region BrowseClonePathBT private void BrowseClonePathBT_MouseEnter(object sender, EventArgs e) { BrowseClonePathBT.BackgroundImage = Properties.Resources.Browse_Icon_Hover; SettingsInfoSSSL.Text = "Browse for a default location to use when cloning."; } #endregion #region Object_Description private void Object_MouseEnter(object sender, EventArgs e) { try { RadioButton temp = sender as RadioButton; switch (temp.Name) { case "SingleParseRB": SettingsInfoSSSL.Text = "Only parse each repo's logs once during runtime (Faster)"; return; case "DynamicParseRB": SettingsInfoSSSL.Text = "Parse each repo's logs whenever a selection changes (Slower)"; return; default: return; } } catch { } try { CheckBox temp = sender as CheckBox; switch (temp.Name) { case "AutoChangeCB": SettingsInfoSSSL.Text = "Set the increment to check for external changes"; return; default: return; } } catch { } } #endregion #endregion Enter #region Leave #region BrowseBT private void BrowseBT_MouseLeave(object sender, EventArgs e) { BrowseBT.BackgroundImage = Properties.Resources.Add_Tag_Icon; SettingsInfoSSSL.Text = string.Empty; } #endregion #region SaveSettingsBT private void SaveSettingsBT_MouseLeave(object sender, EventArgs e) { SaveSettingsBT.BackgroundImage = Properties.Resources.Save_Settings_Icon; SettingsInfoSSSL.Text = string.Empty; } #endregion #region DeleteLocationBT private void DeleteLocationBT_MouseLeave(object sender, EventArgs e) { DeleteLocationBT.BackgroundImage = Properties.Resources.DeleteIcon; SettingsInfoSSSL.Text = string.Empty; } #endregion #region BrowseClonePathBT private void BrowseClonePathBT_MouseLeave(object sender, EventArgs e) { BrowseClonePathBT.BackgroundImage = Properties.Resources.Browse_Icon; SettingsInfoSSSL.Text = string.Empty; } #endregion #region Object_Description private void Object_MouseLeave(object sender, EventArgs e) { SettingsInfoSSSL.Text = string.Empty; } #endregion #endregion Leave #endregion Mouse #region List View #region Selected Index Changed #region StoreLocationsLV private void StoreLocationsLV_SelectedIndexChanged(object sender, EventArgs e) { if (StoreLocationLV.SelectedItems.Count > 0) { DeleteLocationBT.Visible = true; SettingsInfoSSSL.Text = StoreLocationLV.SelectedItems[0].SubItems[1].Text; } else { DeleteLocationBT.Visible = false; } } #endregion #endregion Selected Index Changed #endregion List View #region Text Box private void CloneDestinationTB_TextChanged(object sender, EventArgs e) { SaveMessageLB.Text = string.Empty; } #endregion Text Box #endregion Events #region Methods #region Populate_Stores private void Populate_Stores() { if (ManagerData.Stores.Count > 0) { foreach (KeyValuePair<string, StoreCell> kvp in ManagerData.Stores) { ListViewItem Main = new ListViewItem { Name = kvp.Key, Text = kvp.Key, }; ListViewItem.ListViewSubItem Sub = new ListViewItem.ListViewSubItem { Name = kvp.Value._Path, Text = kvp.Value._Path }; Main.SubItems.Add(Sub); StoreLocationLV.Items.Add(Main); } } } #endregion #region Get_Repos private Dictionary<string, RepoCell> Get_Repos(DirectoryInfo pathInfo) { Dictionary<string, RepoCell> Repos = new Dictionary<string, RepoCell>(); foreach (string dir in Directory.GetDirectories(pathInfo.FullName)) { DirectoryInfo dirInfo = new DirectoryInfo(dir); if (dirInfo.Exists) { if (RepoHelpers.Is_Git_Repo(dir)) { RepoCell tempRepo = new RepoCell() { Name = dirInfo.Name, Path = dirInfo.FullName, Current_Status = RepoCell.Status.Type.NEW, Last_Commit = DateTime.MinValue, Last_Commit_Message = "", Notes = new Dictionary<string, string>(), Logs = new Dictionary<string, List<EntryCell>>() }; Repos.Add(dirInfo.Name, tempRepo); } } } return Repos; } #endregion #region Store_List_Changed private bool Store_List_Changed() { foreach (ListViewItem lvi in StoreLocationLV.Items) { if (!ManagerData.Stores.Keys.Contains(lvi.Name)) { return true; } } if (StoreLocationLV.Items.Count != ManagerData.Stores.Count) { return true; } return false; } #endregion #endregion Methods private void AutoChangeCB_CheckedChanged(object sender, EventArgs e) { if(AutoChangeCB.Checked) { AutoChangeLB1.Visible = true; AutoChangeRateTB.Visible = true; AutoChangeLB2.Visible = true; } else { AutoChangeLB1.Visible = false; AutoChangeRateTB.Visible = false; AutoChangeLB2.Visible = false; } } private void AutoChangeRateTB_TextChanged(object sender, EventArgs e) { try { int res = Convert.ToInt32(AutoChangeRateTB.Text); if (res < 0) { AutoChangeRateTB.Text = "0"; } else { AutoChangeRateTB.Text = res.ToString(); } } catch { } } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; // Place onto game object to allow player to pick up the new item public class InventoryItemPickUp : MonoBehaviour { public InvenctoryMenu inventoryScript; public string name; public string description; public Sprite image; public TriggerType triggerType; private bool inRange = false; void Update() { if (inRange == true) { if (triggerType == TriggerType.ButtonPress && Input.GetKeyDown(KeyCode.R)) { AddItemToInventory(); this.enabled = false; } else if (triggerType == TriggerType.Automatic) { AddItemToInventory(); this.enabled = false; } } } public void AddItemToInventory () { inventoryScript.AddNewItem(new InventoryItem(name, description, image)); } void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Player") { inRange = true; } } void OnTriggerExit(Collider other) { if (other.gameObject.tag == "Player") { inRange = false; } } }
using System; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; namespace receiver { public static class receiver { [FunctionName("receiver")] public static void Run([ServiceBusTrigger("messagesqueue", Connection = "ServiceBusConnectionString")]string myQueueItem, ILogger log) { log.LogInformation($"[QueueMessage];{myQueueItem};{DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff")}"); } } }
using System; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace NetFabric.Hyperlinq { public static partial class ReadOnlyListExtensions { [GeneratorMapping("TPredicate", "NetFabric.Hyperlinq.FunctionWrapper<TSource, bool>")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static WhereEnumerable<TList, TSource, FunctionWrapper<TSource, bool>> Where<TList, TSource>(this TList source, Func<TSource, bool> predicate) where TList : IReadOnlyList<TSource> => source.Where<TList, TSource, FunctionWrapper<TSource, bool>>(new FunctionWrapper<TSource, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static WhereEnumerable<TList, TSource, TPredicate> Where<TList, TSource, TPredicate>(this TList source, TPredicate predicate = default) where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, bool> => source.Where<TList, TSource, TPredicate>(predicate, 0, source.Count); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static WhereEnumerable<TList, TSource, TPredicate> Where<TList, TSource, TPredicate>(this TList source, TPredicate predicate, int offset, int count) where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, bool> => new(in source, predicate, offset, count); [StructLayout(LayoutKind.Auto)] public readonly partial struct WhereEnumerable<TList, TSource, TPredicate> : IValueEnumerable<TSource, WhereEnumerable<TList, TSource, TPredicate>.DisposableEnumerator> where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, bool> { readonly TList source; readonly TPredicate predicate; readonly int offset; readonly int count; internal WhereEnumerable(in TList source, TPredicate predicate, int offset, int count) { this.source = source; this.predicate = predicate; (this.offset, this.count) = Utils.SkipTake(source.Count, offset, count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly Enumerator GetEnumerator() => new(in this); readonly DisposableEnumerator IValueEnumerable<TSource, DisposableEnumerator>.GetEnumerator() => new(in this); readonly IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator() // ReSharper disable once HeapView.BoxingAllocation => new DisposableEnumerator(in this); readonly IEnumerator IEnumerable.GetEnumerator() // ReSharper disable once HeapView.BoxingAllocation => new DisposableEnumerator(in this); [StructLayout(LayoutKind.Auto)] public struct Enumerator { readonly TList source; TPredicate predicate; readonly int end; int index; internal Enumerator(in WhereEnumerable<TList, TSource, TPredicate> enumerable) { source = enumerable.source; predicate = enumerable.predicate; index = enumerable.offset - 1; end = index + enumerable.count; } public readonly TSource Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => source[index]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { while (++index <= end) { if (predicate.Invoke(source[index])) return true; } return false; } } [StructLayout(LayoutKind.Auto)] public struct DisposableEnumerator : IEnumerator<TSource> { readonly TList source; TPredicate predicate; readonly int end; int index; internal DisposableEnumerator(in WhereEnumerable<TList, TSource, TPredicate> enumerable) { source = enumerable.source; predicate = enumerable.predicate; index = enumerable.offset - 1; end = index + enumerable.count; } public readonly TSource Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => source[index]; } readonly TSource IEnumerator<TSource>.Current => source[index]; readonly object? IEnumerator.Current // ReSharper disable once HeapView.PossibleBoxingAllocation => source[index]; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { while (++index <= end) { if (predicate.Invoke(source[index])) return true; } return false; } [ExcludeFromCodeCoverage] public readonly void Reset() => Throw.NotSupportedException(); public readonly void Dispose() { } } #region Aggregation [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Count() => source.Count<TList, TSource, TPredicate>(predicate, offset, count); #endregion #region Quantifier [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool All() => source.All<TList, TSource, TPredicate>(predicate); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool All(Func<TSource, bool> predicate) => All(new FunctionWrapper<TSource, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool All<TPredicate2>(TPredicate2 predicate) where TPredicate2 : struct, IFunction<TSource, bool> => source.All<TList, TSource, PredicatePredicateCombination<TPredicate, TPredicate2, TSource>>(new PredicatePredicateCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool All(Func<TSource, int, bool> predicate) => AllAt(new FunctionWrapper<TSource, int, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllAt<TPredicate2>(TPredicate2 predicate) where TPredicate2 : struct, IFunction<TSource, int, bool> => source.AllAt<TList, TSource, PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>>(new PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Any() => source.Any<TList, TSource, TPredicate>(predicate); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Any(Func<TSource, bool> predicate) => Any(new FunctionWrapper<TSource, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Any<TPredicate2>(TPredicate2 predicate) where TPredicate2 : struct, IFunction<TSource, bool> => source.Any<TList, TSource, PredicatePredicateCombination<TPredicate, TPredicate2, TSource>>(new PredicatePredicateCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Any(Func<TSource, int, bool> predicate) => AnyAt(new FunctionWrapper<TSource, int, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AnyAt<TPredicate2>(TPredicate2 predicate) where TPredicate2 : struct, IFunction<TSource, int, bool> => source.AnyAt<TList, TSource, PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>>(new PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate)); #endregion #region Filtering [MethodImpl(MethodImplOptions.AggressiveInlining)] public WhereEnumerable<TList, TSource, PredicatePredicateCombination<TPredicate, FunctionWrapper<TSource, bool>, TSource>> Where(Func<TSource, bool> predicate) => Where(new FunctionWrapper<TSource, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public WhereEnumerable<TList, TSource, PredicatePredicateCombination<TPredicate, TPredicate2, TSource>> Where<TPredicate2>(TPredicate2 predicate = default) where TPredicate2 : struct, IFunction<TSource, bool> => source.Where<TList, TSource, PredicatePredicateCombination<TPredicate, TPredicate2, TSource>>(new PredicatePredicateCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate), offset, count); [MethodImpl(MethodImplOptions.AggressiveInlining)] public WhereAtEnumerable<TList, TSource, PredicatePredicateAtCombination<TPredicate, FunctionWrapper<TSource, int, bool>, TSource>> Where(Func<TSource, int, bool> predicate) => WhereAt<FunctionWrapper<TSource, int, bool>>(new FunctionWrapper<TSource, int, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public WhereAtEnumerable<TList, TSource, PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>> WhereAt<TPredicate2>(TPredicate2 predicate = default) where TPredicate2 : struct, IFunction<TSource, int, bool> => source.WhereAt<TList, TSource, PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>>(new PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate), offset, count); #endregion #region Projection [MethodImpl(MethodImplOptions.AggressiveInlining)] public WhereSelectEnumerable<TList, TSource, TResult, TPredicate, FunctionWrapper<TSource, TResult>> Select<TResult>(Func<TSource, TResult> selector) => Select<TResult, FunctionWrapper<TSource, TResult>>(new FunctionWrapper<TSource, TResult>(selector)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public WhereSelectEnumerable<TList, TSource, TResult, TPredicate, TSelector> Select<TResult, TSelector>(TSelector selector = default) where TSelector : struct, IFunction<TSource, TResult> => source.WhereSelect<TList, TSource, TResult, TPredicate, TSelector>(predicate, selector, offset, count); #endregion #region Element [MethodImpl(MethodImplOptions.AggressiveInlining)] public Option<TSource> ElementAt(int index) => source.ElementAt<TList, TSource, TPredicate>(index, predicate, offset, count); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Option<TSource> First() => source.First<TList, TSource, TPredicate>(predicate, offset, count); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Option<TSource> Single() #pragma warning disable HLQ005 // Avoid Single() and SingleOrDefault() => source.Single<TList, TSource, TPredicate>(predicate, offset, count); #pragma warning restore HLQ005 // Avoid Single() and SingleOrDefault() #endregion #region Conversion [MethodImpl(MethodImplOptions.AggressiveInlining)] public TSource[] ToArray() => source.ToArray<TList, TSource, TPredicate>(predicate, offset, count); [MethodImpl(MethodImplOptions.AggressiveInlining)] public IMemoryOwner<TSource> ToArray(MemoryPool<TSource> memoryPool) => source.ToArray<TList, TSource, TPredicate>(predicate, offset, count, memoryPool); [MethodImpl(MethodImplOptions.AggressiveInlining)] public List<TSource> ToList() => source.ToList<TList, TSource, TPredicate>(predicate, offset, count); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Dictionary<TKey, TSource> ToDictionary<TKey>(Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer = default) where TKey : notnull => ToDictionary<TKey, FunctionWrapper<TSource, TKey>>(new FunctionWrapper<TSource, TKey>(keySelector), comparer); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Dictionary<TKey, TSource> ToDictionary<TKey, TKeySelector>(TKeySelector keySelector, IEqualityComparer<TKey>? comparer = default) where TKey : notnull where TKeySelector : struct, IFunction<TSource, TKey> => source.ToDictionary<TList, TSource, TKey, TKeySelector, TPredicate>(keySelector, comparer, predicate, offset, count); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Dictionary<TKey, TElement> ToDictionary<TKey, TElement>(Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey>? comparer = default) where TKey : notnull => ToDictionary<TKey, TElement, FunctionWrapper<TSource, TKey>, FunctionWrapper<TSource, TElement>>(new FunctionWrapper<TSource, TKey>(keySelector), new FunctionWrapper<TSource, TElement>(elementSelector), comparer); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Dictionary<TKey, TElement> ToDictionary<TKey, TElement, TKeySelector, TElementSelector>(TKeySelector keySelector, TElementSelector elementSelector, IEqualityComparer<TKey>? comparer = default) where TKey : notnull where TKeySelector : struct, IFunction<TSource, TKey> where TElementSelector : struct, IFunction<TSource, TElement> => source.ToDictionary<TList, TSource, TKey, TElement, TKeySelector, TElementSelector, TPredicate>(keySelector, elementSelector, comparer, predicate, offset, count); #endregion } } }
 using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using NetCode; using NetcodeTest.Util; namespace NetcodeTest.Entities { public abstract class Entity { public Vector2 Position { get; protected set; } public float Angle { get; protected set; } public Vector2 Velocity { get; protected set; } [Synchronisable(SyncFlags.HalfPrecision)] public Vector2 baseVelocity { get; protected set; } [Synchronisable(SyncFlags.HalfPrecision)] public float AngularVelocity { get; protected set; } [Synchronisable(SyncFlags.HalfPrecision)] protected Vector2 basePosition { get; set; } [Synchronisable(SyncFlags.HalfPrecision)] protected float baseAngle { get; set; } [Synchronisable(SyncFlags.Timestamp)] protected int baseTimestamp { get; set; } public bool NeedsMotionReset { get; private set; } = true; public bool IsDestroyed { get; protected set; } = false; protected ContextToken Context; public Entity() { Position = Vector2.Zero; Velocity = Vector2.Zero; Angle = 0f; AngularVelocity = 0f; } public void RequestMotionUpdate() { NeedsMotionReset = true; } public virtual void UpdateMotion(long timestamp) { baseTimestamp = (int)timestamp; basePosition = Position; baseAngle = Angle; baseVelocity = Velocity; NeedsMotionReset = false; } public virtual void Predict(long timestamp) { long delta = timestamp - baseTimestamp; Position = basePosition + (baseVelocity * (delta / 1000.0f)); Angle = baseAngle + (AngularVelocity * (delta / 1000.0f)); } public virtual void Update(float delta) { Position += Velocity * delta; Angle += AngularVelocity * delta; if (Angle > MathHelper.TwoPi || Angle < MathHelper.TwoPi) { Angle = Fmath.Mod(Angle, MathHelper.TwoPi); } } public virtual void Set( Vector2 position, float angle ) { Position = position; Angle = angle; } public virtual void Clamp(Vector2 low, Vector2 high) { if (Position.X < low.X || Position.X > high.X || Position.Y < low.Y || Position.Y > high.Y) { Vector2 newPos = new Vector2(Fmath.Mod(Position.X - low.X, high.X - low.X) + low.X, Fmath.Mod(Position.Y - low.Y, high.Y - low.Y) + low.Y); Set(newPos, Angle); RequestMotionUpdate(); } } public void SetContext(ContextToken context) { Context = context; } public virtual void OnDestroy() { } public abstract void Draw(SpriteBatch batch); } }
using ReliableDbProvider.SqlAzure; namespace ReliableDbProvider.Tests { class SqlAzureProviderShould : DbProviderTestBase<SqlAzureProvider> {} }
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 BaseDeDonnees; namespace MaisonDesLigues { public partial class FormAjoutTheme : Form { private BaseDeDonnees.Bdd UneConnexion = new Bdd("mdl", "mdl"); public FormAjoutTheme() { InitializeComponent(); } private void BtnAnuler_Click(object sender, EventArgs e) { try { (new FrmPrincipale()).Show(this); this.Hide(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void comboAtelierTheme_SelectedIndexChanged(object sender, EventArgs e) { } private void FormAjoutTheme_Load(object sender, EventArgs e) { if (UneConnexion.ObtenirDonnesOracle("atelier").Rows.Count > 0) { comboAtelierTheme.DataSource = UneConnexion.ObtenirDonnesOracle("ATELIER"); comboAtelierTheme.DisplayMember = "LIBELLEATELIER"; comboAtelierTheme.ValueMember = "ID"; comboAtelierTheme.SelectedValue = "ID"; comboAtelierTheme.Enabled = true; } else { MessageBox.Show("Il existe aucun atelier"); FrmPrincipale form = new FrmPrincipale(); form.Show(); this.Hide(); } } private void BtnAjoutTheme_Click(object sender, EventArgs e) { UneConnexion.ajoutTheme(Convert.ToInt32(this.comboAtelierTheme.SelectedValue), Convert.ToInt32(this.numeroTheme.Value), Convert.ToString(this.libelleTheme.Text)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace WebApplication7.Models { public class Warehouse { [Key] public int WarehouseID { get; set; } //fk public int beach_id { get; set; } [ForeignKey("beach_id")] public Beach Beach { get; set; } [Required] [Display(Name = "Warehouse Name")] public string WarehouseName { get; set; } } }
using UnityEngine; using System.Collections; namespace ProjectV.ItemSystem{ public class ISArmorDatabase : ScriptableObjectDatabase<ISArmor> { } }
using MediatR; using Newtonsoft.Json; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol { namespace Models { [Parallel] [Method(TextDocumentNames.Rename, Direction.ClientToServer)] [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] [GenerateHandlerMethods] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] [RegistrationOptions(typeof(RenameRegistrationOptions))] [Capability(typeof(RenameCapability))] public partial record RenameParams : ITextDocumentIdentifierParams, IRequest<WorkspaceEdit?>, IWorkDoneProgressParams { /// <summary> /// The document to format. /// </summary> public TextDocumentIdentifier TextDocument { get; init; } = null!; /// <summary> /// The position at which this request was sent. /// </summary> public Position Position { get; init; } = null!; /// <summary> /// The new name of the symbol. If the given name is not valid the /// request must return a [ResponseError](#ResponseError) with an /// appropriate message set. /// </summary> public string NewName { get; init; } = null!; } [Parallel] [Method(TextDocumentNames.PrepareRename, Direction.ClientToServer)] [GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.Document")] [GenerateHandlerMethods] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] [RegistrationOptions(typeof(RenameRegistrationOptions))] [Capability(typeof(RenameCapability))] public partial record PrepareRenameParams : TextDocumentPositionParams, IRequest<RangeOrPlaceholderRange?>; [JsonConverter(typeof(RangeOrPlaceholderRangeConverter))] public record RangeOrPlaceholderRange { private readonly RenameDefaultBehavior? _renameDefaultBehavior; private readonly Range? _range; private readonly PlaceholderRange? _placeholderRange; public RangeOrPlaceholderRange(Range value) { _range = value; } public RangeOrPlaceholderRange(PlaceholderRange value) { _placeholderRange = value; } public RangeOrPlaceholderRange(RenameDefaultBehavior renameDefaultBehavior) { _renameDefaultBehavior = renameDefaultBehavior; } public bool IsPlaceholderRange => _placeholderRange != null; public PlaceholderRange? PlaceholderRange { get => _placeholderRange; init { _placeholderRange = value; _renameDefaultBehavior = default; _range = null; } } public bool IsRange => _range is not null; public Range? Range { get => _range; init { _placeholderRange = default; _renameDefaultBehavior = default; _range = value; } } public bool IsDefaultBehavior => _renameDefaultBehavior is not null; public RenameDefaultBehavior? DefaultBehavior { get => _renameDefaultBehavior; init { _placeholderRange = default; _renameDefaultBehavior = value; _range = default; } } public object? RawValue { get { if (IsPlaceholderRange) return PlaceholderRange; if (IsRange) return Range; if (IsDefaultBehavior) return DefaultBehavior; return default; } } public static implicit operator RangeOrPlaceholderRange(PlaceholderRange value) { return new RangeOrPlaceholderRange(value); } public static implicit operator RangeOrPlaceholderRange(Range value) { return new RangeOrPlaceholderRange(value); } } public record PlaceholderRange { public Range Range { get; init; } = null!; public string Placeholder { get; init; } = null!; } public record RenameDefaultBehavior { public bool DefaultBehavior { get; init; } } [GenerateRegistrationOptions(nameof(ServerCapabilities.RenameProvider))] [RegistrationName(TextDocumentNames.Rename)] public partial class RenameRegistrationOptions : ITextDocumentRegistrationOptions, IWorkDoneProgressOptions, IStaticRegistrationOptions { /// <summary> /// Renames should be checked and tested before being executed. /// </summary> [Optional] public bool PrepareProvider { get; set; } } } namespace Client.Capabilities { [CapabilityKey(nameof(ClientCapabilities.TextDocument), nameof(TextDocumentClientCapabilities.Rename))] public class RenameCapability : DynamicCapability { /// <summary> /// Client supports testing for validity of rename operations /// before execution. /// </summary> [Optional] public bool PrepareSupport { get; set; } /// <summary> /// Client supports the default behavior result (`{ defaultBehavior: boolean }`). /// /// @since version 3.16.0 /// </summary> [Optional] public PrepareSupportDefaultBehavior PrepareSupportDefaultBehavior { get; set; } /// <summary> /// Whether th client honors the change annotations in /// text edits and resource operations returned via the /// `CodeAction#edit` property by for example presenting /// the workspace edit in the user interface and asking /// for confirmation. /// /// @since 3.16.0 /// </summary> [Optional] public bool HonorsChangeAnnotations { get; set; } } public enum PrepareSupportDefaultBehavior { /// <summary> /// The client's default behavior is to select the identifier /// according the to language's syntax rule. /// </summary> Identifier = 1 } } namespace Document { } }
using CalculatorProject; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Calculator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> enum SelectedOperator { Plus, Minus, Times, Divide } public partial class MainWindow : Window { private static double? lastNumber = null; private static double? result = null; private static SelectedOperator? selectedOperator = null; public MainWindow() { InitializeComponent(); AC.Click += AC_Click; Equal.Click += Equal_Click; Plus_Minus.Click += Plus_Minus_Click; Dot.Click += Dot_Click; Percent.Click += Percent_Click; Divide.Click += Operation; Times.Click += Operation; Minus.Click += Operation; Add.Click += Operation; } private void Operation(object sender, RoutedEventArgs e) { var theClicked = sender as Button; String operation = theClicked.Name; switch (operation) { case "Divide": selectedOperator = SelectedOperator.Divide; OperationSymbol.Content = "/"; break; case "Times": selectedOperator = SelectedOperator.Times; OperationSymbol.Content = "*"; break; case "Minus": selectedOperator = SelectedOperator.Minus; OperationSymbol.Content = "-"; break; case "Add": selectedOperator = SelectedOperator.Plus; OperationSymbol.Content = "+"; break; } lastNumber = Double.Parse(Label.Content.ToString()); } private void Percent_Click(object sender, RoutedEventArgs e) { if (lastNumber != null) // if there was a previous number { Label.Content = ((lastNumber / 100) * Double.Parse(Label.Content.ToString())).ToString(); } else // if there isn't a previous number { Label.Content = (Double.Parse(Label.Content.ToString()) * 0.01).ToString(); lastNumber = Double.Parse(Label.Content.ToString()); } } private void Dot_Click(object sender, RoutedEventArgs e) { if (!(Label.Content.ToString()).Contains(".")) { Label.Content += "."; } } private void Plus_Minus_Click(object sender, RoutedEventArgs e) { Label.Content = (Convert.ToDouble(Label.Content)*-1).ToString(); } private void Equal_Click(object sender, RoutedEventArgs e) { if (lastNumber == null) lastNumber = null; else { switch (selectedOperator) { case SelectedOperator.Divide: if (MathService.isFinished == true) { try { result = MathService.Divide(lastNumber, MathService.secondNumber); } catch (DivideByZeroException ex) { MessageBox.Show("Cannot divide by 0", "Error", MessageBoxButton.OK, MessageBoxImage.Error); lastNumber = 0; result = 0; } } else { try { result = MathService.Divide(lastNumber, Convert.ToDouble(Label.Content)); } catch (DivideByZeroException ex) { MessageBox.Show("Cannot divide by 0", "Error", MessageBoxButton.OK, MessageBoxImage.Error); lastNumber = 0; result = 0; } } break; case SelectedOperator.Times: if (MathService.isFinished == true) result = MathService.Times(lastNumber, MathService.secondNumber); else result = MathService.Times(lastNumber, Convert.ToDouble(Label.Content)); break; case SelectedOperator.Minus: if (MathService.isFinished == true) result = MathService.Minus(lastNumber, MathService.secondNumber); else result = MathService.Minus(lastNumber, Convert.ToDouble(Label.Content)); break; case SelectedOperator.Plus: if (MathService.isFinished == true) result = MathService.Plus(lastNumber, MathService.secondNumber); else result = MathService.Plus(lastNumber, Convert.ToDouble(Label.Content)); break; } Label.Content = result; lastNumber = result; } } private void AC_Click(object sender, RoutedEventArgs e) { lastNumber = null; result = null; selectedOperator = null; Label.Content = "0"; MathService.isFinished = false; MathService.secondNumber = null; } private void Number(object sender, RoutedEventArgs e) { if (MathService.isFinished == true) MathService.isFinished = false; OperationSymbol.Content = ""; var theClicked = sender as Button; String number = theClicked.Content.ToString(); if (Label.Content.ToString() == "0") Label.Content = ""; else if (Label.Content.ToString() == lastNumber.ToString()) Label.Content = ""; Label.Content += number; } } }
using System; namespace Binocle.Importers { [Serializable] public class TexturePackerRectangle { public int x; public int y; public int w; public int h; public override string ToString() { return string.Format("{0} {1} {2} {3}", x, y, w, h); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Convey.CQRS.Events.Handler; using Microsoft.Extensions.DependencyInjection; namespace Convey.CQRS.Events.Dispatchers { internal sealed class EventDispatcher : IEventDispatcher { private readonly IServiceScopeFactory _serviceFactory; public EventDispatcher(IServiceScopeFactory serviceFactory) { _serviceFactory = serviceFactory; } public async Task PublishAsync<T>(T @event) where T : class, IEvent { using (var scope = _serviceFactory.CreateScope()) { var handlers = scope.ServiceProvider.GetServices<IEventHandler<T>>(); foreach (var handler in handlers) { await handler.HandleAsync(@event); } } } public async Task DispatchAsync<T>(T @event) where T : class, IEvent { using (var scope = _serviceFactory.CreateScope()) { Type handlerType = typeof(IEventHandler<>).MakeGenericType(@event.GetType()); Type wrapperType = typeof(Handler.EventHandler<>).MakeGenericType(@event.GetType()); var handlers = scope.ServiceProvider.GetServices(handlerType); IEnumerable<Handler.EventHandler> wrappedHandlers = handlers.Cast<object>() .Select(handler => (Handler.EventHandler)Activator.CreateInstance(wrapperType, handler)); foreach (Handler.EventHandler handler in wrappedHandlers) await handler.Handle(@event); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SQLiteHandler.Instance.InsertKeyword(this.textBox1.Text); this.textBox1.Clear(); } private void button2_Click(object sender, EventArgs e) { this.Close(); //Form2.ActiveForm. } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { button1_Click(sender, new EventArgs()); e.SuppressKeyPress = true; } } } }
using Ramazan.UdemyBlogWebSite.Entities.Concreate; using System; using System.Collections.Generic; using System.Text; namespace Ramazan.UdemyBlogWebSite.Business.ToolsUtilities.JWTTool { public interface IJwtService { JwtToken GenerateJwt(AppUser appUser); } }
using System; using DryIoc; using OmniSharp.Extensions.DebugAdapter.Protocol; using OmniSharp.Extensions.JsonRpc; namespace OmniSharp.Extensions.DebugAdapter.Shared { internal static class DebugAdapterProtocolServiceCollectionExtensions { internal static IContainer AddDebugAdapterProtocolInternals<T>(this IContainer container, DebugAdapterRpcOptionsBase<T> options) where T : IJsonRpcHandlerRegistry<T> { if (options.Serializer == null) { throw new ArgumentException("Serializer is missing!", nameof(options)); } container = container.AddJsonRpcServerCore(options); if (options.UseAssemblyAttributeScanning) { container.RegisterInstanceMany(new AssemblyAttributeHandlerTypeDescriptorProvider(options.Assemblies), nonPublicServiceTypes: true); } else { container.RegisterInstanceMany(new AssemblyScanningHandlerTypeDescriptorProvider(options.Assemblies), nonPublicServiceTypes: true); } container.RegisterInstanceMany(options.Serializer); container.RegisterInstance(options.RequestProcessIdentifier); container.RegisterMany<DebugAdapterSettingsBag>(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.RegisterMany<DapReceiver>(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.RegisterMany<DapOutputFilter>(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.RegisterMany<DebugAdapterRequestRouter>(Reuse.Singleton); container.RegisterMany<DebugAdapterHandlerCollection>(nonPublicServiceTypes: true, reuse: Reuse.Singleton); container.RegisterInitializer<DebugAdapterHandlerCollection>( (manager, context) => { var descriptions = context.Resolve<IJsonRpcHandlerCollection>(); descriptions.Populate(context, manager); } ); container.RegisterMany<DapResponseRouter>(Reuse.Singleton); return container; } } }
using AutoFixture.Xunit2; using Crt.Data.Database; using Crt.Data.Repositories; using Crt.Domain.Services; using Crt.Model; using Crt.Model.Dtos.CodeLookup; using Crt.Model.Dtos.FinTarget; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Crt.Tests.UnitTests.FinTargets { public class FinTargetsShould { [Theory] [AutoMoqData] public void CreateFinTargetWhenValid(FinTargetCreateDto finTargetCreateDto, [Frozen] Mock<IUnitOfWork> mockUnitOfWork, //[Frozen] Mock<IUserRepository> mockUserRepo, [Frozen] Mock<IFinTargetRepository> mockFinTargetRepo, [Frozen] Mock<IFieldValidatorService> mockFieldValidator, FinTargetService sut) { //arrange var errors = new Dictionary<string, List<string>>(); mockFieldValidator.Setup(x => x.Validate(It.IsAny<string>(), It.IsAny<FinTargetCreateDto>() , It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<int>())) .Returns(errors); mockFinTargetRepo.Setup(x => x.ElementExists(It.IsAny<decimal>())).Returns(Task.FromResult(true)); //act var result = sut.CreateFinTargetAsync(finTargetCreateDto).Result; //assert Assert.Empty(result.errors); mockUnitOfWork.Verify(x => x.Commit(), Times.Once); } [Theory] [AutoMoqData] public void FailToCreateFinTargetWhenElementIdInvalid(FinTargetCreateDto finTargetCreateDto, [Frozen] Mock<IUnitOfWork> mockUnitOfWork, //[Frozen] Mock<IUserRepository> mockUserRepo, [Frozen] Mock<IFinTargetRepository> mockFinTargetRepo, [Frozen] Mock<IFieldValidatorService> mockFieldValidator, FinTargetService sut) { //arrange var errors = new Dictionary<string, List<string>>(); mockFieldValidator.Setup(x => x.Validate(It.IsAny<string>(), It.IsAny<FinTargetCreateDto>() , It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<int>())) .Returns(errors); mockFinTargetRepo.Setup(x => x.ElementExists(It.IsAny<decimal>())).Returns(Task.FromResult(false)); //act var result = sut.CreateFinTargetAsync(finTargetCreateDto).Result; //assert Assert.NotEmpty(result.errors); mockUnitOfWork.Verify(x => x.Commit(), Times.Never); } [Theory] [AutoMoqData] public void FailToCreateFinTargetWhenValidationFails(FinTargetCreateDto finTargetCreateDto, [Frozen] Mock<IUnitOfWork> mockUnitOfWork, //[Frozen] Mock<IUserRepository> mockUserRepo, [Frozen] Mock<IFinTargetRepository> mockFinTargetRepo, [Frozen] Mock<IFieldValidatorService> mockFieldValidator, FinTargetService sut) { //arrange var errors = new Dictionary<string, List<string>>(); errors.Add("Error", new List<string>(new string[] { "Error occurred" })); mockFieldValidator.Setup(x => x.Validate(It.IsAny<string>(), It.IsAny<FinTargetCreateDto>() , It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<int>())) .Returns(errors); mockFinTargetRepo.Setup(x => x.ElementExists(It.IsAny<decimal>())).Returns(Task.FromResult(false)); //act var result = sut.CreateFinTargetAsync(finTargetCreateDto).Result; //assert Assert.NotEmpty(result.errors); mockUnitOfWork.Verify(x => x.Commit(), Times.Never); } [Theory] [AutoMoqData] public void UpdateFinTargetWhenValid(FinTargetUpdateDto finTargetUpdateDto, [Frozen] Mock<IUnitOfWork> mockUnitOfWork, //[Frozen] Mock<IUserRepository> mockUserRepo, [Frozen] Mock<IFinTargetRepository> mockFinTargetRepo, [Frozen] Mock<IFieldValidatorService> mockFieldValidator, FinTargetService sut) { //arrange var errors = new Dictionary<string, List<string>>(); var finTargetDto = new FinTargetDto(); mockFieldValidator.Setup(x => x.Validate(It.IsAny<string>(), It.IsAny<FinTargetCreateDto>() , It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<int>())) .Returns(errors); mockFinTargetRepo.Setup(x => x.ElementExists(It.IsAny<decimal>())) .Returns(Task.FromResult(true)); finTargetDto.ProjectId = finTargetUpdateDto.ProjectId; mockFinTargetRepo.Setup(x => x.GetFinTargetByIdAsync(It.IsAny<decimal>())) .Returns(Task.FromResult(finTargetDto)); //act var result = sut.UpdateFinTargetAsync(finTargetUpdateDto).Result; //assert Assert.Empty(result.errors); mockUnitOfWork.Verify(x => x.Commit(), Times.Once); } [Theory] [AutoMoqData] public void FailToUpdateFinTargetWhenDoesntExist(FinTargetUpdateDto finTargetUpdateDto, [Frozen] Mock<IUnitOfWork> mockUnitOfWork, //[Frozen] Mock<IUserRepository> mockUserRepo, [Frozen] Mock<IFinTargetRepository> mockFinTargetRepo, [Frozen] Mock<IFieldValidatorService> mockFieldValidator, FinTargetService sut) { //arrange var errors = new Dictionary<string, List<string>>(); var finTargetDto = new FinTargetDto(); mockFieldValidator.Setup(x => x.Validate(It.IsAny<string>(), It.IsAny<FinTargetCreateDto>() , It.IsAny<Dictionary<string, List<string>>>(), It.IsAny<int>())) .Returns(errors); mockFinTargetRepo.Setup(x => x.ElementExists(It.IsAny<decimal>())) .Returns(Task.FromResult(true)); finTargetDto.ProjectId = 0; //mock will never set the id to zero mockFinTargetRepo.Setup(x => x.GetFinTargetByIdAsync(It.IsAny<decimal>())) .Returns(Task.FromResult(finTargetDto)); //act var result = sut.UpdateFinTargetAsync(finTargetUpdateDto).Result; //assert Assert.Null(result.errors); mockUnitOfWork.Verify(x => x.Commit(), Times.Never); } } }
using System; using MapControl; namespace GoogleForZamelMap { public class GoogleImagesTileLayer : TileLayer { public GoogleImagesTileLayer() { MinZoomLevel = 1; MaxZoomLevel = 21; var random = new Random(0); MapControl.TileImageLoader.HttpUserAgent = string.Format("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:{0}.0) Gecko/{2}{3:00}{4:00} Firefox/{0}.0.{1}", random.Next(3, 14), random.Next(1, 10), random.Next(DateTime.Today.Year - 4, DateTime.Today.Year), random.Next(12), random.Next(30)); TileSource = new GoogleImagesTileSource(); } } }
using Student.Model; namespace Student.Repository.interfaces { public interface IStudentRepository : IGenericRepository<StudentObj> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ITDepartment.Models.Test { public class TestViewModel { public int TestId { get; set; } public int TaskId { get; set; } public string Status { get; set; } public string TaskName { get; set; } } }
using System; using System.Collections.Generic; namespace RMAT3.Models { public class PartyEntityRole { public PartyEntityRole() { PartyEntityRole1 = new List<PartyEntityRole>(); Tasks = new List<EntityTask>(); Tasks1 = new List<EntityTask>(); PartyEntityRolePhones = new List<PartyEntityRolePhone>(); PartyEntityRoleLocations = new List<PartyEntityRoleLocation>(); EntityRoleTypes = new List<EntityRoleType>(); Tasks2 = new List<EntityTask>(); Policies = new List<Policy>(); } public Guid PartyEntityRoleId { get; set; } public string AddedByUserId { get; set; } public DateTime AddTs { get; set; } public string UpdatedByUserId { get; set; } public DateTime UpdatedTs { get; set; } public bool IsActiveInd { get; set; } public string ContactInstructionTxt { get; set; } public int? ContactPrioritySeq { get; set; } public int? DivisionId { get; set; } public DateTime? EffectiveDt { get; set; } public DateTime? ExpirationDt { get; set; } public string TerritoryCd { get; set; } public string ContactPreferenceTypeCd { get; set; } public Guid? ParentPartyEntityRoleId { get; set; } public Guid PartyId { get; set; } public Guid? EntityRoleTypeId { get; set; } public int? ContactPreferenceTypeId { get; set; } public virtual ContactPreferenceType ContactPreferenceType { get; set; } public virtual EntityRoleType EntityRoleType { get; set; } public virtual Party Party { get; set; } public virtual ICollection<PartyEntityRole> PartyEntityRole1 { get; set; } public virtual PartyEntityRole PartyEntityRole2 { get; set; } public virtual ICollection<EntityTask> Tasks { get; set; } public virtual ICollection<EntityTask> Tasks1 { get; set; } public virtual ICollection<PartyEntityRolePhone> PartyEntityRolePhones { get; set; } public virtual ICollection<PartyEntityRoleLocation> PartyEntityRoleLocations { get; set; } public virtual ICollection<EntityRoleType> EntityRoleTypes { get; set; } public virtual ICollection<EntityTask> Tasks2 { get; set; } public virtual ICollection<Policy> Policies { get; set; } } }
using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Threading; using UnityEngine; public class Turret : MonoBehaviour { public virtual void AttackType() { } private List<GameObject> enemys = new List<GameObject>(); //List储存进入攻击范围的敌人序号 void OnTriggerEnter(Collider col) { if (col.tag == "Enemy") { enemys.Add(col.gameObject); //发现敌人,size + 1 } } void OnTriggerExit(Collider col) { if (col.tag == "Enemy") //敌人离开,size - 1 { enemys.Remove(col.gameObject); } } public float attackRateTime = 0.6f;//多少秒攻击一次 private float timer = 0; //计时器 public GameObject bulletPrefab; //子弹 public Transform firePosition; //子弹发射前的位置 public Transform head; //炮管的位置 public bool useLaser = false; //判断攻击方式是否为激光 public float damageRate = 100; //激光每秒的伤害 public LineRenderer laserRenderer; //显示激光 public GameObject laserEffect; //激光命中敌人的特效 void Start() { timer = attackRateTime; } void Update() { if(enemys.Count > 0 && enemys[0] != null) { Vector3 targetPosition = enemys[0].transform.position; targetPosition.y = head.position.y; head.LookAt(targetPosition); } if(useLaser == false) { timer += Time.deltaTime; if(timer >= attackRateTime && enemys.Count > 0) { timer = 0; Attack(); } } else if(enemys.Count > 0) { if (laserRenderer.enabled == false) laserRenderer.enabled = true; laserEffect.SetActive(true); if(enemys[0] == null) { UpdateEnemys(); } if(enemys.Count > 0) { laserRenderer.SetPositions(new Vector3[] { firePosition.position, enemys[0].transform.position }); enemys[0].GetComponent<Enemy>().TakeDamage(damageRate * Time.deltaTime); laserEffect.transform.position = enemys[0].transform.position; Vector3 pos = transform.position; pos.y = enemys[0].transform.position.y; laserEffect.transform.LookAt(pos); } } else { laserEffect.SetActive(false); laserRenderer.enabled = false; } } void Attack() //炮塔攻击第一个敌人 { if(enemys[0] == null) { UpdateEnemys(); } if(enemys.Count > 0) { GameObject bullet = GameObject.Instantiate(bulletPrefab, firePosition.position, firePosition.rotation); bullet.GetComponent<Bullet>().SetTarget(enemys[0].transform); } else { timer = attackRateTime; //重置计时器 } } void UpdateEnemys() //更新enemys数组,取出空指针并将其remove { for(int i = enemys.Count - 1; i >= 0; i--) { if(enemys[i] == null) { enemys.RemoveAt(i); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Threading.Tasks; using System.Data.Common; using System.IO; namespace PocoGenerator { public class Program { public enum CacheType { None, AzureCache, InProcess, Redis } public static string MapPath(string newpath) { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, newpath); } static void PrintUsage() { Console.WriteLine("Usage: sqlbacked.exe <output_path> <namespace> <cache>"); Console.WriteLine("\t\toutput_path: The path where you want the SqlBacked class files to be saved"); Console.WriteLine("\t\tnamespace: The prefix of the namespace for your new SqlBacked classes"); Console.WriteLine("\t\tcache: Either 'none' for no caching methods or 'redis' for caching methods, including the redis adapter"); } static void Main(string[] args) { if (args.Length != 3) { PrintUsage(); return; } string path = args[0]; string namespacePrefix = args[1]; CacheType type = CacheType.None; if (args[2] == "redis") { type = CacheType.Redis; } else if (args[2] == "azure") { type = CacheType.AzureCache; } else if (args[2] == "inproc") { type = CacheType.InProcess; } else if (args[2] != "none") { Console.WriteLine("Unknown / Invalid Cache Type, please use one of ['none', 'redis', 'azure'].\n"); PrintUsage(); return; } bool found = false; foreach (ConnectionStringSettings s in ConfigurationManager.ConnectionStrings) { if (s.Name != "LocalSqlServer") { Console.WriteLine("Writing: {0}", s.Name); BuildClasses(s.ConnectionString, path + "\\" + s.Name, namespacePrefix + "." + s.Name, type); found = true; } } if (!found) { Console.WriteLine("No connection strings were found in the App.config, no SqlBacked objects written"); } File.Copy(MapPath(@"..\Code\ITableBacked.cs"), path + @"\ITableBacked.cs", true); File.Copy(MapPath(@"..\Code\PerformanceLogger.cs"), path + @"\PerformanceLogger.cs", true); File.Copy(MapPath(@"..\Code\ICacheProvider.cs"), path + @"\ICacheProvider.cs", true); File.Copy(MapPath(@"..\Code\CacheConnector.cs"), path + @"\CacheConnector.cs", true); File.Copy(MapPath(@"..\Code\DataResult.cs"), path + @"\DataResult.cs", true); File.Copy(MapPath(@"..\Code\DatabaseConnector.cs"), path + @"\DatabaseConnector.cs", true); File.Copy(MapPath(@"..\Code\DataReaderExtensions.cs"), path + @"\DataReaderExtensions.cs", true); File.Copy(MapPath(@"..\Code\BatchContext.cs"), path + @"\BatchContext.cs", true); if (type == CacheType.Redis) { File.Copy(MapPath(@"..\Code\CacheProviders\RedisCacheProvider.cs"), path + @"\RedisCacheProvider.cs", true); } if (type == CacheType.AzureCache) { File.Copy(MapPath(@"..\Code\CacheProviders\AzureCacheProvider.cs"), path + @"\AzureCacheProvider.cs", true); } if (type == CacheType.InProcess) { File.Copy(MapPath(@"..\Code\CacheProviders\MemoryCacheProvider.cs"), path + @"\MemoryCacheProvider.cs", true); } } private static void BuildClasses(string connectionString, string path, string namespacePrefix, CacheType cacheType) { try { using (var cn = new SqlConnection(connectionString)) { cn.Open(); List<string> schemas = new List<string>(); using (var cmd = new SqlCommand(File.ReadAllText(MapPath(@"..\sql\schemas.sql")), cn)) { using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { schemas.Add(reader["SCHEMA_NAME"] as string); } } } foreach (var schema in schemas) { List<string> tables = new List<string>(); using (var cmd = new SqlCommand(File.ReadAllText(MapPath(@"..\sql\tables.sql")), cn)) { cmd.Parameters.AddWithValue("@TABLE_SCHEMA", schema); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string tableName = reader["TABLE_NAME"] as string; SqlBackedTable t = new SqlBackedTable(connectionString, namespacePrefix, schema, tableName, cacheType != CacheType.None); string directoryPath = string.Format("{0}\\{1}\\", path, schema); string classPath = string.Format("{0}{1}.cs", directoryPath, tableName); Directory.CreateDirectory(directoryPath); Console.WriteLine("Wrote: " + classPath); File.WriteAllText(classPath, t.GetClass()); } } } } } } catch (Exception ex) { Console.WriteLine("An exception occurred"); Console.WriteLine(ex.Message); Console.WriteLine("---------"); Console.WriteLine(ex.StackTrace); } } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class Search_PurchaseOrderParameter { public DateTime? DateFrom; public DateTime? DateTo; public PurchaseOrderStatus? Status; public String ReferenceLike; public Int32 EntriesPerPage; public Int32 PageNumber; public List<Guid> Location; public List<Guid> Supplier; } }
using System; using System.IO; using System.CodeDom; namespace Mono.VisualC.Code.Atoms { public class Property : CodeAtom { public string Name { get; set; } public Method Getter { get; set; } public Method Setter { get; set; } public Property (string name) { Name = name; } internal protected override object InsideCodeTypeDeclaration (CodeTypeDeclaration decl) { // if getter is omitted, just output the setter like a method if (decl.IsInterface || Getter == null) { if (Getter != null) Getter.Visit (decl); if (Setter != null) Setter.Visit (decl); return null; } else if (!decl.IsClass) return null; var prop = new CodeMemberProperty { Name = this.Name, // FIXME: For now, no properties will be virtual... change this at some point? Attributes = MemberAttributes.Public | MemberAttributes.Final, Type = Getter.ReturnTypeReference }; Getter.Visit (prop.GetStatements); if (Setter != null) Setter.Visit (prop.SetStatements); decl.Members.Add (prop); return prop; } public override void Write (TextWriter writer) { throw new NotImplementedException (); } } }
namespace BLL.Infrastructure.ComplexRequest.Products { public enum ProductProperty { Name, Brand, Category, Amount, Price } }
// ---------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="ObjectType.cs" company="David Eiwen"> // Copyright © 2016 by David Eiwen // </copyright> // <author>David Eiwen</author> // <summary> // This file contains the ObjectType enum. // </summary> // ---------------------------------------------------------------------------------------------------------------------------------------- namespace IndiePortable.Formatter.Protocol1_1_0_0 { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public enum ObjectType : byte { RefType = 0x00, Primitive = 0x01, Enum = 0x02, ValueType = 0x03, String = 0x04, Null = 0x05 } }
using System.Collections.Concurrent; using Umbraco.Core.Models.Entities; using Umbraco.Core.Persistence.Dtos; namespace Umbraco.Core.Persistence.Mappers { [MapperFor(typeof (IUmbracoEntity))] public sealed class UmbracoEntityMapper : BaseMapper { private static readonly ConcurrentDictionary<string, DtoMapModel> PropertyInfoCacheInstance = new ConcurrentDictionary<string, DtoMapModel>(); internal override ConcurrentDictionary<string, DtoMapModel> PropertyInfoCache => PropertyInfoCacheInstance; protected override void BuildMap() { CacheMap<IUmbracoEntity, NodeDto>(src => src.Id, dto => dto.NodeId); CacheMap<IUmbracoEntity, NodeDto>(src => src.CreateDate, dto => dto.CreateDate); CacheMap<IUmbracoEntity, NodeDto>(src => src.Level, dto => dto.Level); CacheMap<IUmbracoEntity, NodeDto>(src => src.ParentId, dto => dto.ParentId); CacheMap<IUmbracoEntity, NodeDto>(src => src.Path, dto => dto.Path); CacheMap<IUmbracoEntity, NodeDto>(src => src.SortOrder, dto => dto.SortOrder); CacheMap<IUmbracoEntity, NodeDto>(src => src.Name, dto => dto.Text); CacheMap<IUmbracoEntity, NodeDto>(src => src.Trashed, dto => dto.Trashed); CacheMap<IUmbracoEntity, NodeDto>(src => src.Key, dto => dto.UniqueId); CacheMap<IUmbracoEntity, NodeDto>(src => src.CreatorId, dto => dto.UserId); } } }
using HardcoreHistoryBlog.Data; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace HardcoreHistoryBlog.ViewModels { public class PostViewModel { public int Id { get; set; } [Required(ErrorMessage = "Title is required")] public virtual string Title { get; set; } = ""; public virtual string Short_Description { get; set; } = ""; public string CurrentImage { get; set; } = ""; public IFormFile Image { get; set; } public virtual string Content { get; set; } = ""; public string Category { get; set; } = ""; public string Tags { get; set; } = ""; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GlobalDevelopment.Interfaces { public interface IPost { string postMessage { get; set; } string ImageSrc { get; set; } string PostUrl { get; set; } DateTime CreatedDate { get; set; } string OwnerName { get; set; } } }
using FLS.Business; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FuelSupervisorSetting.ViewModel { public delegate void PersistenceErrorHandler(InterpolationTabDataProvider dataProvider, Exception e); public class InterpolationTabDataProvider { IInterpolationTabDAL dataAccessLayer; long currTankId; public InterpolationTabDataProvider() { dataAccessLayer = new InterpolationTabDAL(); } public InterpolationTabUIObjects GetInterpolationTab(long tankid) { //if (!(String.IsNullOrEmpty(fileName))) //{ // dataAccessLayer.ImportInterpolationTab(fileName, pumpid); //} currTankId = tankid; // populate our list of customers from the data access layer InterpolationTabUIObjects iTabObjs = new InterpolationTabUIObjects(); List<InterpolationRecord> iTabDataObjects = dataAccessLayer.GetInterpolationTab(tankid); foreach (InterpolationRecord iTabDataObject in iTabDataObjects) { // create a business object from each data object iTabObjs.Add(new InterpolationTabUIObject(iTabDataObject)); } iTabObjs.ItemEndEdit += new ItemEndEditEventHandler(InterpolationTabItemEndEdit); iTabObjs.CollectionChanged += new NotifyCollectionChangedEventHandler(InterpolationTabCollectionChanged); return iTabObjs; } public InterpolationTabUIObjects ImportInterpolationTab(long tankid, String fileName) { if ((String.IsNullOrEmpty(fileName))) return null; try { dataAccessLayer.ImportInterpolationTab(fileName, tankid); return GetInterpolationTab(tankid); } catch (Exception ex) { App.Log.LogException(ex); throw; } } void InterpolationTabCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Remove) { try { foreach (object item in e.OldItems) { InterpolationTabUIObject iTabObject = item as InterpolationTabUIObject; // use the data access layer to delete the wrapped data object dataAccessLayer.DeleteInterpolationTab(iTabObject.GetDataObject()); } } catch (Exception ex) { App.Log.LogException(ex); if (PersistenceError != null) { PersistenceError(this, ex); } } } } void InterpolationTabItemEndEdit(IEditableObject sender) { InterpolationTabUIObject iTabObject = sender as InterpolationTabUIObject; try { if (iTabObject.TankId == 0) { iTabObject.TankId = currTankId; } // use the data access layer to update the wrapped data object dataAccessLayer.UpdateInterpolationTab(iTabObject.GetDataObject()); } catch (Exception ex) { App.Log.LogException(ex); if (PersistenceError != null) { PersistenceError(this, ex); } } } public static event PersistenceErrorHandler PersistenceError; } }
using Godot; using System; using AdventureGame; public class BasicCharacter : KinematicBody2D { [Export] public float WalkSpeed = 80.0f; [Export] public float FreezeSpeed = 10.0f; private Globals _globals; private struct AxisMapping { public string ActionName; public Vector2 Axis; public AxisMapping(string actionName, Vector2 axis) { ActionName = actionName; Axis = axis; } } private readonly AxisMapping[] _axisMappings = { new AxisMapping("character_move_left", new Vector2(-1.0f, 0.0f)), new AxisMapping("character_move_right", new Vector2(1.0f, 0.0f)), new AxisMapping("character_move_up", new Vector2(0.0f, -1.0f)), new AxisMapping("character_move_down", new Vector2(0.0f, 1.0f)) }; public override void _Ready() { _globals = GetNode("/root/Globals") as Globals; } public override void _Process(float delta) { CheckHeat(delta); if (Input.IsActionPressed("character_primary_interact")) { _checkInteractions(); } } public override void _PhysicsProcess(float delta) { Vector2 axisInput = new Vector2(0.0f, 0.0f); foreach (AxisMapping axisMapping in _axisMappings) { if (Input.IsActionPressed(axisMapping.ActionName)) { axisInput += axisMapping.Axis; } } axisInput = axisInput.Normalized(); Vector2 velocity = axisInput * WalkSpeed; KinematicCollision2D collision = MoveAndCollide(velocity * delta); if (collision != null) { Node2D collider = collision.Collider as Node2D; if (collider != null && collider.IsInGroup("pushable")) { IPushable pushedObject = collider as IPushable; pushedObject?.TryPush(collision.Normal, delta); } velocity = velocity.Slide(collision.Normal); MoveAndCollide(velocity * delta); } } private void _checkInteractions() { var interactables = GetTree().GetNodesInGroup("interactive"); foreach (Node node in interactables) { IInteractive interactable = node as IInteractive; if (interactable != null) { Area2D interactiveArea = interactable.GetInteractiveArea(); if (interactiveArea.OverlapsBody(this)) { interactable.TryInteract(this); } } } } private void CheckHeat(float delta) { var fireplaces = GetTree().GetNodesInGroup("fireplace"); // Defines how fast (in % of FreezeSpeed) the player's health will decay. // Take the smallest value - freeze factor is the percent distance of the player // from the inner radius of the fire to the outer radius. // Valid between -1.0f and 1.0f. // A value of less than 0.0f indicates that the player is being healed // in which case, the max heal speed will be set according to that fireplace's // heal speed. float minFreezeFactor = 1.0f; // Heal float maxHealSpeed = 0.0f; foreach (Node node in fireplaces) { Fireplace fireplace = node as Fireplace; if (fireplace != null) { float distance = fireplace.GlobalPosition.DistanceTo(GlobalPosition); // Note - multiple fires healing the player at once could be weird! // Not currently handled if (fireplace.HealEnabled && distance < fireplace.HealInnerRadius) { minFreezeFactor = -1.0f; maxHealSpeed = fireplace.HealSpeed; break; } else if (fireplace.HealEnabled && distance < fireplace.HealOuterRadius) { float freezeFactor = -(distance - fireplace.HealInnerRadius) / (fireplace.HealOuterRadius - fireplace.HealInnerRadius); if (freezeFactor < minFreezeFactor) { minFreezeFactor = freezeFactor; maxHealSpeed = fireplace.HealSpeed; } } else if (distance < fireplace.HeatInnerRadius) { if (minFreezeFactor > 0.0f) { minFreezeFactor = 0.0f; } } else if (distance < fireplace.HeatOuterRadius) { float freezeFactor = (distance - fireplace.HeatInnerRadius) / (fireplace.HeatOuterRadius - fireplace.HeatInnerRadius); if (freezeFactor < minFreezeFactor) { minFreezeFactor = freezeFactor; } } } } if (minFreezeFactor > 0.0f) { _globals.PlayerHealth -= FreezeSpeed * minFreezeFactor * delta; } else { _globals.PlayerHealth -= maxHealSpeed * minFreezeFactor * delta; } } public Node2D GetCarryAttachPoint() { return GetNode("carry_attach_point") as Node2D; } }
using System; using System.Collections; using System.Collections.Generic; using Atoms; using Zenject; using UnityEngine; using ModestTree.Util; using uMVC.Metadata; using System.Reflection; namespace uMVC { public interface IApplication { IApplication RegisterPresenter(String url, Type type); IApplication RegisterRoute<A>(String url) where A : MonoBehaviour; A SetEnv<A>(); IApplication BackInHistoryOnEscapeButton(bool value); IApplication UseLayout(bool value); } public interface IRouter { IApplication app { get; } void Back(); void GoTo(String url, Dictionary<string, object> parameters = null, object body = null, String layoutUrl = null, Dictionary<String, object> layoutParameters = null, object layoutBody = null, bool saveInHistory = true); void GoTo(IRequest request, bool saveInHistory = true); void ClearCurrentView(); } public interface IRequest { String path { get; } Dictionary<String, object> parameters { get; } object body { get; } ILayoutRequest layoutRequest { get; set; } string fullPath { get; } } public interface ILayoutRequest { String path { get; set; } Dictionary<String, object> parameters { get; set; } object body { get; set; } string fullPath { get; } } public class Request : IRequest { public object body { get; private set; } public Dictionary<string, object> parameters { get; private set; } public string path { get; private set; } public ILayoutRequest layoutRequest { get; set; } public Request(string url = null, Dictionary<string, object> parameters = null, object body = null, string layoutUrl = null, Dictionary<string, object> layoutParameters = null, object layoutBody = null) { this.path = url; this.parameters = parameters != null ? parameters : new Dictionary<string, object>(); this.body = body; this.layoutRequest = new LayoutRequest(layoutUrl, layoutParameters, layoutBody); } public string fullPath { get { return path != null ? "presenters/" + path : null; } } } public class LayoutRequest : ILayoutRequest { public object body { get; set; } public Dictionary<string, object> parameters { get; set; } public string path { get; set; } public LayoutRequest(string url = null, Dictionary<string, object> parameters = null, object body = null) { this.path = url; this.parameters = parameters != null ? parameters : new Dictionary<string, object>(); this.body = body; } public string fullPath { get { return path != null ? "layouts/" + path : null; } } } public interface IController { void OnDestroy(); } public abstract class MVCPresenter : MonoBehaviour, IEnumLoader, IPresenter { public virtual Transform inner3D { get { return root3D; } } public virtual RectTransform innerUI { get { return rootUI; } } public virtual bool ready { get { return true; } } public virtual Transform root3D { get { return this.transform; } } public virtual RectTransform rootUI { get { return this.transform.RectTransform(); } } public void Load(IEnumerable e) { e.Start(this); } public abstract void OnDestroy(); public void SetChild(MVCPresenter child) { child.transform.SetParent(this.transform); child.root3D.ResetTransformUnder(this.root3D); child.rootUI.ResetRectTransformUnder(this.innerUI); } } public interface IPresenter { Transform root3D { get; } RectTransform rootUI { get;} RectTransform innerUI { get; } Transform inner3D { get; } void OnDestroy(); } public interface ILayoutPresenter : IPresenter { } public class BrokenLayoutPresenter : ILayoutPresenter { public Transform inner3D { get { throw new NotImplementedException(); } } public RectTransform innerUI { get { throw new NotImplementedException(); } } public Transform root3D { get { throw new NotImplementedException(); } } public RectTransform rootUI { get { throw new NotImplementedException(); } } public void OnDestroy() { throw new NotImplementedException(); } } public interface IRoute { string path { get; set; } string layoutPath { get; set; } Type type { get; set; } string fullLayoutPath { get; } ScreenOrientation orientation { get; set; } string fullPath { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ws2008.MODEL; using Ws2008.DAL; namespace Ws2008.BLL { public class UserBLL { //添加用户 public int AddUser(UserMODEL model) { return new UserDAL().AddUser(model); } public UserMODEL GetUserByName(string username) { return new UserDAL().GetUserByName(username); } /// <summary> /// 根据用户名判断是否有重名 /// </summary> /// <param name="username"></param> /// <returns></returns> public bool IsExistsByUserName(string userName) { return new UserDAL().IsExistsByUserName(userName); } /// <summary> /// 根据用户名ID判断是否有此用户 /// </summary> /// <param name="username"></param> /// <returns></returns> public bool IsExistsByUserID(int userID) { return new UserDAL().IsExistsByUserID(userID); } /// <summary> /// 根据邮箱检测是否邮箱己存在 /// </summary> /// <param name="email"></param> /// <returns></returns> public bool IsExistsByEmail(string email) { return new UserDAL().IsExistsByEmail(email); } } }
 namespace Service.Contract { /// <summary> /// Represents a duplex channel provider. /// </summary> public interface IDuplexChannelProvider { /// <summary> /// Gets the command channel. /// </summary> /// <param name="implementation">The implementation.</param> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <returns>A client side proxy of <see cref="Service.ICommandContract" />.</returns> ICommandContract GetCommandChannel(object implementation, string endpointConfigurationName); /// <summary> /// Gets the query channel. /// </summary> /// <param name="implementation">The implementation.</param> /// <param name="endpointConfigurationName">Name of the endpoint configuration.</param> /// <returns>A client side proxy of <see cref="Service.IQueryContract" />.</returns> IQueryContract GetQueryChannel(object implementation, string endpointConfigurationName); } }
using CMS_Tools.Lib; using CMS_Tools.Model; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.SessionState; namespace CMS_Tools.Apis { /// <summary> /// Summary description for API_Customer /// </summary> public class API_Customer : IHttpHandler, IRequiresSessionState { UserInfo accountInfo; Result result = new Result(); List<Constants.USER_PERMISSTIONS> uSER_RULEs = new List<Constants.USER_PERMISSTIONS>(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json;charset=utf-8"; try { #region CHECK ACCOUNT LOGIN accountInfo = Account.GetAccountInfo(context); if (accountInfo == null) { result.status = Constants.NUMBER_CODE.ACCOUNT_NOT_LOGIN; result.msg = Constants.NUMBER_CODE.ACCOUNT_NOT_LOGIN.ToString(); context.Response.Write(JsonConvert.SerializeObject(result)); return; } #endregion Constants.REQUEST_TYPE requestType = (Constants.REQUEST_TYPE)int.Parse(context.Request.Form["type"]); switch (requestType) { case Constants.REQUEST_TYPE.API_GET_GIACONGDONGDAN: API_GET_GIACONGDONGDAN(context); break; case Constants.REQUEST_TYPE.API_FIND_CUSTOMERS_BY_ORDER: API_FIND_CUSTOMERS_BY_ORDER(context); break; case Constants.REQUEST_TYPE.API_GET_CUSTOMER_BY_CODE: API_GET_CUSTOMER_BY_CODE(context); break; case Constants.REQUEST_TYPE.API_FIND_CUSTOMERS: API_FIND_CUSTOMERS(context); break; case Constants.REQUEST_TYPE.API_GET_LOAISONG: API_GET_LOAISONG(context); break; case Constants.REQUEST_TYPE.API_GET_CHATLIEU: API_GET_CHATLIEU(context); break; case Constants.REQUEST_TYPE.API_GET_KIEUTHUNG: API_GET_KIEUTHUNG(context); break; case Constants.REQUEST_TYPE.API_GET_LOAIDONHANG: API_GET_LOAIDONHANG(context); break; case Constants.REQUEST_TYPE.API_GET_LOAIHINHSX: API_GET_LOAIHINHSX(context); break; case Constants.REQUEST_TYPE.API_GET_NHACUNGCAP: API_GET_NHACUNGCAP(context); break; case Constants.REQUEST_TYPE.API_GET_CUSTOMER: API_GET_CUSTOMER(context); break; case Constants.REQUEST_TYPE.API_GET_COUNTRY: API_GET_COUNTRY(context); break; case Constants.REQUEST_TYPE.API_GET_PROVINCE: API_GET_PROVINCE(context); break; case Constants.REQUEST_TYPE.API_CREATE_CUSTOMER: API_CREATE_CUSTOMER(context); break; case Constants.REQUEST_TYPE.API_UPDATE_CUSTOMER: API_UPDATE_CUSTOMER(context); break; default: result.status = Constants.NUMBER_CODE.REQUEST_NOT_FOUND; result.msg = Constants.NUMBER_CODE.REQUEST_NOT_FOUND.ToString(); context.Response.Write(JsonConvert.SerializeObject(result)); break; } } catch (Exception ex) { Logs.SaveError("ERROR " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); context.Response.Write(JsonConvert.SerializeObject(result)); } } private void API_GET_GIACONGDONGDAN(HttpContext context) { try { if (context.Session["API_GET_GIACONGDONGDAN"] == null || ((DateTime)context.Session["API_GET_GIACONGDONGDAN"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetGiaCongDongDan"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_GIACONGDONGDAN: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_GIACONGDONGDAN"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_FIND_CUSTOMERS_BY_ORDER(HttpContext context) { try { if (context.Session["API_FIND_CUSTOMERS_BY_ORDER"] == null || ((DateTime)context.Session["API_FIND_CUSTOMERS_BY_ORDER"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { FindCustomerInfo send = new FindCustomerInfo() { param = accountInfo.AccountId.ToString() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/FindCustomersByOrder"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_FIND_CUSTOMERS_BY_ORDER: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_FIND_CUSTOMERS_BY_ORDER"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_CUSTOMER_BY_CODE(HttpContext context) { try { string param = context.Request.Form["param"]; if (context.Session["API_GET_CUSTOMER_BY_CODE"] == null || ((DateTime)context.Session["API_GET_CUSTOMER_BY_CODE"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { if (!string.IsNullOrEmpty(param)) { param = context.Request.Form["param"].Split('-')[0].Trim(); GetCustomerInfo send = new GetCustomerInfo() { customerCode = param }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetCustomerDetailByCode"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.DATA_NULL; result.msg = "Vui lòng nhập thông tin khách hàng!"; } } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_CUSTOMER_BY_CODE: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_CUSTOMER_BY_CODE"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_FIND_CUSTOMERS(HttpContext context) { try { string param = context.Request.Form["param"]; if (context.Session["API_FIND_CUSTOMERS"] == null || ((DateTime)context.Session["API_FIND_CUSTOMERS"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { if (!string.IsNullOrEmpty(param)) { param = UtilClass.RemoveSign4VietnameseString(param); FindCustomerInfo send = new FindCustomerInfo() { param = param }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/FindCustomers"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.DATA_NULL; result.msg = "Vui lòng nhập thông tin khách hàng!"; } } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_FIND_CUSTOMERS: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_FIND_CUSTOMERS"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_LOAISONG(HttpContext context) { try { if (context.Session["API_GET_LOAISONG"] == null || ((DateTime)context.Session["API_GET_LOAISONG"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetLoaiSong"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_LOAISONG: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_LOAISONG"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_CHATLIEU(HttpContext context) { try { if (context.Session["API_GET_CHATLIEU"] == null || ((DateTime)context.Session["API_GET_CHATLIEU"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { string nhacungcap_id = context.Request.Form["nhaCungCap_ID"]; if (!string.IsNullOrEmpty(nhacungcap_id)) { GetChatLieuInfo send = new GetChatLieuInfo() { nhacungcap_ID = int.Parse(nhacungcap_id) }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetChatLieu"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.DATA_NULL; result.msg = "Vui lòng chọn nhà cung cấp!"; } } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_CHATLIEU: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_CHATLIEU"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_KIEUTHUNG(HttpContext context) { try { if (context.Session["API_GET_KIEUTHUNG"] == null || ((DateTime)context.Session["API_GET_KIEUTHUNG"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetKieuThung"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_KIEUTHUNG: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_KIEUTHUNG"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_LOAIDONHANG(HttpContext context) { try { if (context.Session["API_GET_LOAIDONHANG"] == null || ((DateTime)context.Session["API_GET_LOAIDONHANG"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetLoaiDonHang"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_LOAIDONHANG: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_LOAIDONHANG"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_LOAIHINHSX(HttpContext context) { try { if (context.Session["API_GET_LOAIHINHSX"] == null || ((DateTime)context.Session["API_GET_LOAIHINHSX"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetLoaiHinhSX"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_LOAIHINHSX: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_LOAIHINHSX"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_NHACUNGCAP(HttpContext context) { try { if (context.Session["API_GET_NHACUNGCAP"] == null || ((DateTime)context.Session["API_GET_NHACUNGCAP"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetNhaCungCap"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_NHACUNGCAP: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_NHACUNGCAP"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_CUSTOMER(HttpContext context) { try { if (context.Session["API_GET_CUSTOMER"] == null || ((DateTime)context.Session["API_GET_CUSTOMER"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { if (!string.IsNullOrEmpty(context.Request.Form["customerID"])) { string param = context.Request.Form["customerID"]; GetCustomerInfo send = new GetCustomerInfo() { customerCode = param }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetCustomerDetail"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.CUSTOMER_ID_INVALID; result.msg = Constants.NUMBER_CODE.CUSTOMER_ID_INVALID.ToString(); } } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_CUSTOMER: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_CUSTOMER"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_COUNTRY(HttpContext context) { try { if (context.Session["API_GET_COUNTRY"] == null || ((DateTime)context.Session["API_GET_COUNTRY"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetCountry"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_COUNTRY: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_COUNTRY"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_GET_PROVINCE(HttpContext context) { try { if (context.Session["API_GET_PROVINCE"] == null || ((DateTime)context.Session["API_GET_PROVINCE"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { RequestInfo send = new RequestInfo() { clientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/GetProvince"); context.Response.Write(responseData); return; } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_GET_PROVINCE: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_GET_PROVINCE"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_CREATE_CUSTOMER(HttpContext context) { try { if (context.Session["API_CREATE_CUSTOMER"] == null || ((DateTime)context.Session["API_CREATE_CUSTOMER"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { short KM = 0, KM1 = 0, KM2 = 0; string json = context.Request.Form["json"]; var cus = JsonConvert.DeserializeObject<Customer>(json); if (string.IsNullOrEmpty(cus.CompanyName)) { result.status = Constants.NUMBER_CODE.COMPANY_NAME_IS_NULL; result.msg = "Tên CTY không được bỏ trống!"; } else { if (!string.IsNullOrEmpty(cus.Address)) { if(cus.City == 0) { result.status = Constants.NUMBER_CODE.CITY_IS_NULL; result.msg = "Vui lòng chọn tỉnh thành!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } if (cus.Country == 0) { result.status = Constants.NUMBER_CODE.COUNTRY_IS_NULL; result.msg = "Vui lòng chọn quốc gia!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.Address1)) { if (cus.City1 == 0) { result.status = Constants.NUMBER_CODE.CITY_IS_NULL; result.msg = "Vui lòng chọn tỉnh thành!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } if (cus.Country1 == 0) { result.status = Constants.NUMBER_CODE.COUNTRY_IS_NULL; result.msg = "Vui lòng chọn quốc gia!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.Address2)) { if (cus.City2 == 0) { result.status = Constants.NUMBER_CODE.CITY_IS_NULL; result.msg = "Vui lòng chọn tỉnh thành!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } if (cus.Country2 == 0) { result.status = Constants.NUMBER_CODE.COUNTRY_IS_NULL; result.msg = "Vui lòng chọn quốc gia!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.KM)) { if (!short.TryParse(cus.KM, out KM) || KM < 0) { result.status = Constants.NUMBER_CODE.KM_INVALID; result.msg = "Nhập số Km không chính xác!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.KM1)) { if (!short.TryParse(cus.KM1, out KM1) || KM1 < 0) { result.status = Constants.NUMBER_CODE.KM_INVALID; result.msg = "Nhập số Km không chính xác!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.KM2)) { if (!short.TryParse(cus.KM2, out KM2) || KM2 < 0) { result.status = Constants.NUMBER_CODE.KM_INVALID; result.msg = "Nhập số Km không chính xác!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } CreateCustomerInfo send = new CreateCustomerInfo() { Address = cus.Address != null ? cus.Address.Trim() : "", City = cus.City, Country = cus.Country, Address1 = cus.Address1 != null ? cus.Address1.Trim() : "", City1 = cus.City1, Country1 = cus.Country1, Address2 = cus.Address2 != null ? cus.Address2.Trim() : "", City2 = cus.City2, Country2 = cus.Country2, CompanyName = cus.CompanyName, Contact = cus.Contact != null ? cus.Contact.Trim() : "", Email = cus.Email != null ? cus.Email.Trim() : "", Phone = cus.Phone != null ? cus.Phone.Trim() : "", publickey = Constants.API_PUBLICKEY, serviceID = Constants.API_SERVICEID, sign = Encryptor.GeneralSignature(Constants.API_SECRETKEY, new List<string>() { Constants.API_SERVICEID.ToString(), Constants.API_PUBLICKEY, cus.CompanyName }), TaxCode = cus.TaxCode != null ? cus.TaxCode : "", UserID = accountInfo.AccountId, UserName = accountInfo.UserName, Status = cus.Status, KM = KM, KM1 = KM1, KM2 = KM2, Loaidon_ID = cus.Loaidon_ID, LoaiHinhSX_ID = cus.LoaiHinhSX_ID, ClientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/CreateCustomer"); context.Response.Write(responseData); return; } } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_CREATE_CUSTOMER: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_CREATE_CUSTOMER"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } private void API_UPDATE_CUSTOMER(HttpContext context) { try { if (context.Session["API_UPDATE_CUSTOMER"] == null || ((DateTime)context.Session["API_UPDATE_CUSTOMER"] - DateTime.Now).TotalMilliseconds < Constants.TIME_REQUEST) { string json = context.Request.Form["json"]; var cus = JsonConvert.DeserializeObject<Customer>(json); short KM = 0, KM1 = 0, KM2 = 0; if (string.IsNullOrEmpty(cus.CompanyName)) { result.status = Constants.NUMBER_CODE.COMPANY_NAME_IS_NULL; result.msg = "Tên CTY không được bỏ trống!"; } else { if (!string.IsNullOrEmpty(cus.Address)) { if(cus.City == 0) { result.status = Constants.NUMBER_CODE.CITY_IS_NULL; result.msg = "Vui lòng chọn tỉnh thành!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } if (cus.Country == 0) { result.status = Constants.NUMBER_CODE.COUNTRY_IS_NULL; result.msg = "Vui lòng chọn quốc gia!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.Address1)) { if (cus.City1 == 0) { result.status = Constants.NUMBER_CODE.CITY_IS_NULL; result.msg = "Vui lòng chọn tỉnh thành!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } if (cus.Country1 == 0) { result.status = Constants.NUMBER_CODE.COUNTRY_IS_NULL; result.msg = "Vui lòng chọn quốc gia!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.Address2)) { if (cus.City2 == 0) { result.status = Constants.NUMBER_CODE.CITY_IS_NULL; result.msg = "Vui lòng chọn tỉnh thành!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } if (cus.Country2 == 0) { result.status = Constants.NUMBER_CODE.COUNTRY_IS_NULL; result.msg = "Vui lòng chọn quốc gia!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.KM)) { if(!short.TryParse(cus.KM, out KM) || KM < 0) { result.status = Constants.NUMBER_CODE.KM_INVALID; result.msg = "Nhập số Km không chính xác!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.KM1)) { if (!short.TryParse(cus.KM1, out KM1) || KM1 < 0) { result.status = Constants.NUMBER_CODE.KM_INVALID; result.msg = "Nhập số Km không chính xác!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } if (!string.IsNullOrEmpty(cus.KM2)) { if (!short.TryParse(cus.KM2, out KM2) || KM2 < 0) { result.status = Constants.NUMBER_CODE.KM_INVALID; result.msg = "Nhập số Km không chính xác!"; context.Response.Write(JsonConvert.SerializeObject(result)); return; } } CreateCustomerInfo send = new CreateCustomerInfo() { customerID = cus.CustomerID, Address = cus.Address != null ? cus.Address.Trim() : "", City = cus.City, Country = cus.Country, Address1 = cus.Address1 != null ? cus.Address1.Trim() : "", City1 = cus.City1, Country1 = cus.Country1, Address2 = cus.Address2 != null ? cus.Address2.Trim() : "", City2 = cus.City2, Country2 = cus.Country2, CompanyName = cus.CompanyName, Contact = cus.Contact != null ? cus.Contact.Trim() : "", Email = cus.Email != null ? cus.Email.Trim() : "", Phone = cus.Phone != null ? cus.Phone.Trim() : "", publickey = Constants.API_PUBLICKEY, serviceID = Constants.API_SERVICEID, sign = Encryptor.GeneralSignature(Constants.API_SECRETKEY, new List<string>() { Constants.API_SERVICEID.ToString(), Constants.API_PUBLICKEY, cus.CompanyName }), TaxCode = cus.TaxCode != null ? cus.TaxCode : "", UserID = accountInfo.AccountId, UserName = accountInfo.UserName, Status = cus.Status, KM = KM, KM1 = KM1, KM2 = KM2, Loaidon_ID = cus.Loaidon_ID, LoaiHinhSX_ID = cus.LoaiHinhSX_ID, ClientIP = UtilClass.GetIPAddress() }; PayloadApi p = new PayloadApi() { clientIP = UtilClass.GetIPAddress(), data = Encryptor.EncryptString(JsonConvert.SerializeObject(send), Constants.API_SECRETKEY) }; var responseData = UtilClass.SendPost(JsonConvert.SerializeObject(p), Constants.API_URL + "/api/v1/Customer/UpdateCustomer"); context.Response.Write(responseData); return; } } else { result.status = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER; result.msg = Constants.NUMBER_CODE.ERROR_CONNECT_SERVER.ToString(); } } catch (Exception ex) { Logs.SaveError("ERROR API_UPDATE_CUSTOMER: " + ex); result.status = Constants.NUMBER_CODE.ERROR_EX; result.msg = Constants.NUMBER_CODE.ERROR_EX.ToString(); } finally { context.Session["API_UPDATE_CUSTOMER"] = DateTime.Now; } context.Response.Write(JsonConvert.SerializeObject(result)); } public bool IsReusable { get { return false; } } } public class CreateCustomerInfo { public int customerID; public string publickey; public short serviceID; public string CompanyName; public string TaxCode; public string Address; public short City; public short Country; public string Address1; public short City1; public short Country1; public string Address2; public short City2; public short Country2; public string Email; public string Phone; public string Contact; public int UserID; public string UserName; public byte Status; public short KM; public short KM1; public short KM2; public byte Loaidon_ID; public int LoaiHinhSX_ID; public string ClientIP; public string sign; } public struct Customer { public int CustomerID; public string CompanyName; public string TaxCode; public string Email; public string Phone; public string Contact; public byte Status; public string Address; public short City; public short Country; public string Address1; public short City1; public short Country1; public string Address2; public short City2; public short Country2; public string KM; public string KM1; public string KM2; public byte Loaidon_ID; public int LoaiHinhSX_ID; } public class GetChatLieuInfo { public int nhacungcap_ID; } public class GetCustomerInfo { public string customerCode; } public class FindCustomerInfo { public string param; } public class RequestInfo { public string clientIP; } public abstract class BaseApiInfo { public string publickey = Constants.API_PUBLICKEY; public short serviceID = Constants.API_SERVICEID; } }
// https://www.hackerrank.com/challenges/birthday-cake-candles/problem using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static int birthdayCakeCandles(int n, int[] ar) { int max = ar.Max(); int counter = 0; for (int i = 0; i < ar.Length; i++) { if (ar[i] == max) { counter++; } } return counter; } static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] ar_temp = Console.ReadLine().Split(' '); int[] ar = Array.ConvertAll(ar_temp,Int32.Parse); int result = birthdayCakeCandles(n, ar); Console.WriteLine(result); } }
using System; using System.Collections.Generic; using System.Text; using TesteC_Sharp.Interfaces; using static TesteC_Sharp.Model.Enumerators; namespace TesteC_Sharp.Model { public class Sale : ISale { private Dictionary<SaleStatus, List<Vehicle>> vehiclesAndSaleStatus = new Dictionary<SaleStatus, List<Vehicle>>(); private List<Vehicle> allVehicles = new List<Vehicle>(); public Dictionary<SaleStatus, List<Vehicle>> SaleAnVehicle(double saleValue, Vehicle vehicle) { VehicleSale(saleValue, vehicle); return vehiclesAndSaleStatus; } private void VehicleSale(double saleValue, Vehicle vehicle) { if (saleValue < vehicle.MinValue) { vehiclesAndSaleStatus.Add(SaleStatus.rejectedByMinValue, allVehicles.FindAll(x => x.MinValue >= saleValue)); } vehiclesAndSaleStatus.Add(SaleStatus.sold,new List<Vehicle>()); } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_Screen : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { Screen o = new Screen(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SetResolution_s(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 3) { int num2; LuaObject.checkType(l, 1, out num2); int num3; LuaObject.checkType(l, 2, out num3); bool flag; LuaObject.checkType(l, 3, out flag); Screen.SetResolution(num2, num3, flag); LuaObject.pushValue(l, true); result = 1; } else if (num == 4) { int num4; LuaObject.checkType(l, 1, out num4); int num5; LuaObject.checkType(l, 2, out num5); bool flag2; LuaObject.checkType(l, 3, out flag2); int num6; LuaObject.checkType(l, 4, out num6); Screen.SetResolution(num4, num5, flag2, num6); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_resolutions(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_resolutions()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_currentResolution(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_currentResolution()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_width(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_width()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_height(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_height()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_dpi(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_dpi()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_fullScreen(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_fullScreen()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_fullScreen(IntPtr l) { int result; try { bool fullScreen; LuaObject.checkType(l, 2, out fullScreen); Screen.set_fullScreen(fullScreen); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_autorotateToPortrait(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_autorotateToPortrait()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_autorotateToPortrait(IntPtr l) { int result; try { bool autorotateToPortrait; LuaObject.checkType(l, 2, out autorotateToPortrait); Screen.set_autorotateToPortrait(autorotateToPortrait); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_autorotateToPortraitUpsideDown(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_autorotateToPortraitUpsideDown()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_autorotateToPortraitUpsideDown(IntPtr l) { int result; try { bool autorotateToPortraitUpsideDown; LuaObject.checkType(l, 2, out autorotateToPortraitUpsideDown); Screen.set_autorotateToPortraitUpsideDown(autorotateToPortraitUpsideDown); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_autorotateToLandscapeLeft(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_autorotateToLandscapeLeft()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_autorotateToLandscapeLeft(IntPtr l) { int result; try { bool autorotateToLandscapeLeft; LuaObject.checkType(l, 2, out autorotateToLandscapeLeft); Screen.set_autorotateToLandscapeLeft(autorotateToLandscapeLeft); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_autorotateToLandscapeRight(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_autorotateToLandscapeRight()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_autorotateToLandscapeRight(IntPtr l) { int result; try { bool autorotateToLandscapeRight; LuaObject.checkType(l, 2, out autorotateToLandscapeRight); Screen.set_autorotateToLandscapeRight(autorotateToLandscapeRight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_orientation(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushEnum(l, Screen.get_orientation()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_orientation(IntPtr l) { int result; try { ScreenOrientation orientation; LuaObject.checkEnum<ScreenOrientation>(l, 2, out orientation); Screen.set_orientation(orientation); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_sleepTimeout(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, Screen.get_sleepTimeout()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_sleepTimeout(IntPtr l) { int result; try { int sleepTimeout; LuaObject.checkType(l, 2, out sleepTimeout); Screen.set_sleepTimeout(sleepTimeout); 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, "UnityEngine.Screen"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Screen.SetResolution_s)); LuaObject.addMember(l, "resolutions", new LuaCSFunction(Lua_UnityEngine_Screen.get_resolutions), null, false); LuaObject.addMember(l, "currentResolution", new LuaCSFunction(Lua_UnityEngine_Screen.get_currentResolution), null, false); LuaObject.addMember(l, "width", new LuaCSFunction(Lua_UnityEngine_Screen.get_width), null, false); LuaObject.addMember(l, "height", new LuaCSFunction(Lua_UnityEngine_Screen.get_height), null, false); LuaObject.addMember(l, "dpi", new LuaCSFunction(Lua_UnityEngine_Screen.get_dpi), null, false); LuaObject.addMember(l, "fullScreen", new LuaCSFunction(Lua_UnityEngine_Screen.get_fullScreen), new LuaCSFunction(Lua_UnityEngine_Screen.set_fullScreen), false); LuaObject.addMember(l, "autorotateToPortrait", new LuaCSFunction(Lua_UnityEngine_Screen.get_autorotateToPortrait), new LuaCSFunction(Lua_UnityEngine_Screen.set_autorotateToPortrait), false); LuaObject.addMember(l, "autorotateToPortraitUpsideDown", new LuaCSFunction(Lua_UnityEngine_Screen.get_autorotateToPortraitUpsideDown), new LuaCSFunction(Lua_UnityEngine_Screen.set_autorotateToPortraitUpsideDown), false); LuaObject.addMember(l, "autorotateToLandscapeLeft", new LuaCSFunction(Lua_UnityEngine_Screen.get_autorotateToLandscapeLeft), new LuaCSFunction(Lua_UnityEngine_Screen.set_autorotateToLandscapeLeft), false); LuaObject.addMember(l, "autorotateToLandscapeRight", new LuaCSFunction(Lua_UnityEngine_Screen.get_autorotateToLandscapeRight), new LuaCSFunction(Lua_UnityEngine_Screen.set_autorotateToLandscapeRight), false); LuaObject.addMember(l, "orientation", new LuaCSFunction(Lua_UnityEngine_Screen.get_orientation), new LuaCSFunction(Lua_UnityEngine_Screen.set_orientation), false); LuaObject.addMember(l, "sleepTimeout", new LuaCSFunction(Lua_UnityEngine_Screen.get_sleepTimeout), new LuaCSFunction(Lua_UnityEngine_Screen.set_sleepTimeout), false); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Screen.constructor), typeof(Screen)); } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades; using PDV.DAO.Enum; using System; using System.Collections.Generic; using System.Data; namespace PDV.CONTROLER.Funcoes { public class FuncoesCFOP { public static bool Existe(decimal IDCfop) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM CFOP WHERE IDCFOP = @IDCFOP"; oSQL.ParamByName["IDCFOP"] = IDCfop; oSQL.Open(); return !oSQL.IsEmpty; } } public static Cfop GetCFOP(decimal IDCfop) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT CFOP.IDCFOP, CFOP.CODIGO, CFOP.DESCRICAO, ATIVO FROM CFOP WHERE IDCFOP = @IDCFOP"; oSQL.ParamByName["IDCFOP"] = IDCfop; oSQL.Open(); return EntityUtil<Cfop>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static Cfop GetCFOPPorCodigo(string Codigo) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT CFOP.IDCFOP, CFOP.CODIGO, CFOP.DESCRICAO, ATIVO FROM CFOP WHERE CODIGO = @CODIGO"; oSQL.ParamByName["CODIGO"] = Codigo; oSQL.Open(); return EntityUtil<Cfop>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static DataTable GetCFOPS(string Codigo, string Descricao) { using (SQLQuery oSQL = new SQLQuery()) { List<string> Filtros = new List<string>(); if (!string.IsNullOrEmpty(Codigo)) Filtros.Add(string.Format("(UPPER(CODIGO) LIKE UPPER('%{0}%'))", Codigo)); if (!string.IsNullOrEmpty(Descricao)) Filtros.Add(string.Format("(UPPER(DESCRICAO) LIKE UPPER('%{0}%'))", Descricao)); oSQL.SQL = string.Format( @"SELECT CFOP.IDCFOP, CFOP.CODIGO, CFOP.DESCRICAO, ATIVO FROM CFOP {0} ORDER BY CODIGO, DESCRICAO", Filtros.Count > 0 ? "WHERE " + string.Join(" AND ", Filtros.ToArray()) : string.Empty); oSQL.Open(); return oSQL.dtDados; } } public static List<Cfop> GetCFOPSAtivos() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT CFOP.IDCFOP, CFOP.CODIGO, CFOP.DESCRICAO, CFOP.CODIGO||' - '||CFOP.DESCRICAO AS CODIGODESCRICAO, CFOP.TIPO FROM CFOP WHERE ATIVO = 1 ORDER BY CODIGO, DESCRICAO"; oSQL.Open(); return new DataTableParser<Cfop>().ParseDataTable(oSQL.dtDados); } } public static bool Salvar(Cfop _Cfop, TipoOperacao Op) { using (SQLQuery oSQL = new SQLQuery()) { switch (Op) { case TipoOperacao.INSERT: oSQL.SQL = "INSERT INTO CFOP (IDCFOP, CODIGO, DESCRICAO, ATIVO) VALUES (@IDCFOP, @CODIGO, @DESCRICAO, @ATIVO)"; break; case TipoOperacao.UPDATE: oSQL.SQL = @"UPDATE CFOP SET CODIGO = @CODIGO, DESCRICAO = @DESCRICAO, ATIVO = @ATIVO WHERE IDCFOP = @IDCFOP"; break; } oSQL.ParamByName["IDCFOP"] = _Cfop.IDCfop; oSQL.ParamByName["CODIGO"] = _Cfop.Codigo; oSQL.ParamByName["DESCRICAO"] = _Cfop.Descricao; oSQL.ParamByName["ATIVO"] = _Cfop.Ativo; return oSQL.ExecSQL() == 1; } } public static bool Remover(decimal IDCfop) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM CFOP WHERE IDCFOP = @IDCFOP"; oSQL.ParamByName["IDCFOP"] = IDCfop; oSQL.Open(); if (!oSQL.IsEmpty) throw new Exception("O CFOP tem vínculo com produto e não pode ser removido."); oSQL.ClearAll(); oSQL.SQL = @"DELETE FROM CFOP WHERE IDCFOP = @IDCFOP"; oSQL.ParamByName["IDCFOP"] = IDCfop; return oSQL.ExecSQL() == 1; } } } }
using System; using System.Xml.Serialization; namespace RO.Config { [CustomLuaClass] public class BuildBundleInfo { [XmlAttribute("SVN_Start")] public int startV = -1; [XmlAttribute("SVN_End")] public int endV; [XmlAttribute("ResVersion")] public int version; [XmlAttribute("ServerVersion")] public string serverVersion; [XmlAttribute("ForceUpdateApp")] public bool forceUpdateApp; public override string ToString() { return string.Format("[BuildBundleInfo] startV:{0} endV:{1} version:{2} serverVersion:{3} forceUpdateApp:{4}", new object[] { this.startV, this.endV, this.version, this.serverVersion, this.forceUpdateApp }); } } }
/** 版本信息模板在安装目录下,可自行修改。 * TEMPLATE_INFO.cs * * 功 能: N/A * 类 名: TEMPLATE_INFO * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2014-6-26 9:19:18 N/A 初版 * * Copyright (c) 2012 Maticsoft Corporation. All rights reserved. *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:动软卓越(北京)科技有限公司              │ *└──────────────────────────────────┘ */ using System; using System.Data; using System.Text; using System.Data.SqlClient; using System.Collections.Generic; using Maticsoft.DBUtility;//Please add references namespace PDTech.OA.DAL { /// <summary> /// 数据访问类:TEMPLATE_INFO /// </summary> public partial class TEMPLATE_INFO { public TEMPLATE_INFO() {} #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(string TEMPLATE_JC) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) from TEMPLATE_INFO"); strSql.Append(" where TEMPLATE_JC=@TEMPLATE_JC "); SqlParameter[] parameters = { new SqlParameter("@TEMPLATE_JC", SqlDbType.NVarChar) }; parameters[0].Value = TEMPLATE_JC; return DbHelperSQL.Exists(strSql.ToString(),parameters); } /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(string TEMPLATE_JC, decimal TEMPLATE_ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from TEMPLATE_INFO"); strSql.Append(" where TEMPLATE_JC=@TEMPLATE_JC AND TEMPLATE_ID<>@TEMPLATE_ID "); SqlParameter[] parameters = { new SqlParameter("@TEMPLATE_JC", SqlDbType.NVarChar), new SqlParameter("@TEMPLATE_ID",SqlDbType.Decimal,4) }; parameters[0].Value = TEMPLATE_JC; return DbHelperSQL.Exists(strSql.ToString(), parameters); } /// <summary> /// 增加一条数据 /// </summary> public int Add(PDTech.OA.Model.TEMPLATE_INFO model) { if (Exists(model.TEMPLATE_JC)) { return -1; } StringBuilder strSql=new StringBuilder(); strSql.Append("insert into TEMPLATE_INFO("); strSql.Append("TEMPLATE_TYPE,TEMPLATE_JC,TEMPLATE_VALUE)"); strSql.Append(" values ("); strSql.Append("@TEMPLATE_TYPE,@TEMPLATE_JC,@TEMPLATE_VALUE)"); SqlParameter[] parameters = { new SqlParameter("@TEMPLATE_TYPE", SqlDbType.NVarChar,150), new SqlParameter("@TEMPLATE_JC", SqlDbType.NVarChar,60), new SqlParameter("@TEMPLATE_VALUE", SqlDbType.NVarChar,3000)}; parameters[0].Value = model.TEMPLATE_TYPE; parameters[1].Value = model.TEMPLATE_JC; parameters[2].Value = model.TEMPLATE_VALUE; DAL_Helper.get_db_para_value(parameters); int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return 1; } else { return 0; } } /// <summary> /// 更新一条数据 /// </summary> public int Update(PDTech.OA.Model.TEMPLATE_INFO model) { if (Exists(model.TEMPLATE_JC,(decimal)model.TEMPLATE_ID)) { return -1; } StringBuilder strSql=new StringBuilder(); strSql.Append("update TEMPLATE_INFO set "); strSql.Append("TEMPLATE_JC=@TEMPLATE_JC,"); strSql.Append("TEMPLATE_VALUE=@TEMPLATE_VALUE"); strSql.Append(" where TEMPLATE_ID=@TEMPLATE_ID "); SqlParameter[] parameters = { new SqlParameter("@TEMPLATE_JC", SqlDbType.NVarChar,60), new SqlParameter("@TEMPLATE_VALUE", SqlDbType.NVarChar,3000), new SqlParameter("@TEMPLATE_ID", SqlDbType.Decimal,4)}; parameters[0].Value = model.TEMPLATE_JC; parameters[1].Value = model.TEMPLATE_VALUE; parameters[2].Value = model.TEMPLATE_ID; DAL_Helper.get_db_para_value(parameters); int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return 1; } else { return 0; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(decimal TEMPLATE_ID) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from TEMPLATE_INFO "); strSql.Append(" where TEMPLATE_ID=@TEMPLATE_ID "); SqlParameter[] parameters = { new SqlParameter("@TEMPLATE_ID", SqlDbType.Decimal,22) }; parameters[0].Value = TEMPLATE_ID; int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 获取信息 /// </summary> /// <param name="where"></param> /// <returns></returns> public Model.TEMPLATE_INFO GetmTempInfo(decimal tId) { string strSQL = string.Format(@"SELECT T.*, (SELECT FULL_NAME FROM USER_INFO WHERE USER_ID=T.TEMPLATE_OWNER) FULL_NAME FROM TEMPLATE_INFO T WHERE TEMPLATE_ID={0}", tId); DataTable dt = DbHelperSQL.GetTable(strSQL); if (dt.Rows.Count > 0) { return DAL_Helper.CommonFillList<Model.TEMPLATE_INFO>(dt)[0]; } else { return null; } } /// <summary> /// 获取模板信息-分页 /// </summary> /// <param name="where"></param> /// <param name="currentpage"></param> /// <param name="pagesize"></param> /// <param name="totalrecord"></param> /// <returns></returns> public IList<Model.TEMPLATE_INFO> get_Paging_tempList(Model.TEMPLATE_INFO where, int currentpage, int pagesize, out int totalrecord) { string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Format(@"SELECT TOP (100) PERCENT T.*, (SELECT FULL_NAME FROM USER_INFO WHERE USER_ID=T.TEMPLATE_OWNER) FULL_NAME FROM TEMPLATE_INFO T WHERE 1=1 {0} ", condition); PageDescribe pdes = new PageDescribe(); pdes.CurrentPage = currentpage; pdes.PageSize = pagesize; DataTable dt = pdes.PageDescribes(strSQL, "TEMPLATE_ID","DESC"); totalrecord = pdes.RecordCount; return DAL_Helper.CommonFillList<Model.TEMPLATE_INFO>(dt); } /// <summary> /// 获取模板信息-未分页 /// </summary> /// <param name="where"></param> /// <param name="currentpage"></param> /// <param name="pagesize"></param> /// <param name="totalrecord"></param> /// <returns></returns> public IList<Model.TEMPLATE_INFO> get_Paging_tempList(Model.TEMPLATE_INFO where) { string condition = DAL_Helper.GetWhereCondition(where); string strSQL = string.Format(@"SELECT T.*, (SELECT FULL_NAME FROM USER_INFO WHERE USER_ID=T.TEMPLATE_OWNER) FULL_NAME FROM TEMPLATE_INFO T WHERE 1=1 {0} ", condition); DataTable dt = DbHelperSQL.GetTable(strSQL); return DAL_Helper.CommonFillList<Model.TEMPLATE_INFO>(dt); } #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL.Interface.Entities { public class QuestionEntity { public int Id { get; set; } public string Content { get; set; } public int Cost { get; set; } public int UserId { get; set; } public DateTime Date { get; set; } public bool IsDelete { get; set; } } }
using System.Configuration; using System.Data.Entity; using Fundamentals.DomainModel; using Fundamentals.Models.Authorization; using Fundamentals.Models.Error; using Microsoft.AspNet.Identity.EntityFramework; namespace Fundamentals.Models.DBContext { public class FundamentalsDBContext : IdentityDbContext<ApplicationUser> { private static readonly string _connectionString; protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer<FundamentalsDBContext>(null); base.OnModelCreating(modelBuilder); } public static FundamentalsDBContext Create() { return new FundamentalsDBContext(); } static FundamentalsDBContext() { _connectionString = ConfigurationManager.ConnectionStrings[nameof(FundamentalsDBContext)].ConnectionString; } public FundamentalsDBContext() : base(_connectionString) { Database.SetInitializer(new CreateDatabaseIfNotExists<FundamentalsDBContext>()); } public FundamentalsDBContext(string connectionstring) : this() { } public DbSet<CustomerViewModel> Customers { get; set; } public DbSet<MovieViewModel> Movies { get; set; } public DbSet<Ganres> Ganres { get; set; } public DbSet<File> Files { get; set; } public DbSet<AppError> Errors { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace DataCenter.Helpers { internal class Downloader { private static object Lock = new object(); public delegate void OnProgress(double percent); public static Task<string> DownloadStringAsync(string url, OnProgress onProgressChanged) { TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(); double previous = -1; using (WebClient wc = new WebClient()) { if (onProgressChanged != null) wc.DownloadProgressChanged += (s, e) => { lock (Lock) { if (e.ProgressPercentage - previous > 0.3) { previous = e.ProgressPercentage; onProgressChanged(e.ProgressPercentage); } } }; wc.DownloadStringCompleted += (s, e) => { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetException(new Exception("Downloading was cancelled")); else tcs.TrySetResult(e.Result); }; wc.DownloadStringAsync(new Uri(url)); } return tcs.Task; } public static Task<object> DownloadFileAsync(string url, string file, OnProgress onProgressChanged, string cookie) { TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); double previous = -1; using (WebClient wc = new WebClient()) { if (onProgressChanged != null) wc.DownloadProgressChanged += (s, e) => { lock (Lock) { if (e.ProgressPercentage - previous > 0.3) { previous = e.ProgressPercentage; onProgressChanged(e.ProgressPercentage); } } }; wc.DownloadFileCompleted += (s, e) => { if (e.Error != null) tcs.TrySetException(e.Error); else if (e.Cancelled) tcs.TrySetException(new Exception("Downloading was cancelled")); else tcs.TrySetResult(new Object()); }; if (cookie != null) wc.Headers.Add(HttpRequestHeader.Cookie, cookie); wc.DownloadFileAsync(new Uri(url), file); } return tcs.Task; } } }
#if NETSTANDARD1_0 using System; using System.Collections.Generic; using System.Reflection; namespace yocto { internal static class AssemblyExtensions { public static IEnumerable<TypeInfo> ExportedTypes(this Assembly extendThis) { var typeInfo = new List<TypeInfo>(); foreach (var type in extendThis.ExportedTypes) { typeInfo.Add(type.GetTypeInfo()); } return typeInfo; } } } #endif
using FastSQL.Core; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; namespace FastSQL.MsSql { public class ConnectionStringBuilder { private IEnumerable<OptionItem> _selfOptions; public ConnectionStringBuilder(IEnumerable<OptionItem> selfOptions) { _selfOptions = selfOptions; } public string Build() { var username = _selfOptions.FirstOrDefault(o => o.Name == "UserID")?.Value; var password = _selfOptions.FirstOrDefault(o => o.Name == "Password")?.Value; var builder = new SqlConnectionStringBuilder { DataSource = _selfOptions.FirstOrDefault(o => o.Name == "DataSource")?.Value, MultipleActiveResultSets = true, //builder.MultiSubnetFailover = true; Pooling = false, InitialCatalog = _selfOptions.FirstOrDefault(o => o.Name == "Database")?.Value }; if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password)) { builder.UserID = username; builder.Password = password; builder.IntegratedSecurity = false; } else { builder.IntegratedSecurity = true; } return builder.ToString(); } } }
using PlatformRacing3.Server.API.Game.Commands; using PlatformRacing3.Server.Game.Client; using PlatformRacing3.Server.Game.Match; namespace PlatformRacing3.Server.Game.Commands.Match; internal class DelayStartCommand : ICommand { public string Permission => "command.delaystart.use"; public void OnCommand(ICommandExecutor executor, string label, ReadOnlySpan<string> args) { if (executor is ClientSession { MultiplayerMatchSession.Match: { } match }) { if (match.Status <= MultiplayerMatchStatus.WaitingForUsersToDraw) { match.DelayedStart = !match.DelayedStart; match.CheckGameState(); executor.SendMessage(match.DelayedStart ? "Delayed start enabled" : "Delayed start disabled"); } else { executor.SendMessage("The game has started!"); } } else if (executor is ClientSession { LobbySession.MatchListing: { } matchListing }) { matchListing.DelayedStart = !matchListing.DelayedStart; executor.SendMessage(matchListing.DelayedStart ? "Delayed start enabled" : "Delayed start disabled"); } else { executor.SendMessage("You are not in a match!"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Grisaia.Utils; namespace Grisaia.Extensions { partial class BinaryReaderExtensions { #region Read Array (Signed) /// <summary> /// Reads an array of 1-byte signed integers from the current stream and advances the current position of the /// stream by <paramref name="count"/> bytes. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 1-byte signed integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> public static sbyte[] ReadSBytes(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); sbyte[] values = new sbyte[count]; byte[] buffer = reader.ReadBytes(count); Buffer.BlockCopy(buffer, 0, values, 0, count); return values; } /// <summary> /// Reads an array of 2-byte signed integers from the current stream and advances the current position of the /// stream by two bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 2-byte signed integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static short[] ReadInt16s(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(short); short[] values = new short[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } /// <summary> /// Reads an array of 4-byte signed integers from the current stream and advances the current position of the /// stream by four bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 4-byte signed integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static int[] ReadInt32s(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(int); int[] values = new int[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } /// <summary> /// Reads an array of 8-byte signed integers from the current stream and advances the current position of the /// stream by eight bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 8-byte signed integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static long[] ReadInt64s(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(long); long[] values = new long[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } #endregion #region Read Array (Unsigned) /// <summary> /// Reads an array of 2-byte unsigned integers from the current stream and advances the current position of /// the stream by two bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 2-byte unsigned integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static ushort[] ReadUInt16s(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(ushort); ushort[] values = new ushort[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } /// <summary> /// Reads an array of 4-byte unsigned integers from the current stream and advances the current position of /// the stream by four bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 4-byte unsigned integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static uint[] ReadUInt32s(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(uint); uint[] values = new uint[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } /// <summary> /// Reads an array of 8-byte unsigned integers from the current stream and advances the current position of /// the stream by eight bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of 8-byte unsigned integers read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static ulong[] ReadUInt64s(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(ulong); ulong[] values = new ulong[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } #endregion #region Read Array (Floating) /// <summary> /// Reads an array of single-floating points from the current stream and advances the current position of the /// stream by four bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of single-floating points read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static float[] ReadSingles(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(float); float[] values = new float[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } /// <summary> /// Reads an array of double-floating points from the current stream and advances the current position of the /// stream by eight bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of double-floating points read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static double[] ReadDoubles(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(double); double[] values = new double[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } /// <summary> /// Reads an array of decimal-floating points from the current stream and advances the current position of the /// stream by sixteen bytes times <paramref name="count"/>. /// </summary> /// <param name="reader">The <see cref="BinaryReader"/> to read with.</param> /// <param name="count">The number of values to read.</param> /// <returns>An array of decimal-floating points read from the current stream.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="reader"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count"/> is negative. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached. /// </exception> /// <exception cref="IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="NotSupportedException"> /// The stream does not support reading. /// </exception> /// <exception cref="ObjectDisposedException"> /// The stream is closed. /// </exception> /// <exception cref="OverflowException"> /// The number of bytes to read is greater than <see cref="int.MaxValue"/>. /// </exception> public static decimal[] ReadDecimals(this BinaryReader reader, int count) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (count < 0) throw ArgumentOutOfRangeUtils.OutsideMin(nameof(count), count, 0, true); int bufferSize = count * sizeof(decimal); decimal[] values = new decimal[count]; byte[] buffer = reader.ReadBytes(bufferSize); Buffer.BlockCopy(buffer, 0, values, 0, bufferSize); return values; } #endregion } }
using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webcorp.unite; namespace Webcorp.Model.Quotation { public class Prestataire:Entity { [BsonId(IdGenerator = typeof(EntityIdGenerator))] public override string Id { get; set; } [KeyProvider] public string Nom { get; set; } } public class Prestation<T,U> where T : Unit<T> where U : Unit<U> { public string Nom { get; set; } public List<Tranche<T,U>> Tranches { get; set; } } }
//-------------------------------- // Skinned Metaball Builder // Copyright © 2015 JunkGames //-------------------------------- using UnityEngine; using System.Collections; public abstract class Weapon : MonoBehaviour { public GameObject weaponBody; public IMBrush brush; public Animator animator; public AudioSource audioSource; protected abstract void DoShoot(DungeonControl2 dungeon, Vector3 from, Vector3 to); public AudioClip equipAudio; public AudioClip shotAudio; public void Shoot(DungeonControl2 dungeon, Vector3 from, Vector3 to) { if (audioSource != null && shotAudio != null) { audioSource.PlayOneShot(shotAudio); } DoShoot(dungeon, from, to); } public void OnEquip() { animator.SetBool("EQUIP", true); if( audioSource != null && equipAudio != null ) { audioSource.PlayOneShot(equipAudio); } } public void OnRemove() { animator.SetBool("EQUIP", false); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief JSON。JSON化。 */ /** NJsonItem */ namespace NJsonItem { /** ObjectToJson_Work */ public class ObjectToJson_Work { /** from_object */ private System.Object from_object; /** to_jsonitem */ private JsonItem to_jsonitem; private int to_index; private string to_key; /** additem */ private bool mode_add; /** setitem */ private bool mode_set; /** constructor */ public ObjectToJson_Work(System.Object a_object,int a_index,JsonItem a_to_jsonitem) { this.from_object = a_object; this.to_jsonitem = a_to_jsonitem; this.to_index = a_index; this.to_key = null; this.mode_add = true; this.mode_set = false; } /** constructor */ public ObjectToJson_Work(System.Object a_object,string a_key,JsonItem a_to_jsonitem) { this.from_object = a_object; this.to_jsonitem = a_to_jsonitem; this.to_index = -1; this.to_key = a_key; this.mode_add = false; this.mode_set = true; } /** 実行。 */ public void Do(List<ObjectToJson_Work> a_work_pool) { JsonItem t_jsonitem_member = ObjectToJson.Convert(this.from_object,a_work_pool); if(this.mode_add == true){ this.to_jsonitem.SetItem(this.to_index,t_jsonitem_member,false); }else if(this.mode_set == true){ this.to_jsonitem.SetItem(this.to_key,t_jsonitem_member,false); } } } }
using Shop.Data.DataModels; using Shop.Data.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shop.BusinnesLogic.Services.Fuctory { public static class ClientSimpleFuctoty { private static Dictionary<int, Client> _client = new Dictionary<int, Client>(); static ClientSimpleFuctoty() { _client.Add(1, new OneTimeClient()); _client.Add(2, new LongTimeClient()); } public static Client CreateClient(int clientType) { var client = _client[clientType]; return client; } } }
using Moq; using NETCommunity.FsCheck.Discounts; using NETCommunity.FsCheck.Discounts.Card; namespace NETCommunity.FsCheck.Tests.Discounts.Card { public class DiscountCardDiscountTests { private MockRepository mockRepository; private Mock<IDiscountCard> mockDiscountCard; [TestInitialize] public void TestInitialize() { this.mockRepository = new MockRepository(MockBehavior.Strict); this.mockDiscountCard = this.mockRepository.Create<IDiscountCard>(); } [TestCleanup] public void TestCleanup() { this.mockRepository.VerifyAll(); } [TestMethod] public void TestMethod1() { // Arrange // Act DiscountCardDiscount discountCardDiscount = this.CreateDiscountCardDiscount(); // Assert } private DiscountCardDiscount CreateDiscountCardDiscount() { return new DiscountCardDiscount( this.mockDiscountCard.Object); } } }
using BoatRegistration.Process; using Microsoft.AspNetCore.Mvc; namespace BoatRegistration.Controllers { public class BoatController : Controller { private readonly BoatProcess _boatProcess; public BoatController(BoatProcess boatProcess) { _boatProcess = boatProcess; } [HttpGet] public IActionResult RegisterBoat() { return View(); } [HttpPost] public IActionResult RegisterBoat(string boatName, int hourlyCharges) { var id = _boatProcess.RegisterBoat(boatName, hourlyCharges); ViewBag.Message = $"Boat Registered with ID : {id}"; ModelState.Clear(); return View(); } [HttpGet] public IActionResult RentBoat() { return View(); } [HttpPost] public IActionResult RentBoat(int id, string customername) { var message = _boatProcess.RentBoat(id, customername); ViewBag.Message = message; ModelState.Clear(); return View(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UserSessionsController.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Web; using System.Web.Configuration; using System.Web.Mvc; using System.Web.Security; using CGI.Reflex.Core; using CGI.Reflex.Core.Entities; using CGI.Reflex.Core.Queries; using CGI.Reflex.Web.Commands; using CGI.Reflex.Web.Configuration; using CGI.Reflex.Web.Infra.Controllers; using CGI.Reflex.Web.Infra.Filters; using CGI.Reflex.Web.Models.UserSessions; using Postal; namespace CGI.Reflex.Web.Controllers { public class UserSessionsController : BaseController { [AllowedAuthenticationMode(AuthenticationMode.Forms)] public ActionResult Login(string returnUrl) { return View(new Login { ReturnUrl = returnUrl }); } [HttpPost] [ExcludeFromCodeCoverage] [AllowedAuthenticationMode(AuthenticationMode.Forms)] public ActionResult Login(Login model) { if (ModelState.IsValid) { var userAuth = UserAuthentication.Authenticate(model.NameOrEmail, model.Password); if (userAuth == null && Config.AutoCreateUsers && Config.Environment != ConfigEnvironment.Production) { var role = NHSession.QueryOver<Role>().Where(r => r.Name == model.Password).SingleOrDefault(); if (role != null) { var user = new User { UserName = model.NameOrEmail, Email = model.NameOrEmail, Role = role }; NHSession.Save(user); userAuth = new UserAuthentication { User = user, LastLoginDate = DateTime.Now }; userAuth.SetPassword(model.Password); NHSession.Save(userAuth); } } if (userAuth != null) { FormsAuthentication.SetAuthCookie(userAuth.User.Id.ToString(CultureInfo.InvariantCulture), false); if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/") && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\")) return Redirect(model.ReturnUrl); return RedirectToAction("Index", "Home"); } Flash(FlashLevel.Error, "Le nom d'utilisateur, courriel ou mot de passe est incorrect."); } return View(model); } [ExcludeFromCodeCoverage] [AllowedAuthenticationMode(AuthenticationMode.Forms)] public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToRoute("Login"); } [AllowedAuthenticationMode(AuthenticationMode.Forms)] public ActionResult Boarding(string key) { var userAuth = NHSession.QueryOver<UserAuthentication>() .Where(a => a.SingleAccessToken == key) .Fetch(a => a.User).Eager .SingleOrDefault(); if (userAuth == null) return HttpNotFound(); if (userAuth.SingleAccessTokenValidUntil < DateTime.Now) return View("BoardingPerished"); if (userAuth.User.IsLockedOut) return View("BoardingPerished"); var model = new Boarding { SingleAccessToken = key, UserName = userAuth.User.UserName }; return View(model); } [HttpPost] [AllowedAuthenticationMode(AuthenticationMode.Forms)] [ExcludeFromCodeCoverage] public ActionResult Boarding(Boarding model) { var userAuth = NHSession.QueryOver<UserAuthentication>() .Where(a => a.SingleAccessToken == model.SingleAccessToken) .Fetch(a => a.User).Eager .SingleOrDefault(); if (userAuth == null) return HttpNotFound(); if (userAuth.SingleAccessTokenValidUntil < DateTime.Now) return HttpNotFound(); if (userAuth.User.IsLockedOut) return HttpNotFound(); if (!ModelState.IsValid) { model.UserName = userAuth.User.UserName; return View(model); } userAuth.SetPassword(model.Password); userAuth.ClearSingleAccessToken(); FormsAuthentication.SetAuthCookie(userAuth.User.Id.ToString(CultureInfo.InvariantCulture), false); return RedirectToAction("Index", "Home"); } [AllowedAuthenticationMode(AuthenticationMode.Forms)] public ActionResult ResetPassword() { return View(); } [HttpPost] [AllowedAuthenticationMode(AuthenticationMode.Forms)] [ExcludeFromCodeCoverage] public ActionResult ResetPassword(string userNameOrEmail) { var user = new UserQuery { NameOrEmail = userNameOrEmail }.SingleOrDefault(); if (user == null) { Flash(FlashLevel.Warning, "Ce nom d'utilisateur ou courriel est introuvable."); return View(); } var userAuth = NHSession.QueryOver<UserAuthentication>().Where(a => a.User.Id == user.Id).SingleOrDefault(); userAuth.ClearPassword(); Execute<SendUserResetTokenCommand, string>(cmd => { cmd.UserAuthentication = userAuth; cmd.UrlHelper = Url; }); Flash(FlashLevel.Success, string.Format("Un courriel permettant la connexion a été envoyé à l'adresse {0}.", user.Email)); return View("ResetPasswordResult"); } } }
using System; namespace fraction_calculator_dotnet.Operators { internal class Lcd : IOperator<ulong> { public ulong Execute(ulong a, ulong b) { var operatorGcd = new Gcd(); var gcd = operatorGcd.Execute(a, b); return (a / gcd) * b; } } }