text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using SSDAssignmentBOX.Models; using Microsoft.AspNetCore.Identity; namespace SSDAssignmentBOX { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } #region snippet_ConfigureServices public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BookContext>(options => options.UseSqlServer(Configuration.GetConnectionString("BookContext"))); //ConfigureServices() method calls AddIdentity() method to add ASP.NET Core Identity services to the container. This is where ApplicationUser and IdentityRole classes are also mentioned. //The following code register the context and identity to Dependency Injection during the Application start up. Register these as a Service in the ConfigureServices method of the StartUp class, services.AddIdentity<ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores<BookContext>() .AddDefaultTokenProviders(); services.Configure<IdentityOptions>(options => { // Password settings. Password, lockout and user settings can be configured. options.Password.RequireDigit = true; options.Password.RequiredLength = 12; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequireLowercase = true; options.Password.RequiredUniqueChars = 1; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 3; options.Lockout.AllowedForNewUsers = true; // User settings options.User.RequireUniqueEmail = true; }); services.ConfigureApplicationCookie(options => { // options.Cookie.Name = "YourCookieName"; // options.Cookie.Domain= // options.LoginPath = "/Account/Login"; // options.LogoutPath = "/Account/Logout"; // options.AccessDeniedPath = "/Account/AccessDenied"; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromSeconds(300); options.SlidingExpiration = true; }); //Use of authorization filters - AuthorizePage(), AuthorizeFolder(), AllowAnonymousToPage() and AllowAnonymousToFolder() methods at startup to control access. //AuthorizeFolder method to restrict access to a folder and all of its contents. //AuthorizePage method to restrict access on a page-by-page basis. services.AddMvc().AddRazorPagesOptions(options => { //options.Conventions.AllowAnonymousToFolder("/Books"); options.Conventions.AuthorizePage("/Books/Create"); options.Conventions.AuthorizePage("/Account/Create"); }); } #endregion // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseStatusCodePages("text/html", "<h1>Status code page</h1> <h2>Status Code: {0}</h2> <br> <a href='/Index'>Go back to Mainpage</a>"); app.UseExceptionHandler("/Error"); app.UseHsts(); /*if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("~/Error"); app.UseHsts(); }*/ /* if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { //When exception occurs, route to Error page in the Pages folder app.UseStatusCodePages("text/html", "<h1>Status code page</h1> <h2>Status Code: {0}</h2> <br> <a href='/Index'>Go back to Mainpage</a>"); app.UseExceptionHandler("/Error"); }*/ app.UseStaticFiles(); app.UseAuthentication(); //Configure() method calls UserAuthentication() method to add ASP.NET Core Identity to the request pipeline. app.UseMvc(); } } }
namespace WebApi.Helpers{ public class PresentXException : System.Exception { public PresentXException() { } public PresentXException(string message) : base(message) { } public PresentXException(string message, System.Exception inner) : base(message, inner) { } protected PresentXException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
using System; namespace Uintra.Core.MediaToolkit { public class ConvertProgressEventArgs : EventArgs { public ConvertProgressEventArgs(TimeSpan processed, TimeSpan totalDuration, long? frame, double? fps, int? sizeKb, double? bitrate) { TotalDuration = totalDuration; ProcessedDuration = processed; Frame = frame; Fps = fps; SizeKb = sizeKb; Bitrate = bitrate; } public long? Frame { get; private set; } public double? Fps { get; private set; } public int? SizeKb { get; private set; } public TimeSpan ProcessedDuration { get; private set; } public double? Bitrate { get; private set; } public TimeSpan TotalDuration { get; internal set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace eTicaretProjesi.ENT.Model { [Table("Kategoriler")] public class Kategoriler { [Key] public int KategoriID { get; set; } [Required(ErrorMessage = "Kategori ad girmek zorunludur")] public string KategoriAD { get; set; } public virtual List<KategoriAlt> AltKategori { get; set; } = new List<KategoriAlt>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polaris.Models { /// <summary> /// ファイルの状態 /// </summary> public class FileState { /// <summary> /// ctor /// </summary> public FileState() #region { } #endregion /// <summary> /// 設定 /// </summary> public void Set( FileTypes fileType, string fileTypeStr, int count ) #region { FileType = fileType; FileTypeStr = fileTypeStr; Count = count; } #endregion public FileTypes FileType { get; private set; } = FileTypes.INVALID; public string FileTypeStr { get; private set; } = ""; public int Count { get; private set; } = 0; } }
using System; using System.Data; using System.Drawing; using System.Windows.Forms; namespace Movil_RIDA { public partial class PrincipalAbastoPkg : Form { AbastoPkg abasto = new AbastoPkg(); public PrincipalAbastoPkg() { InitializeComponent(); } // private void btnSalir_Click(object sender, EventArgs e) { Global.LogOut(Global.Usuario); this.Close(); } // private void btnRecolectar_Click(object sender, EventArgs e) { /*Se da inicio al proceso de recolección, obteniendo el número de Transferenica correspondiente*/ btnRecolectar.Enabled = false; //Cerramos la ventana principal y pasamos a la de recolección this.Close(); Recolectar fRecolectar = new Recolectar(); fRecolectar.Show(); } // private void frmPrincipal_Load(object sender, EventArgs e) { /* Al cargar la página principal, lo primero que se debe de verificar es si existen recolecciones pendientes de Re-Abastecer, antes de hacer otra recolección en caso de que si, primero se procede a terminar la recoleccón pendiente de Re-Abastecer, en caso de que no existan pendiente, entonces se procede a generar el cálculo correspondiente al semáforo de picking. */ DataSet ds0 = new DataSet(); DataSet ds1 = new DataSet(); DataSet dsError = new DataSet(); DataRow dr,dr0, drError; int ExistenPendientesPorReAbastecer = 0; //Mandamos llamar el método que verifica si existen recolecciones pendientes de Re-Abastecer ds0 = abasto.VerificarReAbastoPendiente(Global.Usuario); ExistenPendientesPorReAbastecer = ds0.Tables[0].Rows.Count; //Mandamos llamar el método que verifica si existen transferencias fallidas (es decir, con error) dsError = abasto.VerificarAbastoError(Global.Usuario); int AbastosConErrorPorAbastecedor = dsError.Tables[0].Rows.Count; try { //Si existen abastos con status de Error, entonces: if (AbastosConErrorPorAbastecedor > 0) { //Asignamos el número de Transferencia que corresponde a la recolección pendiente de Re-Abastecer drError = dsError.Tables[0].Rows[0]; AbastoPkg.Transferencia = drError["transferencia"].ToString(); AbastoPkg.ClaveRecolectar = drError["Clave"].ToString(); //Primero se debe de concluir con el Re-Abasto de la recolección pendiente, por tal motivo sólo se habilita el botón de Re-Abastecer. btnRecolectar.Enabled = false; btnAbastecer.Enabled = false; btnAbastecer.BackColor = Color.Red; btnAbastecer.ForeColor = Color.Black; string msj = string.Format("NO se pudo generar lote de abasto en SL para el ID:{0} ", AbastoPkg.Transferencia, AbastoPkg.ClaveRecolectar); lbClavesDelSemaforo.Text = "ERROR"; //msj; lbClavesEnRojo.Text = ""; lbClavesEnAmarillo.Text = ""; lbClavesEnVerde.Text = ""; MessageBox.Show(msj); } //Si existen recolecciones pendientes de Re-Abastecer, entonces: else if (ExistenPendientesPorReAbastecer > 0) { //Asignamos el número de Transferencia que corresponde a la recolección pendiente de Re-Abastecer dr0 = ds0.Tables[0].Rows[0]; AbastoPkg.Transferencia = dr0[0].ToString(); //Primero se debe de concluir con el Re-Abasto de la recolección pendiente, por tal motivo sólo se habilita el botón de Re-Abastecer. btnRecolectar.Enabled = false; btnAbastecer.Enabled = true; btnAbastecer.BackColor = Color.Red; btnAbastecer.ForeColor = Color.Black; lbClavesDelSemaforo.Text = "Existen recolecciones pendientes por Re-Abastecer"; lbClavesEnRojo.Text = ""; lbClavesEnAmarillo.Text = ""; lbClavesEnVerde.Text = ""; } else { //Si no hay recolecciones pendientes de Re-Abastecer, sólo se habilita el Botón Recolectar btnRecolectar.Enabled = true; btnAbastecer.Enabled = false; if (abasto.GenerarAbastoPicking(Global.Usuario)) { ds1 = abasto.ObtenerClavesSemaforoPorColor(Global.Usuario); dr = ds1.Tables[0].Rows[0]; //Asignamos los datos obtenidos de la clave a las variables globales del programa lbClavesDelSemaforo.Text = "Claves por Abastecer: "; lbClavesEnRojo.Text = dr["Rojo"].ToString().Trim(); lbClavesEnAmarillo.Text = dr["Amarillo"].ToString().Trim(); lbClavesEnVerde.Text = dr["Verde"].ToString().Trim(); } else { MessageBox.Show("Error, no se generó correctamente el cálculo del semáforo."); } } } catch (Exception) { MessageBox.Show("Error, no controlado."); } } // private void btnAbastecer_Click(object sender, EventArgs e) { /* Se da inicio al proceso de Re-Abasto, esto solo es en el caso de que exista rolección pendiente de re-abastecer */ //Habilitamos el botón de abastecer y inabilitamos el botón de Recolectar btnAbastecer.Enabled = true; btnRecolectar.Enabled = false; this.Close(); Abastecer fAbastecer = new Abastecer(); fAbastecer.Show(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Author: Nathan Hales /// This is a simple script for a trigger box inside the credits scene. Any cedit object that enters it fades over time. (Alpha fades) /// </summary> public class CreditEater : MonoBehaviour { public float fadeSpeed = 10f; TextMesh _textmesh; SpriteRenderer _backingSprite; private void OnTriggerEnter(Collider other) { print("Hit"); if (other.GetComponent<TextMesh>() != null) { print("beep1"); _textmesh = other.GetComponent<TextMesh>(); _backingSprite = other.GetComponentInChildren<SpriteRenderer>(); } } private void Update() { if (_textmesh != null && _backingSprite != null) { Color textcolor = _textmesh.color; textcolor.a -= Time.deltaTime * fadeSpeed; _textmesh.color = textcolor; Color backingColor = _backingSprite.color; backingColor.a -= Time.deltaTime * fadeSpeed; _backingSprite.color = backingColor; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems.AdventOfCode.Y2022 { public class Problem15 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2022: 15"; public override string GetAnswer() { return Answer1(Input(), 2000000).ToString(); } public override string GetAnswer2() { return Answer2(Input(), 4000000).ToString(); } private int Answer1(List<string> input, int y) { var state = new State(); SetSensors(input, state); SetMinMax(state); return CountRow(y, state); } private ulong Answer2(List<string> input, int max) { var state = new State(); SetSensors(input, state); for (int y = 0; y <= max; y++) { var count = CountRow2(y, state); if (count != -1) { return (ulong)count * (ulong)4000000 + (ulong)y; } } return 0; } private int CountRow2(int y, State state) { var lines = new List<Line>(); foreach (var sensor in state.Sensors) { var diff = Math.Abs(y - sensor.Location.Y); if (diff <= sensor.Distance) { lines.Add(new Line() { Start = sensor.Location.X - (sensor.Distance - diff), End = sensor.Location.X + (sensor.Distance - diff) }); } } Merge(lines); Merge(lines); if (lines.Count == 1) { return -1; } else { if (lines[0].Start < lines[1].Start) { return lines[0].End + 1; } else { return lines[1].End + 1; } } } private void Merge(List<Line> lines) { int index = 0; do { var line = lines[index]; for (int nextIndex = index + 1; nextIndex < lines.Count; nextIndex++) { if (nextIndex != index) { var nextLine = lines[nextIndex]; if (line.Start <= nextLine.End && line.End >= nextLine.Start) { line.Start = Math.Min(line.Start, nextLine.Start); line.End = Math.Max(line.End, nextLine.End); lines.RemoveAt(nextIndex); nextIndex--; } } } index++; } while (index < lines.Count); } private int CountRow(int y, State state) { var hash = new HashSet<int>(); foreach (var sensor in state.Sensors) { var diff = Math.Abs(y - sensor.Location.Y); if (diff <= sensor.Distance) { hash.Add(sensor.Location.X); int count = 1; while (diff + count <= sensor.Distance) { hash.Add(sensor.Location.X - count); hash.Add(sensor.Location.X + count); count++; } } } foreach (var sensor in state.Sensors) { if (sensor.Location.Y == y && hash.Contains(sensor.Location.X)) hash.Remove(sensor.Location.X); if (sensor.Beacon.Y == y && hash.Contains(sensor.Beacon.X)) hash.Remove(sensor.Beacon.X); } return hash.Count; } private void SetMinMax(State state) { var sensorMin = new Point() { X = state.Sensors.Select(x => x.Location.X).Min(), Y = state.Sensors.Select(x => x.Location.Y).Min() }; var sensorMax = new Point() { X = state.Sensors.Select(x => x.Location.X).Max(), Y = state.Sensors.Select(x => x.Location.Y).Max() }; var beaconMin = new Point() { X = state.Sensors.Select(x => x.Beacon.X).Min(), Y = state.Sensors.Select(x => x.Beacon.Y).Min() }; var beaconMax = new Point() { X = state.Sensors.Select(x => x.Beacon.X).Max(), Y = state.Sensors.Select(x => x.Beacon.Y).Max() }; } private void SetSensors(List<string> input, State state) { state.Sensors = input.Select(line => { var split = line.Split(' '); var sensor = new Sensor() { Beacon = new Point(), Location = new Point() }; sensor.Location.X = Convert.ToInt32(split[2].Substring(2).Replace(",","")); sensor.Location.Y = Convert.ToInt32(split[3].Substring(2).Replace(":", "")); sensor.Beacon.X = Convert.ToInt32(split[8].Substring(2).Replace(",", "")); sensor.Beacon.Y = Convert.ToInt32(split[9].Substring(2)); sensor.Distance = GetDistance(sensor.Location, sensor.Beacon); return sensor; }).ToList(); } private int GetDistance(Point point1, Point point2) { return Math.Abs(point1.X - point2.X) + Math.Abs(point1.Y - point2.Y); } private bool IsSame(Point point1, Point point2) { return point1.X == point2.X && point1.Y == point2.Y; } private class State { public List<Sensor> Sensors { get; set; } } private class Sensor { public Point Location { get; set; } public Point Beacon { get; set; } public int Distance { get; set; } } private class Point { public int X { get; set; } public int Y { get; set; } } private class Line { public int Start { get; set; } public int End { get; set; } } } }
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using HCore.Web.Exceptions; using System; using System.Threading.Tasks; using Newtonsoft.Json; using Microsoft.Extensions.Configuration; using System.Web; using HCore.Translations.Providers; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.DataProtection; namespace HCore.Web.Middleware { internal class UnhandledExceptionHandlingMiddleware { private readonly RequestDelegate _next; private readonly ITranslationsProvider _translationsProvider; private readonly ILogger<UnhandledExceptionHandlingMiddleware> _logger; private int? _webPort; private int? _apiPort; private string _criticalFallbackUrl; private string _tenantSelectorFallbackUrl; private readonly IDataProtectionProvider _dataProtectionProvider; public UnhandledExceptionHandlingMiddleware( RequestDelegate next, IDataProtectionProvider dataProtectionProvider, IServiceProvider serviceProvider, IConfiguration configuration, ILogger<UnhandledExceptionHandlingMiddleware> logger) { _next = next; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); bool useWeb = configuration.GetValue<bool>("WebServer:UseWeb"); bool useApi = configuration.GetValue<bool>("WebServer:UseApi"); _criticalFallbackUrl = configuration["WebServer:CriticalFallbackUrl"]; _tenantSelectorFallbackUrl = configuration["Identity:Tenants:TenantSelectorFallbackUrl"]; if (string.IsNullOrEmpty(_criticalFallbackUrl)) throw new Exception("The critical fallback URL is not set"); if (string.IsNullOrEmpty(_tenantSelectorFallbackUrl)) _tenantSelectorFallbackUrl = null; if (useWeb) { _webPort = configuration.GetValue<int>("WebServer:WebPort"); } if (useApi) { _apiPort = configuration.GetValue<int>("WebServer:ApiPort"); } _translationsProvider = serviceProvider.GetService<ITranslationsProvider>(); _dataProtectionProvider = dataProtectionProvider; } public async Task InvokeAsync(HttpContext context) { ApiException resultException = null; try { await _next.Invoke(context).ConfigureAwait(false); } catch (ApiException e) { resultException = e; } catch (JsonSerializationException e) { resultException = new RequestFailedApiException(RequestFailedApiException.ArgumentInvalid, e.Message); } catch (NotImplementedException e) { _logger.LogError($"Not implemented exception: {e}"); resultException = new NotImplementedApiException(); } catch (Exception e) { if (!string.IsNullOrEmpty(e.Message) && e.Message.Contains("IDX20803")) { resultException = new ServiceUnavailableApiException(ServiceUnavailableApiException.AuthorizationAuthorityNotAvailable, "The authorization authority for this service is currently not available. Your access credentials cannot be validated. Please try again later"); } else { _logger.LogError($"Unexpected server error: {e}"); resultException = new InternalServerErrorApiException(); } } if (resultException != null) { await HandleResultExceptionAsync(context, resultException).ConfigureAwait(false); } } private async Task HandleResultExceptionAsync(HttpContext context, ApiException resultException) { string path = context.Request.Path; if (string.Equals(resultException.GetErrorCode(), NotFoundApiException.TenantNotFound) && _tenantSelectorFallbackUrl != null && !string.Equals(path, _tenantSelectorFallbackUrl)) { // redirect to the tenant selector context.Response.Redirect(_tenantSelectorFallbackUrl); return; } if (_webPort == null || context.Connection.LocalPort != _webPort) { // we have a call to some endpoint outside of our web interface, so just return the error JSON await resultException.WriteResponseAsync(context).ConfigureAwait(false); return; } // we have a call to our web interface, we need to go to the error page // but not twice, because then we'd run in circles if (!string.IsNullOrEmpty(path) && path.ToLower().StartsWith("/error")) { // we ARE already on the error page, use critical fallback URL context.Response.Redirect(_criticalFallbackUrl); return; } string errorCode = resultException.GetErrorCode(); string errorDescription = resultException.Message; if (_translationsProvider != null) errorDescription = _translationsProvider.TranslateError(resultException.GetErrorCode(), resultException.Message, resultException.Uuid, resultException.Name); if (!string.IsNullOrEmpty(errorDescription)) errorDescription = _dataProtectionProvider.CreateProtector("Error").Protect(errorDescription); context.Response.Redirect($"/Error?errorCode={HttpUtility.UrlEncode(errorCode ?? "")}&errorDescription={HttpUtility.UrlEncode(errorDescription ?? "")}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Microsoft.BotBuilderSamples.Models { public class UserProfile { public string Greeted { get; set; } = "not greeted"; public List<string> UtteranceList { get; private set; } = new List<string>(); public string Language { get; set; } } public class ConversationData { public string ChannelId { get; set; } public string Timestamp { get; set; } public bool PromptedUserForName { get; set; } } }
using UnityEngine; using System.Collections; public class CameraController : MonoBehaviour { public bool followPlayer = true; public float speed = 10f; public Transform player; private Transform target; private Vector3 mousePos; void Awake () { if (player == null) Debug.LogError("No target Player found attached to this gameObject! [CAMERA_CONTROLLER.CS]"); } void Start () { mousePos = GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition); } void LateUpdate () { mousePos = GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition); mousePos.z = -10; if (followPlayer) this.transform.position = new Vector3(player.position.x, player.position.y, -10); else this.transform.position = Vector3.MoveTowards (this.transform.position, (player.position*2.5f + mousePos) /7*2 , speed * Time.deltaTime); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterInput : MonoBehaviour { public Character character { get; protected set; } public Vector2 input { get; set; } public Vector2 rawInput { get; set; } private void Awake () { character = GetComponent<Character> (); } private void Update () { if (character.IsAI) return; CheckAim (); input = new Vector2 ( Input.GetAxis ( "Horizontal" ), Input.GetAxis ( "Vertical" ) ).normalized; rawInput = new Vector2 ( Input.GetAxisRaw ( "Horizontal" ), Input.GetAxisRaw ( "Vertical" ) ).normalized; if (Input.GetKeyDown ( KeyCode.C )) { character.isCrouchingInput = !character.isCrouchingInput; } character.isRunning = Input.GetKey ( KeyCode.LeftShift ); if (Input.GetKeyDown ( KeyCode.Space )) { character.shouldJump = true; } } public bool isAimInput { get; protected set; } = false; private void CheckAim () { //if (character.cWeapon.ShouldAim) //{ //isAimInput = true; //return; //} isAimInput = Input.GetKey ( KeyCode.V ) || Input.GetMouseButton ( 1 ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Data; using System.Data.Common; using Testr.Models.Commands; using Testr.Models.Queries; namespace Testr.Models { public class Repository { public T Load<T>(IQuery<T> query) { var cs = ConfigurationManager.ConnectionStrings["db"]; var factory = DbProviderFactories.GetFactory(cs.ProviderName); using (var connection = factory.CreateConnection()) { connection.ConnectionString = cs.ConnectionString; connection.Open(); return query.Execute(connection, null); } } public T Save<T>(IQuery<T> query) { var cs = ConfigurationManager.ConnectionStrings["db"]; var factory = DbProviderFactories.GetFactory(cs.ProviderName); using (var connection = factory.CreateConnection()) { connection.ConnectionString = cs.ConnectionString; connection.Open(); using (var transaction = connection.BeginTransaction()) { try { var o = query.Execute(connection, transaction); transaction.Commit(); return o; } catch (Exception e) { transaction.Rollback(); throw; } } } } } }
namespace BlockchainNet.Core.Communication { using System.Threading.Tasks; public interface ICommunicationClient<T> : ICommunication { /// <summary> /// Id сервера для обратной связи /// </summary> string ResponceServerId { get; set; } /// <summary> /// Асинхронный метод для отправки сообщения /// </summary> /// <param name="message">Сообщение</param> /// <returns>True если отправка успещна, иначе False</returns> Task<bool> SendMessageAsync(T message); } }
using System; using CoreLocation; using Aquamonix.Mobile.Lib.Utilities; namespace Aquamonix.Mobile.IOS.Utilities { public class LocationUtilityIos : ILocationUtility { private static CLLocation _location = null; public double DistanceInMetersFrom(double latitude, double longitude) { double output = -1; CLLocationManager locationManager = new CLLocationManager(); locationManager.RequestWhenInUseAuthorization(); if (locationManager.Location != null) _location = locationManager.Location; if (_location != null) { CLLocation location2 = new CLLocation(_location.Coordinate.Latitude, _location.Coordinate.Longitude); output = location2.DistanceFrom(new CLLocation(latitude, longitude)); } return output; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IRAP.Entity.MDM { public class ProductionLineOfProduct { public int Ordinal { get; set; } public int T134LeafID { get; set; } public string T134Code { get; set; } public string T134Name { get; set; } public ProductionLineOfProduct Clone() { return MemberwiseClone() as ProductionLineOfProduct; } } }
using System; namespace ConsoleApp1 { public class Program { static void Main(string[] args) { Person p = new Person(); //p.SetName ("Вася"); p.Name = ("Вася"); p.SecondName = ("Пупкин "); //Console.WriteLine(p.GetName()); Console.WriteLine(p.Name); Console.WriteLine(p.FullName); Console.WriteLine(p.ShotName); Console.ReadLine(); Console.ReadKey(); } } }
using ChatSupport.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ChatSupport.ViewModels { public class ChatViewModel { [ScaffoldColumn(false)] public int ChatId { get; set; } [Display(Description = "Customer")] public string ClientUserName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace csharp_fun { public static class OddOccurrencesInArray { //A non-empty zero-indexed array A consisting of N integers is given.The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. //For example, in array A such that: // A[0] = 9 A[1] = 3 A[2] = 9 // A[3] = 3 A[4] = 9 A[5] = 7 // A[6] = 9 //the elements at indexes 0 and 2 have value 9, //the elements at indexes 1 and 3 have value 3, //the elements at indexes 4 and 6 have value 9, //the element at index 5 has value 7 and is unpaired. //Write a function: //int solution(int A[], int N); //that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. //For example, given array A such that: //A[0] = 9 A[1] = 3 A[2] = 9 //A[3] = 3 A[4] = 9 A[5] = 7 //A[6] = 9 //the function should return 7, as explained in the example above. //Assume that: //N is an odd integer within the range [1..1,000,000]; //each element of array A is an integer within the range[1..1, 000, 000, 000]; //all but one of the values in A occur an even number of times. //Complexity: //expected worst-case time complexity is O(N); //expected worst-case space complexity is O(1), beyond input storage(not counting the storage required for input arguments). public static void Run() { List<int[]> ec = new List<int[]>(); //int[] a = new int[] { -1, 1, 3, 6, 4, 1, 2 }; ec.Add(new int[] { 9, 3, 9, 3, 9, 7, 9 }); ec.Add(new int[] { 1, 1, 3, 6, 4, 1, 2 }); ec.Add(new int[] { 1, 2, 3 }); ec.Add(new int[] { 1, 3 }); ec.Add(new int[] { 0, 3, 0, 3, 9, 7, 9 }); foreach (var item in ec) { int oddOccurrences = solution(item); Console.WriteLine("Odd Occurrences In Array" + item.ToArray() + " is " + oddOccurrences); } Console.WriteLine("Press any key to Continue"); Console.Read(); } static public int solution(int[] A) { // write your code in C# 6.0 with .NET 4.5 (Mono) try { return A.Where(m => m > 0).GroupBy(c => c).Where(c => c.Count() == 1).Select(s => s.Key).LastOrDefault(); } catch (Exception) { return -1; } } } }
using System; using System.Collections.Generic; using System.Linq; using Mastermind.NET.Models; using Mastermind.NET.Utility; using Mastermind.NET.Validation; namespace Mastermind.NET { internal class Program { /// <summary> /// Startup and main game loop function. /// </summary> /// <param name="args">Arguments passed from the command line.</param> private static void Main(string[] args) { var state = new GameState(); Console.WriteLine("I am thinking of a number. Can you guess what it is?"); Console.WriteLine("Enter four digits between 1 and 6 and press enter."); while (!state.MaxAttemptsReached) { var guess = Console.ReadLine(); if (!InputIsValid(guess, out var guessDigits)) continue; // Ok. We know this is valid, so we can actually work with it now. First, increment the attempts. state.IncrementAttempts(); // Run it through the validator. var validationResult = GuessValidator.Validate(state, guessDigits); // Print the "you won the game" message, if you in fact won the game. if (validationResult.VictoryCondition) { Console.WriteLine($"You won in {state.Attempts} attempt(s)!"); Environment.Exit(0); } else { // Print any positioning info we're going to provide to the user, assuming there is any. if (!validationResult.GuessResult.IsNullOrWhiteSpace()) Console.WriteLine(validationResult.GuessResult); } } // Maximum attempts exhausted; regretful message and a quick goodbye. // You'll note this returns an exit code back to the environment upon termination; // though it's really not a big deal here given this is a toy game, it's good practice // to return an exit code from applications so calling scripts can use that for flow // control if needed. Console.WriteLine("I'm afraid you are not a winner. Have a nice day."); Environment.Exit(1); } /// <summary> /// Validates whether an input string is 4 characters long and contains only digits between 1 and 6. /// </summary> /// <param name="guess">Raw input guess from the console.</param> /// <param name="guessDigits">List (int) of guess digits - out param returned as part of the process of checking /// whether all digits are valid.</param> /// <returns>Boolean indicating if the string is valid or not.</returns> private static bool InputIsValid(string guess, out List<int> guessDigits) { guessDigits = new List<int>(); // Validate that it's only 4 characters. if (guess.Length != 4) { Console.WriteLine("Please only enter four digits. No more and no less."); return false; } // Validate that all characters are digits. if (!guess.All(char.IsDigit)) { Console.WriteLine("Please only enter digits between 1 and 6"); return false; } // Coerce the string input to integers. This is a little gross; I could also do .TryParse() here but // it's a bit superfluous since we just LINQ .All()'ed the string verifying that all we have are digits. foreach (var digit in guess) guessDigits.Add(int.Parse(digit.ToString())); // Validate all digits are between 1 and 6. if (guessDigits.Any(gd => gd < 1 || gd > 6)) { Console.WriteLine("Please only enter digits between 1 and 6."); return false; } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Engine { public class Bound: BaseComponent { public Plane BoundingPlane = new Plane(); public bool Intersect(ModelRenderer modelRenderer) { return modelRenderer.BoundingSphere.Transform(modelRenderer.GameObject.GlobalTransform).Intersects( BoundingPlane) == PlaneIntersectionType.Intersecting; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class KeyBindingContract { }
using System.Linq; using GridMvc; using Welic.Dominio.Models.Marketplaces.Entityes; namespace WebApi.Models.Grids { public class ListingTypesGrid : Grid<ListingType> { public ListingTypesGrid(IQueryable<ListingType> ListingTypes) : base(ListingTypes) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class HUDManager : MonoBehaviour { public Text score; public Text lives; public Text enemiesKilled; public Text time; void Update () { //Keeps HUD Updated score.text = "Score: " + Player.Get().ReturnScore().ToString(); lives.text = "Lives: " + Player.Get().ReturnLives().ToString(); enemiesKilled.text = "Enemies Killed: " + Player.Get().ReturnEnemiesKilled().ToString(); time.text = "Time: " + Player.Get().ReturnTime().ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MyContacts.WebApi.Infrastructure; namespace MyContacts.WebApi.Controllers { [ApiController] [Route("api/contacts/{contactId:int}/phones")] public class PhonesController : ControllerBase { [HttpGet] public IActionResult GetPhones(int contactId) { var contactDto = DataService.Current.Contacts.FirstOrDefault(c => c.Id == contactId); if (contactDto == null) { return NotFound(); } return Ok(contactDto.Phones); } [HttpGet("{id:int}")] public IActionResult GetPhone(int contactId, int id) { var contactDto = DataService.Current.Contacts.FirstOrDefault(c => c.Id == contactId); if (contactDto == null) { return NotFound(); } var phoneDto = contactDto.Phones.FirstOrDefault(p => p.Id == id); if (phoneDto == null) { return NotFound(); } return Ok(phoneDto); } } }
using System; using System.Collections.Generic; using System.Text; namespace PaperPlane.API.ProtocolSchema.Internal { [System.AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] sealed class BareAttribute : Attribute { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DTO; using System.Data.OleDb; namespace DAO { /// <summary> /// Thanh Phuc /// </summary> public class TuKhoaPhuongDAO : AbstractDAO { /// <summary> /// /// </summary> /// <param name="dsCumTu"></param> /// <returns> </returns> public static int TimPhuong(List<string> dsCumTu) { OleDbConnection ketNoi = null; int maPhuong = -1; try { ketNoi = MoKetNoi(); string chuoiLenh = "SELECT MaTuKhoaPhuong FROM TUKHOAPHUONG WHERE TuKhoaPhuong Like @CumTu"; foreach (string cumTu in dsCumTu) { OleDbCommand lenh = new OleDbCommand(chuoiLenh, ketNoi); OleDbParameter thamSo = new OleDbParameter("@CumTu", OleDbType.VarChar); thamSo.Value = cumTu; lenh.Parameters.Add(thamSo); OleDbDataReader boDoc = lenh.ExecuteReader(); if (boDoc.Read()) { maPhuong = boDoc.GetInt32(0); break; } } } catch (Exception ex) { maPhuong = -1; } finally { if (ketNoi != null && ketNoi.State == System.Data.ConnectionState.Open) ketNoi.Close(); } return maPhuong; } } /// <summary> /// Thanh Phuc /// </summary> }
using Microsoft.Extensions.DependencyInjection; namespace DB_CQRS.DB.CommandQueryHandler { public static class ConfigureServices { public static void AddEFDatabase(this IServiceCollection serviceCollection) { serviceCollection.AddTransient<OrderCommandHandlers>(); } } }
/*********************************************************************** * Module: TypeOfExamination.cs * Author: Sladjana Savkovic * Purpose: Definition of the Class TypeOfExamination ***********************************************************************/ using System; namespace Model.Doctor { public enum TypeOfExamination { Opsti = 0, Specijalisticki = 1, Operacija = 2 } }
using System; using Microsoft.Framework.Configuration; using Quartz; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Autofac; using Npgsql; using NPoco; using SciVacancies.Domain.Enums; using Microsoft.Framework.Logging; using SciVacancies.Services.Elastic; using Nest; namespace SciVacancies.SearchSubscriptionsService.Jobs { public class SearchSubscriptionJob : IJob { private readonly ILifetimeScope _lifetimeScope; private readonly ILogger _logger; public SearchSubscriptionJob(ILifetimeScope lifetimeScope, ILoggerFactory loggerFactory) { _lifetimeScope = lifetimeScope; _logger = loggerFactory.CreateLogger<SearchSubscriptionJob>(); } /// <summary> /// выполнить работу /// </summary> /// <param name="context"></param> public void Execute(IJobExecutionContext context) { ExecuteJob(); } /// <summary> /// выполнить работу /// </summary> public void ExecuteJob() { _logger.LogInformation("SearchSubscriptionJob started"); try { var dataBase = _lifetimeScope.Resolve<IDatabase>(); _logger.LogInformation($"SearchSubscriptionJob: Select Subscriptions from DB"); Queue<ReadModel.Core.SearchSubscription> subscriptionQueue = new Queue<ReadModel.Core.SearchSubscription>(dataBase.Fetch<ReadModel.Core.SearchSubscription>(new Sql($"SELECT * FROM res_searchsubscriptions ss WHERE ss.status = @0", SearchSubscriptionStatus.Active))); _logger.LogInformation($"SearchSubscriptionJob: Found {subscriptionQueue.Count} Subscriptions in DB"); //int poolCount = 20; //var threadSize = subscriptionQueue.Count > poolCount // ? (subscriptionQueue.Count / poolCount) + 1 // : 1; //_logger.LogInformation($"SearchSubscriptionJob: threadSize = {threadSize}"); //var i = 0; //var actions = new List<Action>(); //while (subscriptionQueue.Skip(threadSize * i).Take(threadSize).Any()) //{ // var y = i; // var scanner = _lifetimeScope.Resolve<ISearchSubscriptionScanner>(); // actions.Add(() => // { // scanner.Initialize(subscriptionQueue.Skip(threadSize * y).Take(threadSize)); // scanner.PoolHandleSubscriptions(); // }); // i++; //} //var actionsArray = actions.ToArray(); _logger.LogInformation("SearchSubscriptionJob: Обработка потоков началась"); //Parallel.Invoke(actionsArray); var scanner = _lifetimeScope.Resolve<ISearchSubscriptionScanner>(); _logger.LogInformation("SearchSubscriptionJob: Scanner initializaing"); scanner.Initialize(subscriptionQueue); _logger.LogInformation("SearchSubscriptionJob: Scanner initialized"); _logger.LogInformation("SearchSubscriptionJob: Scanner subsciptions starting to invoke"); scanner.PoolHandleSubscriptions(); _logger.LogInformation("SearchSubscriptionJob: Scanner subsciptions finished to invoke"); _logger.LogInformation("SearchSubscriptionJob: Обработка потоков завершена"); } catch (Exception e) { _logger.LogError(e.Message, e); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShowMeDateDataLayer { public class ShowMeDateDataLayer { public string GetDate() { String today = DateTime.Today.ToShortDateString(); return today; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameStart : MonoBehaviour { private float wait_time = 3f; private void Awake() { Invoke("YouCanMove", wait_time); } private void YouCanMove() { Debug.Log("CanMove"); GameController.AnyDownStart(); } }
using System; namespace demo2 { class Solution { public static int solution(int[] A) { int ans = 0; for (int i = 1; i <= A.Length; i++) { ans = ans + A[i]; } return ans; } static void Main() { int []A ={-1,-2,9,7}; Console.Write(solution(A)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FrecuenciaStrategy { class FrecuenciaTrimestral : FrecuenciaEspecifica { /** * Requiere medición si el día de hoy es fin de mes y hace tres meses o más que se realizó la última medición * * **/ public override bool RequiereMedicion(DateTime ultimaMedicion) { int ultimoDiaMes = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); return /*ultimoDiaMes == DateTime.Now.Day &&*/ ProximaMedicion(ultimaMedicion) <= DateTime.Now; } public override DateTime ProximaMedicion(DateTime ultimaMedicion) { return ultimaMedicion.AddMonths(3); } } }
using Lucene.Net.Analysis; using Lucene.Net.Analysis.PanGu; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Store; using PanGu; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using LnVersion = Lucene.Net.Util.Version; namespace LuceneServer { /// <summary> /// Lucene.Net操作封装 /// </summary> internal static class LnHelper { /// <summary> /// 写入锁 /// </summary> private static object _writerSyncRoot = new object(); /// <summary> /// 分析器 /// </summary> private static Analyzer _analyzer = new PanGuAnalyzer(); /// <summary> /// 索引目录 /// </summary> private static ConcurrentDictionary<string, Directory> _indexStores = new ConcurrentDictionary<string, Directory>(StringComparer.OrdinalIgnoreCase); /// <summary> /// 获取索引是否已存在 /// </summary> /// <param name="indexName">索引名</param> /// <returns></returns> private static bool ExistsIndex(string indexName) { return System.IO.File.Exists(System.IO.Path.Combine("Indexs/" + indexName, "segments.gen")); } /// <summary> /// 获取索引存储目录 /// </summary> /// <param name="indexName">索引名</param> /// <returns></returns> private static Directory GetIndexStore(string indexName) { return _indexStores.GetOrAdd(indexName, (key) => { var indexPath = "Indexs/" + key; System.IO.Directory.CreateDirectory(indexPath); var dirInfo = new System.IO.DirectoryInfo(indexPath); return FSDirectory.Open(dirInfo); }); } /// <summary> /// 提供安全执行Reader操作 /// </summary> /// <typeparam name="T">返回类型</typeparam> /// <param name="indexName">索引名</param> /// <param name="func">Func</param> /// <returns></returns> private static T InvokeReaderNoLock<T>(string indexName, Func<IndexReader, T> func) { var indexStore = GetIndexStore(indexName); using (var reader = IndexReader.Open(indexStore, true)) { return func(reader); } } /// <summary> /// 提供安全执行Writer操作 /// </summary> /// <param name="indexName">索引名</param> /// <param name="action">Action</param> private static void InvokeWriterWithLock(string indexName, Action<IndexWriter> action) { lock (_writerSyncRoot) { var indexStore = GetIndexStore(indexName); using (var writer = new IndexWriter(indexStore, _analyzer, !ExistsIndex(indexName), IndexWriter.MaxFieldLength.LIMITED)) { action(writer); writer.Commit(); } } } /// <summary> /// 创建或更新到索引 /// </summary> /// <param name="indexName">索引名称</param> /// <param name="models">模型</param> /// <returns></returns> public static bool SetIndex(string indexName, IEnumerable<LnModel> models) { InvokeWriterWithLock(indexName, (writer) => { foreach (var model in models) { writer.DeleteDocuments(model.GetTerm()); writer.AddDocument(model.ToDocument()); } }); return true; } /// <summary> /// 删除索引的全部记录 /// </summary> /// <param name="indexName">索引名称</param> /// <returns></returns> public static bool DeleteIndex(string indexName) { InvokeWriterWithLock(indexName, (writer) => { writer.DeleteAll(); }); return true; } /// <summary> /// 删除索引的记录 /// </summary> /// <param name="indexName">索引名称</param> /// <param name="idFields">记录的Id字段</param> /// <returns></returns> public static bool DeleteIndex(string indexName, IEnumerable<LnField> idFields) { InvokeWriterWithLock(indexName, (writer) => { writer.DeleteDocuments(idFields.Select(item => item.ToTerm()).ToArray()); }); return true; } /// <summary> /// 搜索索引 /// </summary> /// <param name="q">查询对象</param> /// <returns></returns> public static LnPage SearchIndex(LnQuery q) { if (ExistsIndex(q.IndexName) == false) { return new LnPage { Models = new LnModel[0] }; } return InvokeReaderNoLock(q.IndexName, (reader) => { using (var searcher = new IndexSearcher(reader)) { var matchFields = q.MatchFields == null ? null : q.MatchFields.Select(item => item.Name).ToArray(); var parser = new MultiFieldQueryParser(LnVersion.LUCENE_30, matchFields, _analyzer); var query = parser.Parse(q.Keywords); Sort sort = null; if (q.SortFields != null && q.SortFields.Length > 0) { sort = new Sort(q.SortFields.Select(f => f.ToSortField()).ToArray()); } var docs = sort == null ? searcher.Search(query, null, q.MaxSearchCount) : searcher.Search(query, null, q.MaxSearchCount, sort); var models = docs.ScoreDocs.Skip(q.Skip).Take(q.Take).Select(item => DocToLnModel(searcher.Doc(item.Doc))).ToArray(); foreach (var model in models) { model.SetHighLight(q.Keywords, q.MatchFields); } return new LnPage { Models = models, TotalCount = docs.TotalHits }; } }); } /// <summary> /// Document对象转换为LnModel /// </summary> /// <param name="doc">Document</param> /// <returns></returns> private static LnModel DocToLnModel(Document doc) { var fields = doc.GetFields().Select(field => new LnField { Name = field.Name, Value = field.StringValue }); return new LnModel(fields); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Runtime.Serialization; using System.Threading.Tasks; using Newtonsoft.Json; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Web.Editors; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; namespace Umbraco.SampleSite.Controllers { [PluginController("Starterkit")] public class LessonsController : UmbracoAuthorizedJsonController { /// <summary> /// Fetches available lessons for a given section from our.umbaco.org /// </summary> /// <param name="path">Name of the documentation section to fetch from, ex: "getting-started", "Tutorials/Starter-kit/Lessons" </param> /// <returns></returns> [ValidateAngularAntiForgeryToken] public async Task<IEnumerable<Lesson>> GetLessons(string path) { //information for the request, so we could in the future filter by user, allowed sections, langugae and user-type var user = Security.CurrentUser; var userType = user.UserType.Alias; var allowedSections = string.Join(",", user.AllowedSections); var language = user.Language; var version = UmbracoVersion.GetSemanticVersion().ToSemanticString(); //construct the url and cache key var url = string.Format("https://our.umbraco.org/Umbraco/Documentation/Lessons/GetDocsForPath?path={0}&userType={1}&allowedSections={2}&lang={3}&version={4}", path, userType, allowedSections, language, version); var key = "umbraco-lessons-" + userType + language + allowedSections.Replace(",", "-") + path; var result = new List<Lesson>(); Func<List<Lesson>> fetchLesson = () => { try { using (var web = new HttpClient()) { //fetch dashboard json and parse to JObject var json = web.GetStringAsync(url); result = JsonConvert.DeserializeObject<IEnumerable<Lesson>>(json.Result).ToList(); } } catch (HttpRequestException ex) { //Log it so we are aware there was an issue LogHelper.Debug<LessonsController>(string.Format("Error getting lesson content from '{0}': {1}\n{2}", url, ex.Message, ex.InnerException)); //The result is still a new/empty JObject() - So we will return it like this to avoid error codes which triggers UI warnings //So this will cache an empty response until cache expires } return result; }; //Get cache item or add new cache item with func result = ApplicationContext.ApplicationCache.RuntimeCache.GetCacheItem<List<Lesson>>(key, fetchLesson, new TimeSpan(0, 30, 0)); return result; } /// <summary> /// This gets the steps that make up a specific lesson /// </summary> /// <param name="path"></param> /// <returns></returns> [ValidateAngularAntiForgeryToken] public async Task<IEnumerable<LessonStep>> GetLessonSteps(string path) { var url = string.Format("https://our.umbraco.org/Umbraco/Documentation/Lessons/GetStepsForPath?path={0}", path); using (var web = new HttpClient()) { //fetch dashboard json and parse to JObject var json = await web.GetStringAsync(url); return JsonConvert.DeserializeObject<List<LessonStep>>(json); } } } /// <summary> /// Simple POCO for binding JSON from our.umbraco WebAPI /// </summary> [DataContract(Name = "lesson")] public class Lesson { [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "path")] public string Path { get; set; } [DataMember(Name = "level")] public string Level { get; set; } [DataMember(Name = "url")] public string Url { get; set; } [DataMember(Name = "directories")] public IEnumerable<Lesson> Directories { get; set; } } /// <summary> /// Simple POCO for binding JSON from our.umbraco WebAPI /// </summary> [DataContract(Name = "LesssonStep")] public class LessonStep { [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "content")] public string Content { get; set; } } }
using Enviosbase.Data; using Enviosbase.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Enviosbase.Business { public class MarcaBusiness { public int Create(MarcaModel item) { return new MarcaDataMapper().Create(item); } public void Update(MarcaModel item) { MarcaDataMapper MarcaDM = new MarcaDataMapper(); MarcaDM.Update(item); } public List<MarcaModel> GetAll() { return new MarcaDataMapper().GetAll(); } public MarcaModel GetById(int Id) { return new MarcaDataMapper().GetById(Id); } } }
using System; namespace GenericDataAcessLayer { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); new DataAcessUtil().Search<Person>(new object()); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using HappyBall.Models; namespace HappyBall.Controllers.Api { public class UserLocationController : ApiController { private UserManager<ApplicationUser> manager; private ApplicationDbContext db = new ApplicationDbContext(); public UserLocationController() { manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)); } // GET api/UserLocation public IQueryable<UserLocation> GetUserLocations() { return db.UserLocations; } // GET api/UserLocation/5 [ResponseType(typeof(UserLocation))] [System.Web.Http.Route("api/userlocation/team", Name = "GetUserLocationByTeam")] public IHttpActionResult GetUserLocationByTeam() { var currentUserId = User.Identity.GetUserId(); var currentTeamName = manager.FindById(currentUserId).TeamName; var result = db.UserLocations.Where(x => x.TeamName == currentTeamName).FirstOrDefault(); //UserLocation userlocation = db.UserLocations.Find(id); //if (userlocation == null) //{ // return NotFound(); //} return Ok(result); } // PUT api/UserLocation/5 public IHttpActionResult PutUserLocation(int id, UserLocation userlocation) { //get user id and teamname var currentUserId = User.Identity.GetUserId(); var currentTeamName = manager.FindById(currentUserId).TeamName; userlocation.TeamName = currentTeamName; if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != userlocation.Id) { return BadRequest(); } db.Entry(userlocation).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!UserLocationExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST api/UserLocation [ResponseType(typeof(UserLocation))] public IHttpActionResult PostUserLocation(UserLocation userlocation) { var currentUserId = User.Identity.GetUserId(); var currentTeamName = manager.FindById(currentUserId).TeamName; userlocation.TeamName = currentTeamName; if (!ModelState.IsValid) { return BadRequest(ModelState); } db.UserLocations.Add(userlocation); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = userlocation.Id }, userlocation); } // DELETE api/UserLocation/5 [ResponseType(typeof(UserLocation))] public IHttpActionResult DeleteUserLocation(int id) { UserLocation userlocation = db.UserLocations.Find(id); if (userlocation == null) { return NotFound(); } db.UserLocations.Remove(userlocation); db.SaveChanges(); return Ok(userlocation); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool UserLocationExists(int id) { return db.UserLocations.Count(e => e.Id == id) > 0; } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using SpatialEye.Framework.Geometry; using SpatialEye.Framework.Units; namespace Lite { /// <summary> /// The abstract base class for measurers to be used with the corresponding /// interaction mode. /// </summary> public abstract class LiteMapMeasurerBase { #region Delegates /// <summary> /// Delegate used for notifying changes in segment length /// </summary> internal delegate void SegmentLengthTextChangedDelegate(LiteMapMeasurerBase sender, string text); /// <summary> /// Delegate used for notifying changes in total length /// </summary> internal delegate void TotalLengthTextChangedDelegate(LiteMapMeasurerBase sender, string text); /// <summary> /// Delegate used for notifying changes in area /// </summary> internal delegate void AreaTextChangedDelegate(LiteMapMeasurerBase sender, string text); /// <summary> /// Delegate used for notifying changes in geometry /// </summary> internal delegate void FeatureGeometryChangedDelegate(LiteMapMeasurerBase sender, List<FrameworkElement> geometry); #endregion #region Static Annotation Helpers /// <summary> /// A static helper for determining the length (in meters) between specified pixel coordinates /// </summary> protected static double LengthInMeters(CoordinateSystem cs, ITransform txfm, Coordinate pixelCd1, Coordinate pixelCd2) { Coordinate worldCd1 = pixelCd1.Transformed(txfm); Coordinate worldCd2 = pixelCd2.Transformed(txfm); var ls = new LineString(cs, worldCd1, worldCd2); var lengthType = cs.IsLocal ? LinearLineLengthType.Meter : LinearLineLengthType.Geodetic; return ls.LineLength(lengthType); } /// <summary> /// Transforms the length to a human readable string, making use of the active unit system /// </summary> protected static String LengthInMetersToString(double length) { return UnitSystem.Convert(length, "m").ToString(); } /// <summary> /// Transforms the area to a human readable string, making use of the active unit system /// </summary> protected static String AreaInMetersToString(double area) { return UnitSystem.Convert(area, "m2").ToString(); } /// <summary> /// Calculates the area contribution of the given ring /// </summary> protected static double CalculateAreaContribution(Ring closedRing) { double result = 0; if (closedRing != null && closedRing.IsClosed) { result = Math.Abs(closedRing.AreaContribution(SurfaceAreaType.Geodetic)); } return result; } /// <summary> /// Creates a closed ring from the given coordinates /// </summary> /// <param name="coordinates">coordinates of the linestring</param> /// <param name="newCoord">optional coordinate to add</param> /// <returns>a new closed ring</returns> protected static Ring CreateClosedRing(CoordinateSystem cs, IList<Coordinate> coordinates, Coordinate newCoord = null) { Ring result = null; if (coordinates != null && coordinates.Count > 1) { LineString lineString = new LineString(cs, coordinates); if (newCoord != null) { lineString.Add(newCoord); } Ring ring = new Ring(lineString); ring.Close(); result = ring; } return result; } /// <summary> /// Determines the point (as a polygon) at a specified coordinate /// </summary> protected static System.Windows.Shapes.Polygon PointPolygonFor(Coordinate coord, double angle, double size, Brush brush) { var polygon = new System.Windows.Shapes.Polygon(); var cd1 = Coordinate.NewAtDistanceAngleFrom(coord, size, angle - Math.PI / 2.0 + Math.PI / 10); var cd2 = Coordinate.NewAtDistanceAngleFrom(coord, size, angle - Math.PI / 2.0 - Math.PI / 10); polygon.Points = new System.Windows.Media.PointCollection(); polygon.Points.Add(new System.Windows.Point(coord.X, coord.Y)); polygon.Points.Add(new System.Windows.Point(cd1.X, cd1.Y)); polygon.Points.Add(new System.Windows.Point(cd2.X, cd2.Y)); polygon.Points.Add(new System.Windows.Point(coord.X, coord.Y)); polygon.Stroke = brush; polygon.Fill = brush; return polygon; } /// <summary> /// Creates the annotation for the specified coordinate, style and length /// </summary> protected static FrameworkElement AnnotationForLength(CoordinateSystem cs, Coordinate coord, double angle, Brush style, double size, double lengthInMeters, TextAlignment alignment, int extraDistance) { var realAngle = 180 * angle / Math.PI; var annotation = new TextBlock() { Text = LengthInMetersToString(lengthInMeters), FontSize = size, TextAlignment = alignment }; var x = coord.X - Math.Cos(angle) * extraDistance; var y = coord.Y - Math.Sin(angle) * extraDistance; var txfm = new TransformGroup(); txfm.Children.Add(new RotateTransform { Angle = realAngle }); txfm.Children.Add(new TranslateTransform { X = x, Y = y }); annotation.RenderTransform = txfm; return annotation; } protected static FrameworkElement AnnotationForArea(CoordinateSystem cs, Coordinate coord, Brush style, double size, double areaInMeters) { var annotation = new TextBlock() { Text = AreaInMetersToString(areaInMeters), FontSize = size, TextAlignment = TextAlignment.Center }; var x = coord.X; var y = coord.Y; var txfm = new TransformGroup(); txfm.Children.Add(new TranslateTransform { X = x, Y = y }); annotation.RenderTransform = txfm; return annotation; } #endregion #region Static fields /// <summary> /// The zero length string /// </summary> private static string _lengthZeroString = UnitSystem.Convert(0.0, "m").ToString(); #endregion #region Fields /// <summary> /// The resulting geometry /// </summary> private List<FrameworkElement> _geometry; /// <summary> /// The list of coordinates /// </summary> private List<Coordinate> _coordinates = new List<Coordinate>(); /// <summary> /// The last known mouse position /// </summary> private Coordinate _lastMouseCoordinate; /// <summary> /// The last coordinate /// </summary> private Coordinate _lastCoordinate; /// <summary> /// The meters per pixel /// </summary> private double _metersPerPixel; /// <summary> /// The cs units per pixel /// </summary> private double _CSUnitsPerPixel; #endregion #region Constructor /// <summary> /// Default constructor /// </summary> internal LiteMapMeasurerBase() { Initialize(); } #endregion #region protected abstract void Initialize(); /// <summary> /// Sets the geometry /// </summary> protected List<FrameworkElement> FeatureGeometry { get { return _geometry; } set { _geometry = value; RaiseFeatureGeometryChanged(_geometry); } } /// <summary> /// Holds the coordinates /// </summary> protected IList<Coordinate> Coordinates { get { return _coordinates; } } /// <summary> /// Holds the last coordinate /// </summary> protected Coordinate LastCoordinate { get { return _lastCoordinate; } set { _lastCoordinate = value; } } /// <summary> /// Holds the last mouse coordinate /// </summary> protected Coordinate LastMouseCoordinate { get { return _lastMouseCoordinate; } set { _lastMouseCoordinate = value; } } /// <summary> /// Returns the display coordinate system /// </summary> internal CoordinateSystem CoordinateSystem { get; set; } /// <summary> /// Returns the display coordinate system /// </summary> internal SpatialEye.Framework.Geometry.ITransform PixelToWorldTransform { get; set; } /// <summary> /// Raises that segment length has changed /// </summary> protected void RaiseStatusSegmentLengthChanged(string text) { var handler = SegmentLengthTextChanged; if (handler != null) { handler(this, text); } } /// <summary> /// Raises that segment length has changed /// </summary> protected void RaiseStatusSegmentLengthChanged(double length) { RaiseStatusSegmentLengthChanged(LengthInMetersToString(length)); } /// <summary> /// Raises that total length has changed /// </summary> protected void RaiseEmptySegmentLengthTextChanged() { var handler = SegmentLengthTextChanged; if (handler != null) { handler(this, _lengthZeroString); } } /// <summary> /// Raises that total length has changed /// </summary> protected void RaiseTotalLengthChanged(string text) { var handler = TotalLengthTextChanged; if (handler != null) { handler(this, text); } } /// <summary> /// Raises that segment length has changed /// </summary> protected void RaiseTotalLengthChanged(double length) { RaiseTotalLengthChanged(LengthInMetersToString(length)); } /// <summary> /// Raises that total length has changed /// </summary> protected void RaiseEmptyTotalLengthChanged() { var handler = TotalLengthTextChanged; if (handler != null) { handler(this, _lengthZeroString); } } /// <summary> /// Raises that area has changed /// </summary> protected void RaiseAreaChanged(string text) { var handler = AreaTextChanged; if (handler != null) { handler(this, text); } } /// <summary> /// Raises that the area to be displayed has changed. Interprets the specified /// area as an area in m2. /// </summary> protected void RaiseAreaChanged(double area) { RaiseAreaChanged(UnitSystem.Convert(area, "m2").ToString()); } /// <summary> /// Raises that the area to be displayed has changed. Interpretes all coordinates /// in the current display coordinate system (as specified by the func). /// </summary> protected void RaiseAreaChanged(IList<Coordinate> coordinates, Coordinate newCoord) { var handler = AreaTextChanged; if (handler != null) { if (coordinates != null && coordinates.Count > 1) { LineString lineString = new LineString(CoordinateSystem, coordinates); if (newCoord != null) { lineString.Add(newCoord); } Ring ring = new Ring(lineString); ring.Close(); RaiseAreaChanged(Math.Abs(ring.AreaContribution(SurfaceAreaType.Geodetic))); } else { RaiseAreaChanged("-"); } } } /// <summary> /// Raises a change in styled feature geometry, to be rendered by the measure component /// </summary> private void RaiseFeatureGeometryChanged(List<FrameworkElement> geometry) { var handler = FeatureGeometryChanged; if (handler != null) { handler(this, geometry); } } #endregion #region Properties and Events /// <summary> /// The event raised when status segment length text has changed /// </summary> internal event SegmentLengthTextChangedDelegate SegmentLengthTextChanged; /// <summary> /// The event raised when status total length text has changed /// </summary> internal event TotalLengthTextChangedDelegate TotalLengthTextChanged; /// <summary> /// The event raised when status area text has changed /// </summary> internal event AreaTextChangedDelegate AreaTextChanged; /// <summary> /// The event raised whenever the feature geometry has changed /// </summary> internal event FeatureGeometryChangedDelegate FeatureGeometryChanged; #endregion #region Public API /// <summary> /// Gets the resource key describing this mode /// </summary> public virtual String DescriptionResourceKey { get { return null; } } /// <summary> /// Start the interaction /// </summary> internal virtual void Start() { // Start with an empty element Clear(); } /// <summary> /// Start the interaction /// </summary> internal virtual void Stop() { // End with an empty element Clear(); } /// <summary> /// Clears the active elements /// </summary> internal virtual void Clear() { Coordinates.Clear(); LastCoordinate = null; LastMouseCoordinate = null; this.FeatureGeometry = new List<FrameworkElement>(); RaiseStatusSegmentLengthChanged(""); RaiseTotalLengthChanged(""); RaiseAreaChanged(""); } /// <summary> /// The meters per pixel /// </summary> internal double MetersPerPixel { get { return _metersPerPixel; } set { _metersPerPixel = value; OnMetersPerPixelChanged(_metersPerPixel); } } /// <summary> /// The CS Units per pixel /// </summary> internal double CSUnitsPerPixel { get { return _CSUnitsPerPixel; } set { _CSUnitsPerPixel = value; OnCSUnitsPerPixelChanged(_CSUnitsPerPixel); } } /// <summary> /// Returns the length in meters for a number of pixels /// </summary> internal double MetersForPixels(int pixels) { return pixels * _metersPerPixel; } /// <summary> /// Returns the length in Display CS Units to be used that /// correspond to a number of pixels /// </summary> internal double CSUnitsForPixels(int pixels) { return pixels * _CSUnitsPerPixel; } /// <summary> /// Add a coordinate /// </summary> internal abstract void AddCoordinate(Coordinate worldCoord); /// <summary> /// Move the coordinate /// </summary> /// <param name="worldCoord"></param> internal abstract void MoveCoordinate(Coordinate worldCoord); /// <summary> /// Move the coordinate /// </summary> /// <param name="worldCoord"></param> internal abstract void MoveAll(double divX, double divY); /// <summary> /// Deletes the last coordinate /// </summary> internal abstract void DeleteLastCoordinate(); /// <summary> /// Close the trail /// </summary> internal abstract void CloseMeasurer(); /// <summary> /// End the measuring /// </summary> internal virtual void EndMeasuring() { LastCoordinate = null; } internal virtual bool CanMoveScreen { get { return true; } } /// <summary> /// The meters per pixel changed /// </summary> internal virtual void OnMetersPerPixelChanged(double metersPerPixel) { } /// <summary> /// The cs units per pixel changed /// </summary> internal virtual void OnCSUnitsPerPixelChanged(double csUnitsPerPixel) { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.Object { [DataContract] public class APICarBrand { [DataMember(Name = "id")] public string carBrandId { get; set; } [DataMember(Name = "name")] public string carBrandName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APICarModel { [DataMember(Name = "id")] public string carModelId { get; set; } [DataMember(Name = "name")] public string carModelName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APICarType { [DataMember(Name = "id")] public int CarTypeID { get; set; } [DataMember(Name = "name")] public string CarTypeName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APIProvince { [DataMember(Name = "id")] public string provinceCode { get; set; } [DataMember(Name = "name")] public string provinceName { get; set; } [DataMember(Name = "geo_id")] public int geoID { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APIAumphur { [DataMember(Name = "aumphur_code")] public string aumphurCode { get; set; } [DataMember(Name = "aumphur_name")] public string aumphurName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APICarColor { [DataMember(Name = "id")] public int? colorID { get; set; } [DataMember(Name = "name")] public string colorName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IWorkFlow.DataBase; namespace IWorkFlow.ORM { // FX_RYLXInfo [Serializable] [DataTableInfo("FX_RYLXInfo", "ryid")] public class FX_RYLXInfo : QueryInfo { [DataField("ryid","FX_RYLXInfo",false)] public int? ryid { get { return _ryid; } set { _ryid = value; } } private int? _ryid; [DataField("UserID", "FX_RYLXInfo")] public string UserID{get;set;} [DataField("UserType", "FX_RYLXInfo")] public int UserType { get; set; } [DataField("UserNumber", "FX_RYLXInfo")] public string UserNumber { get; set; } public string UserName { get; set; } public string DepartmentName { get; set; } public string UserTypeText { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dir { class Program { static void Main(string[] args) { //string s = "i am s dsa fd fewenwqe ds a"; //char[] c = new char[] { }; //c = s.ToCharArray(); //foreach (char i in c) //{ // Console.WriteLine(i); //} string s = "qwertyytrewqqwerty0"; Dictionary<char, int> d = new Dictionary<char, int>(); d.Add(Convert.ToChar(Convert.ToString(s[0]).ToUpper()), 1); for (int i = 1; i < s.Length; i++) { char new_char = Convert.ToChar(Convert.ToString(s[i]).ToUpper()); if (d.ContainsKey(new_char)) { d[new_char] += 1; } else { d.Add(new_char, 1); } } foreach (KeyValuePair<char, int> kv in d) { Console.WriteLine("{0}___{1}", kv.Key, kv.Value); } Console.WriteLine(); //int [] n = new int[] { }; //List<int> all = new List<int>(); //List<int> ji = new List<int>(); //List<int> ou = new List<int>(); //Dictionary<int, int> d = new Dictionary<int, int>(); //for (int i = 0; i < 100; i++) //{ // all.Add(i); //} //n = all.ToArray(); //foreach (int i in n) //{ // if (i % 2 == 0) // { // ou.Add(i); // } // else // ji.Add(i); //} //Console.WriteLine("jishu:"); //foreach (int item in ji) //{ // Console.Write(item); //} //Console.WriteLine("ou shu :"); //foreach (int item in ou) //{ // Console.Write(item); //} //int x = 0; //foreach (int i in ji) //{ // d.Add(i,ou[x]); // x++; //} //Console.WriteLine(); //foreach (KeyValuePair<int,int> kv in d) //{ // Console.WriteLine("{0}___{1}",kv.Key,kv.Value); //} //Dictionary<string, string> d = new Dictionary<string, string>(); //d.Add("1","3"); //d.Add("s","f"); //d. //foreach (KeyValuePair<string,string> kv in d) //{ // Console.WriteLine("{0}---{1}",kv.Key,kv.Value); //} Console.ReadKey(); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; namespace WerkWerk { using Data; public static class ServiceCollectionExtensions { public static IServiceCollection AddWerk<TContext>(this IServiceCollection services) where TContext : DbContext { services.AddScoped<IWorkRepository, WorkRepository<TContext>>(); services.AddLogging(); return services; } public static IServiceCollection AddWerk<TContext, TRepository>(this IServiceCollection services) where TContext : DbContext where TRepository : class, IWorkRepository { services.AddScoped<IWorkRepository, TRepository>(); services.AddLogging(); return services; } } }
using SMG.Common.Conditions; using SMG.Common.Exceptions; using SMG.Common.Gates; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SMG.Common.Transitions { /// <summary> /// Collects a set of transitions. /// </summary> public class TransitionSet : IEnumerable<Transition> { #region Private private SortedList<int, VariableTransitions> _variables = new SortedList<int, VariableTransitions>(); private HashSet<Transition> _all = new HashSet<Transition>(); #endregion #region Properties /// <summary> /// The variables affected by the transitions in this set. /// </summary> public IEnumerable<Variable> Variables { get { return _variables.Values.Select(e => e.Variable); } } public bool IsEmpty { get { return !_variables.Any(); } } #endregion #region Construction /// <summary> /// Constructs a new, empty transition set. /// </summary> public TransitionSet() { } /// <summary> /// Constructs a transition set from the variable conditions in a gate. /// </summary> /// <param name="g"></param> public TransitionSet(TransitionSet parent, IGate g) { AddRange(parent.GetTransitions(g)); } public TransitionSet(ICondition c) { AddRange(c.GetTransitions()); } #endregion #region Diagnostics public override string ToString() { return ToDebugString(); } public string ToDebugString() { var sb = new StringBuilder(); var pfirst = true; foreach (var vt in _variables.Values) { if (pfirst) pfirst = false; else sb.Append(" * "); var decl = vt.Variable.Type; sb.Append(vt.Variable.Name); sb.Append("["); var first = true; foreach (var t in vt) { if (first) first = false; else sb.Append(" + "); sb.AppendFormat("({0} => {1})", decl.GetStateNames(t.PreStateIndexes).ToSeparatorList(), decl.GetStateNames(t.NewStateIndexes).ToSeparatorList()); } sb.Append("]"); } return sb.ToString(); } #endregion #region Public Methods public bool Contains(Variable v) { return _variables.ContainsKey(v.Index); } public IEnumerable<Transition> GetTransitions(Variable v) { VariableTransitions vt; if(_variables.TryGetValue(v.Index, out vt)) { return vt; } else { return new Transition[0]; } } public TransitionSet GetTransitions(IGate c, bool post = false) { var tset = new TransitionSet(); var vclist = c.SelectAll(g => g is IVariableCondition).OfType<IVariableCondition>(); foreach (var vc in vclist) { foreach (var x in GetTransitions(vc.Variable)) { if (!post) { // work on preconditions if (x.PreStateIndexes.Contains(vc.StateIndex)) { // transition matches variable condition if (x.PreStateIndexes.Length > 1) { // reduce to simple transition var y = new Transition(x.Parent); y.PreStateIndexes = new int[] { vc.StateIndex }; y.NewStateIndexes = x.NewStateIndexes; tset.Add(y); } else { tset.Add(x); } } } else { throw new NotImplementedException(); } } } return tset; } /// <summary> /// Adds a transition to this transition set. /// </summary> /// <param name="t">The transition to add.</param> public void Add(Transition t) { if (!_all.Contains(t)) { // account only once _all.Add(t); var v = t.Variable; VariableTransitions vt; if (!_variables.TryGetValue(v.Index, out vt)) { _variables[v.Index] = vt = new VariableTransitions(v); } vt.Add(t); } } public void AddRange(IEnumerable<Transition> tlist) { foreach (var t in tlist) Add(t); } public void QualifyForTrigger() { foreach(var vt in _variables.Values) { if(vt.Count > 1) { // multiple transitions for the same variable not allowed. throw new CompilerException(ErrorCode.AmbigousPostCondition, "ambigous post conditions in state transition [" + vt.ToSeparatorList() + "]."); } foreach(var t in vt) { if(t.NewStateIndexes.Length != 1) { // multistate post throw new CompilerException(ErrorCode.AmbigousPostCondition, "ambigous post conditions in state transition [" + t.Parent + "]."); } } } } public IEnumerable<Transition> Match(IGate genter, IGate gleave) { var f1 = genter.GetProduct(); var f2 = gleave.GetProduct(); foreach(var f in f1.Factors) { // must exist ... var t = GetTransitions(f.Variable).First(); int[] indexes; if (f.Variable.Type.IsBoolean) { indexes = new int[] { f.Inputs.First().IsInverted ? 0 : 1 }; } else { indexes = f.Inputs.Select(i => i.Address - i.Group).ToArray(); } var q = t.PreStateIndexes.Intersect(indexes); if(!q.Any()) { // transition is not contained yield break; } yield return t; } } /// <summary> /// Expresses a post state of a variable as an expression of variable preconditions. /// </summary> /// <param name="v">The variables</param> /// <param name="poststateindex">The post state to express.</param> /// <returns>The resulting gate.</returns> public IGate InferPostState(Variable v, int poststateindex) { IGate r = new FalseGate(); VariableTransitions vt; var match = false; if (_variables.TryGetValue(v.Index, out vt)) { foreach (var t in vt.Where(t => t.NewStateIndexes.Contains(poststateindex))) { foreach (var i in t.PreStateIndexes) { var e = t.Parent.CreateElementaryCondition(i); r = Gate.ComposeOR(r, e); match = true; } } if(!match) { var sc = new StateCondition(vt.Variable); sc.SetPreStates(new int[] { poststateindex }); r = sc.CreateElementaryCondition(poststateindex); } } Gate.TraceLabel(new ElementaryCondition(v, poststateindex), r, "infer state"); return r; } #endregion #region IEnumerable public IEnumerator<Transition> GetEnumerator() { return _variables.SelectMany(e => e.Value).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _variables.SelectMany(e => e.Value).GetEnumerator(); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CercaRotate : MonoBehaviour { void Update() { if(Input.GetKeyDown(KeyCode.Alpha1)) { transform.Rotate(0f, 0f, -90f); } } }
using System; using System.Threading.Tasks; using AutoMapper; using DataAccess.Roles; using Entities; using Microsoft.AspNetCore.Identity; namespace DataAccess.DbImplementation.Roles { public class RemoveRoleFromUserCommand : IRemoveRoleFromUserCommand { private readonly IMapper _mapper; private readonly UserManager<User> _userManager; private readonly RoleManager<Role> _roleManager; public RemoveRoleFromUserCommand(IMapper mapper, UserManager<User> userManager, RoleManager<Role> roleManager) { _mapper = mapper; _userManager = userManager; _roleManager = roleManager; } public async Task ExecuteAsync(Guid roleId, Guid userId) { var user = await _userManager.FindByIdAsync(userId.ToString()); if (user != null) { var role = await _roleManager.FindByIdAsync(roleId.ToString()); if (role != null) await _userManager.RemoveFromRoleAsync(user, role.Name); } } } }
using UnityEngine; using System.Collections; public class InputEventCtrl : MonoBehaviour { public static float VerticalVal; float HorizontalVal; public static bool IsClickFireBtDown; public static uint SteerValCur; public static uint TaBanValCur; static private InputEventCtrl Instance = null; //static GameObject InputEventCtrlObj = null; static public InputEventCtrl GetInstance() { if(Instance == null) { GameObject obj = new GameObject("_InputEventCtrl"); //DontDestroyOnLoad(obj); Instance = obj.AddComponent<InputEventCtrl>(); //InputEventCtrlObj = obj; pcvr.GetInstance(); } return Instance; } #region Click Button Envent public delegate void EventHandel(ButtonState val); public event EventHandel ClickStartBtOneEvent; public void ClickStartBtOne(ButtonState val) { if(ClickStartBtOneEvent != null) { ClickStartBtOneEvent( val ); pcvr.StartLightStateP1 = LedState.Mie; } } public event EventHandel ClickStartBtTwoEvent; public void ClickStartBtTwo(ButtonState val) { if(ClickStartBtTwoEvent != null) { ClickStartBtTwoEvent( val ); pcvr.StartLightStateP2 = LedState.Mie; } } public event EventHandel ClickSetEnterBtEvent; public void ClickSetEnterBt(ButtonState val) { SetEnterBtSt = val; if(ClickSetEnterBtEvent != null) { ClickSetEnterBtEvent( val ); } if (val == ButtonState.DOWN) { TimeSetEnterMoveBt = Time.time; } } public event EventHandel ClickSetMoveBtEvent; public void ClickSetMoveBt(ButtonState val) { if(ClickSetMoveBtEvent != null) { ClickSetMoveBtEvent( val ); } } public event EventHandel ClickFireBtEvent; public void ClickFireBt(ButtonState val) { if(ClickFireBtEvent != null) { ClickFireBtEvent( val ); } } public event EventHandel ClickStopDongGanBtEvent; public void ClickStopDongGanBt(ButtonState val) { if(ClickStopDongGanBtEvent != null) { ClickStopDongGanBtEvent( val ); } if (val == ButtonState.DOWN) { if (DongGanUICtrl.Instance != null) { pcvr.DongGanState = (byte)(pcvr.DongGanState == 1 ? 0 : 1); DongGanUICtrl.Instance.ShowDongGanUI(pcvr.DongGanState); } } } #endregion public float GetHorVal() { return HorizontalVal; } float TimeSetEnterMoveBt; ButtonState SetEnterBtSt = ButtonState.UP; void Update() { if (SetEnterBtSt == ButtonState.DOWN && Time.time - TimeSetEnterMoveBt > 2f) { HardwareBtCtrl.OnRestartGame(); } HorizontalVal = pcvr.mGetSteer; VerticalVal = pcvr.TanBanDownCount_P1; if (pcvr.bIsHardWare && !pcvr.IsGetValByKey) { return; } if (Mathf.Abs(Input.GetAxis("Horizontal")) > 0.001f) { SteerValCur = (uint)(Input.GetAxis("Horizontal") > 0f ? 2 : 0); } else { SteerValCur = 1; } TaBanValCur = (uint)(Input.GetAxis("Vertical") + 1f); //StartBt PlayerOne if(Input.GetKeyUp(KeyCode.G)) { ClickStartBtOne( ButtonState.UP ); } if(Input.GetKeyDown(KeyCode.G)) { ClickStartBtOne( ButtonState.DOWN ); } //StartBt PlayerTwo if(Input.GetKeyUp(KeyCode.K)) { ClickStartBtTwo( ButtonState.UP ); } if(Input.GetKeyDown(KeyCode.K)) { ClickStartBtTwo( ButtonState.DOWN ); } //setPanel enter button if(Input.GetKeyUp(KeyCode.F4)) { ClickSetEnterBt( ButtonState.UP ); } if(Input.GetKeyDown(KeyCode.F4)) { ClickSetEnterBt( ButtonState.DOWN ); } //setPanel move button if(Input.GetKeyUp(KeyCode.F5)) { ClickSetMoveBt( ButtonState.UP ); //FramesPerSecond.GetInstance().ClickSetMoveBtEvent( ButtonState.UP ); } if(Input.GetKeyDown(KeyCode.F5)) { ClickSetMoveBt( ButtonState.DOWN ); //FramesPerSecond.GetInstance().ClickSetMoveBtEvent( ButtonState.DOWN ); } //Fire button if(Input.GetKeyUp(KeyCode.Mouse0)) { IsClickFireBtDown = false; ClickFireBt( ButtonState.UP ); } if(Input.GetKeyDown(KeyCode.Mouse0)) { IsClickFireBtDown = true; ClickFireBt( ButtonState.DOWN ); } //DongGan button if(Input.GetKeyUp(KeyCode.P)) { ClickStopDongGanBt( ButtonState.UP ); } if(Input.GetKeyDown(KeyCode.P)) { ClickStopDongGanBt( ButtonState.DOWN ); } } } public enum ButtonState : int { UP = 1, DOWN = -1 }
using System; namespace EngageNet.Exceptions { [Serializable] public class AccountUpgradeNeededException : ResponseException { public AccountUpgradeNeededException(int errorCode, string message, Exception inner) : base(errorCode, message, inner) { } public AccountUpgradeNeededException(int errorCode, string message) : base(errorCode, message, null) { } public AccountUpgradeNeededException() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SimuladorApp { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DistanciaPage : ContentPage { public DistanciaPage() { InitializeComponent(); btnCalcular.Clicked += BtnCalcular_Clicked; } private async void BtnCalcular_Clicked(object sender, EventArgs e) { this.lblResultado.Text = ""; this.lblResultado1.Text = ""; this.lblResultado2.Text = ""; this.lblResultado3.Text = ""; this.lblResultado4.Text = ""; this.lblResultado5.Text = ""; this.lblResultado6.Text = ""; this.lblResultado7.Text = ""; double d = 0; double d1 = 0; double d2 = 0; double d3 = 0; var cad = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad1 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad2 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad3 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad4 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad5 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad6 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); var cad7 = await Funciones.DistanciaCarreteraNEW(txtOrigen.Text, txtDestino.Text); double.TryParse(cad, out d); double.TryParse(cad1, out d1); double.TryParse(cad2, out d2); double.TryParse(cad3, out d3); this.lblResultado.Text = d.ToString(); this.lblResultado1.Text = (d + 1).ToString(); this.lblResultado2.Text = (d + 2).ToString(); this.lblResultado3.Text = (d + 3).ToString(); this.lblResultado4.Text = cad4; this.lblResultado5.Text = cad5; this.lblResultado6.Text = cad6; this.lblResultado7.Text = cad7; } } }
using System; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.WMS { [Serializable] public partial class PickUser : EntityBase, IAuditable { #region O/R Mapping Properties public Int32 Id { get; set; } [Display(Name = "PickUser_PickGroupCode", ResourceType = typeof(Resources.WMS.PickUser))] public string PickGroupCode { get; set; } public Int32? PickUserId { get; set; } [Display(Name = "PickUser_PickUserName", ResourceType = typeof(Resources.WMS.PickUser))] public string PickUserName { get; set; } [Display(Name = "PickUser_IsActive", ResourceType = typeof(Resources.WMS.PickUser))] public Boolean IsActive { get; set; } public Int32 CreateUserId { get; set; } [Display(Name = "PickUser_CreateUserName", ResourceType = typeof(Resources.WMS.PickUser))] public string CreateUserName { get; set; } [Display(Name = "PickUser_CreateDate", ResourceType = typeof(Resources.WMS.PickUser))] public DateTime CreateDate { get; set; } public Int32 LastModifyUserId { get; set; } [Display(Name = "PickUser_LastModifyUserName", ResourceType = typeof(Resources.WMS.PickUser))] public string LastModifyUserName { get; set; } [Display(Name = "PickUser_LastModifyDate", ResourceType = typeof(Resources.WMS.PickUser))] public DateTime LastModifyDate { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { PickUser another = obj as PickUser; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using Microsoft.Extensions.Caching.Memory; using System.Dynamic; namespace Shared.CachingProvider { public interface ICachingProviderService { object GetItem(string key); object GetItem<T>(string key); void SetItem(string key, string value); void DeleteItem(string key); } public class MemoryCacheProvider : ICachingProviderService { private readonly IMemoryCache _memoryCache; public MemoryCacheProvider(IMemoryCache memoryCache) { _memoryCache = memoryCache; } public object GetItem(string key) { _memoryCache.TryGetValue(key, out object value); return value; } public object GetItem<T>(string key) { _memoryCache.TryGetValue<T>(key, out T value); return value; } //TODO: Settings from appSettings public void SetItem(string key, string value) { _memoryCache.Set(key, value); } public void DeleteItem(string key) { _memoryCache.Remove(key); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Management.Automation; using System.Net; using AutoMapper; using Helpers; using Management.Compute.Models; using Model; using Properties; using DataVirtualHardDisk = Model.PersistentVMModel.DataVirtualHardDisk; using OSVirtualHardDisk = Model.PersistentVMModel.OSVirtualHardDisk; using PVM = Model.PersistentVMModel; using RoleInstance = Management.Compute.Models.RoleInstance; [Cmdlet(VerbsCommon.Get, "AzureVM"), OutputType(typeof(PersistentVMRoleContext))] public class GetAzureVMCommand : IaaSDeploymentManagementCmdletBase { protected const string PersistentVMRoleStr = "PersistentVMRole"; [Parameter( Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Service name.")] [ValidateNotNullOrEmpty] public override string ServiceName { get; set; } [Parameter( Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the virtual machine to get.")] public virtual string Name { get; set; } protected override void ExecuteCommand() { ServiceManagementProfile.Initialize(this); base.ExecuteCommand(); if (!string.IsNullOrEmpty(ServiceName) && CurrentDeploymentNewSM == null) { WriteWarning(string.Format(Resources.NoDeploymentFoundInService, ServiceName)); return; } if (string.IsNullOrEmpty(ServiceName)) { var roleContexts = new List<PersistentVMRoleListContext>(); var servicesList = this.ComputeClient.HostedServices.List(); foreach (var service in servicesList.HostedServices) { try { var deployment = this.ComputeClient.Deployments.GetBySlot( service.ServiceName, DeploymentSlot.Production); foreach (var vm in deployment.Roles) { if (string.Equals(vm.RoleType, PersistentVMRoleStr, StringComparison.OrdinalIgnoreCase)) { var roleInstance = deployment.RoleInstances.FirstOrDefault( r => r.RoleName == vm.RoleName); if (roleInstance == null) { WriteWarning(string.Format(Resources.RoleInstanceCanNotBeFoundWithName, vm.RoleName)); roleInstance = new RoleInstance(); } var vmContext = GetContext<PersistentVMRoleListContext>( service.ServiceName, vm, roleInstance, deployment); roleContexts.Add(vmContext); } } } catch (CloudException e) { if (e.Response.StatusCode != HttpStatusCode.NotFound) { throw; } } } WriteObject(roleContexts, true); } else { var roleContexts = new List<PersistentVMRoleContext>(); var vmRoles = new List<Role>(CurrentDeploymentNewSM.Roles.Where( r => string.IsNullOrEmpty(Name) || r.RoleName.Equals(Name, StringComparison.InvariantCultureIgnoreCase))); foreach (var vm in vmRoles) { string lastVM = string.Empty; try { lastVM = vm.RoleName; var roleInstance = CurrentDeploymentNewSM.RoleInstances.FirstOrDefault( r => r.RoleName == vm.RoleName); if (roleInstance == null) { WriteWarning(string.Format(Resources.RoleInstanceCanNotBeFoundWithName, vm.RoleName)); roleInstance = new RoleInstance(); } var vmContext = GetContext<PersistentVMRoleContext>(ServiceName, vm, roleInstance, CurrentDeploymentNewSM); roleContexts.Add(vmContext); } catch (Exception e) { throw new ApplicationException(string.Format(Resources.VMPropertiesCanNotBeRead, lastVM), e); } } WriteObject(roleContexts, true); } } private T GetContext<T>( string serviceName, Role vmRole, RoleInstance roleInstance, DeploymentGetResponse deployment) where T : PersistentVMRoleContext, new() { var vmContext = new T { ServiceName = serviceName, Name = vmRole.RoleName, DeploymentName = deployment.Name, AvailabilitySetName = vmRole.AvailabilitySetName, Label = vmRole.Label, InstanceSize = vmRole.RoleSize.ToString(), InstanceStatus = roleInstance.InstanceStatus, IpAddress = roleInstance.IPAddress, InstanceStateDetails = roleInstance.InstanceStateDetails, PowerState = roleInstance.PowerState.ToString(), InstanceErrorCode = roleInstance.InstanceErrorCode, InstanceName = roleInstance.InstanceName, InstanceFaultDomain = roleInstance.InstanceFaultDomain.HasValue ? roleInstance.InstanceFaultDomain.Value.ToString(CultureInfo.InvariantCulture) : null, InstanceUpgradeDomain = roleInstance.InstanceUpgradeDomain.HasValue ? roleInstance.InstanceUpgradeDomain.Value.ToString(CultureInfo.InvariantCulture) : null, Status = roleInstance.InstanceStatus, OperationDescription = CommandRuntime.ToString(), OperationId = deployment.RequestId, OperationStatus = deployment.StatusCode.ToString(), GuestAgentStatus = Mapper.Map<PVM.GuestAgentStatus>(roleInstance.GuestAgentStatus), ResourceExtensionStatusList = Mapper.Map<List<PVM.ResourceExtensionStatus>>(roleInstance.ResourceExtensionStatusList), VM = new PersistentVM { AvailabilitySetName = vmRole.AvailabilitySetName, ConfigurationSets = PersistentVMHelper.MapConfigurationSets(vmRole.ConfigurationSets), DataVirtualHardDisks = Mapper.Map(vmRole.DataVirtualHardDisks, new Collection<DataVirtualHardDisk>()), Label = vmRole.Label, OSVirtualHardDisk = Mapper.Map(vmRole.OSVirtualHardDisk, new OSVirtualHardDisk()), RoleName = vmRole.RoleName, RoleSize = vmRole.RoleSize.ToString(), RoleType = vmRole.RoleType, DefaultWinRmCertificateThumbprint = vmRole.DefaultWinRmCertificateThumbprint, ProvisionGuestAgent = vmRole.ProvisionGuestAgent, ResourceExtensionReferences = Mapper.Map<PVM.ResourceExtensionReferenceList>(vmRole.ResourceExtensionReferences) } }; if (deployment != null) { vmContext.DNSName = deployment.Uri.AbsoluteUri; } return vmContext; } } }
using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LibModels.common; namespace LibModels { public class BaiViet { private int _ID; private string _TieuDe; private string _SoLuoc; private string _NoiDung; private string _NgayDang; private string _IP; private int _LuotXem; private byte _ChuDeID; private string _TenChuDe; private int _AnhID; private string _URL; private int _LopHocID; private DBAccess db; public BaiViet() { db = new DBAccess(); } public int ID { get { return _ID; } set { _ID = value; } } public string TieuDe { get { return _TieuDe; } set { _TieuDe = value; } } public string SoLuoc { get { return _SoLuoc; } set { _SoLuoc = value; } } public string NoiDung { get { return _NoiDung; } set { _NoiDung = value; } } public string NgayDang { get { return _NgayDang; } set { _NgayDang = value; } } public string IP { get { return _IP; } set { _IP = value; } } public byte ChuDeID { get { return _ChuDeID; } set { _ChuDeID = value; } } public string TenChuDe { get { return _TenChuDe; } set { _TenChuDe = value; } } public int LuotXem { get { return _LuotXem; } set { _LuotXem = value; } } public string URL { get { return _URL; } set { _URL = value; } } public int AnhID { get { return _AnhID; } set { _AnhID = value; } } public int LopHocID { get { return _LopHocID; } set { _LopHocID = value; } } //=============================================================================== public int Add() { int out0 = 0; try { SqlCommand cmd = new SqlCommand("BaiViet_tao"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@TieuDe", this.TieuDe)); cmd.Parameters.Add(new SqlParameter("@SoLuoc", this.SoLuoc)); cmd.Parameters.Add(new SqlParameter("@NoiDung", this.NoiDung)); cmd.Parameters.Add(new SqlParameter("@IP", this.IP)); cmd.Parameters.Add(new SqlParameter("@ChuDeID", this.ChuDeID)); cmd.Parameters.Add(new SqlParameter("@URL", this.URL)); // cmd.Parameters.Add(new SqlParameter("@lophocid", this.LopHocID)); cmd.Parameters.Add("@out", SqlDbType.Int).Direction = ParameterDirection.Output; db.ExecuteSQL(cmd); out0 = Convert.ToInt32(cmd.Parameters["@out"].Value); } catch (Exception ex) { throw ex; } return out0; } public int Update() { int out0 = 0; try { SqlCommand cmd = new SqlCommand("BaiViet_sua"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID", this.ID)); cmd.Parameters.Add(new SqlParameter("@TieuDe", this.TieuDe)); cmd.Parameters.Add(new SqlParameter("@SoLuoc", this.SoLuoc)); cmd.Parameters.Add(new SqlParameter("@NoiDung", this.NoiDung)); cmd.Parameters.Add(new SqlParameter("@LuotXem", this.LuotXem)); cmd.Parameters.Add(new SqlParameter("@ChuDeID", this.ChuDeID)); cmd.Parameters.Add(new SqlParameter("@AnhID", this.AnhID)); cmd.Parameters.Add(new SqlParameter("@URL", this.URL)); cmd.Parameters.Add(new SqlParameter("@lophocid", this.LopHocID)); cmd.Parameters.Add("@out", SqlDbType.Int).Direction = ParameterDirection.Output; db.ExecuteSQL(cmd); out0 = Convert.ToInt32(cmd.Parameters["@out"].Value); } catch (Exception ex) { throw ex; } return out0; } public int Delete(string list) { int out0 = 0; try { SqlCommand cmd = new SqlCommand("BaiViet_xoa"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@list", list)); cmd.Parameters.Add("@out", SqlDbType.Int).Direction = ParameterDirection.Output; db.ExecuteSQL(cmd); out0 = Convert.ToInt32(cmd.Parameters["@out"].Value); } catch (Exception ex) { throw ex; } return out0; } public BaiViet FindByID(int ID) { BaiViet bv = new BaiViet(); SqlConnection con = db.getConnection(); try { SqlCommand cmd = new SqlCommand("BaiViet_chitiet"); cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@ID", ID)); SqlDataReader reader = cmd.ExecuteReader(); SmartDataReader smartReader = new SmartDataReader(reader); while (smartReader.Read()) { bv.ID = smartReader.GetInt32("ID"); bv.TieuDe = smartReader.GetString("TieuDe"); bv.SoLuoc = smartReader.GetString("SoLuoc"); bv.NoiDung = smartReader.GetString("NoiDung"); bv.NgayDang = smartReader.GetString("NgayDang"); bv.IP = smartReader.GetString("IP"); bv.LuotXem = smartReader.GetInt32("LuotXem"); bv.TenChuDe = smartReader.GetString("TenChuDe"); bv.URL = smartReader.GetString("URL"); bv.ChuDeID = smartReader.GetByte("ChuDeID"); bv.AnhID = smartReader.GetInt32("AnhID"); bv.LopHocID = smartReader.GetInt32("lophocid"); } smartReader.disposeReader(reader); } catch (Exception ex) { throw ex; } finally { db.closeConnection(con); } return bv; } public List<BaiViet> GetList(string TieuDe, string NgayDangMin, string NgayDangMax, byte ChuDeID) { SqlConnection con = db.getConnection(); List<BaiViet> l_BaiViet = new List<BaiViet>(); try { SqlCommand cmd = new SqlCommand("BaiViet_timkiem"); cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@TieuDe", TieuDe)); cmd.Parameters.Add(new SqlParameter("@NgayDangMin", NgayDangMin)); cmd.Parameters.Add(new SqlParameter("@NgayDangMax", NgayDangMax)); cmd.Parameters.Add(new SqlParameter("@ChuDeID", ChuDeID)); SqlDataReader reader = cmd.ExecuteReader(); SmartDataReader smartReader = new SmartDataReader(reader); while (smartReader.Read()) { BaiViet bv = new BaiViet(); bv.ID = smartReader.GetInt32("ID"); bv.TieuDe = smartReader.GetString("TieuDe"); bv.NgayDang = smartReader.GetString("NgayDang"); bv.LuotXem = smartReader.GetInt32("LuotXem"); bv.TenChuDe = smartReader.GetString("TenChuDe"); bv.URL = smartReader.GetString("URL"); bv.IP = smartReader.GetString("IP"); bv.LopHocID = smartReader.GetInt32("lophocid"); l_BaiViet.Add(bv); } smartReader.disposeReader(reader); } catch (Exception ex) { throw ex; } finally { db.closeConnection(con); } return l_BaiViet; } public List<BaiViet> GetList(string TieuDe, string NgayDangMin, string NgayDangMax, byte ChuDeID, int LopHocID) { SqlConnection con = db.getConnection(); List<BaiViet> l_BaiViet = new List<BaiViet>(); try { SqlCommand cmd = new SqlCommand("BaiViet_timkiem"); cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@TieuDe", TieuDe)); cmd.Parameters.Add(new SqlParameter("@NgayDangMin", NgayDangMin)); cmd.Parameters.Add(new SqlParameter("@NgayDangMax", NgayDangMax)); cmd.Parameters.Add(new SqlParameter("@ChuDeID", ChuDeID)); cmd.Parameters.Add(new SqlParameter("@lophocid", LopHocID)); SqlDataReader reader = cmd.ExecuteReader(); SmartDataReader smartReader = new SmartDataReader(reader); while (smartReader.Read()) { BaiViet bv = new BaiViet(); bv.ID = smartReader.GetInt32("ID"); bv.TieuDe = smartReader.GetString("TieuDe"); bv.NgayDang = smartReader.GetString("NgayDang"); bv.LuotXem = smartReader.GetInt32("LuotXem"); bv.TenChuDe = smartReader.GetString("TenChuDe"); bv.URL = smartReader.GetString("URL"); bv.IP = smartReader.GetString("IP"); bv.LopHocID = smartReader.GetInt32("lophocid"); l_BaiViet.Add(bv); } smartReader.disposeReader(reader); } catch (Exception ex) { throw ex; } finally { db.closeConnection(con); } return l_BaiViet; } public List<BaiViet> GetRecentList() { SqlConnection con = db.getConnection(); List<BaiViet> l_BaiViet = new List<BaiViet>(); try { SqlCommand cmd = new SqlCommand("BaiViet_timKiemGanNhat"); cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader reader = cmd.ExecuteReader(); SmartDataReader smartReader = new SmartDataReader(reader); while (smartReader.Read()) { BaiViet bv = new BaiViet(); bv.ID = smartReader.GetInt32("ID"); bv.TieuDe = smartReader.GetString("TieuDe"); bv.NgayDang = smartReader.GetString("NgayDang"); bv.SoLuoc = smartReader.GetString("SoLuoc"); bv.URL = smartReader.GetString("URL"); bv.LopHocID = smartReader.GetInt32("lophocid"); l_BaiViet.Add(bv); } smartReader.disposeReader(reader); } catch (Exception ex) { throw ex; } finally { db.closeConnection(con); } return l_BaiViet; } public List<BaiViet> GetPaginationList(short pageNum, short limitPerPage, byte ChuDeID, int LopHocID) { SqlConnection con = db.getConnection(); List<BaiViet> l_BaiViet = new List<BaiViet>(); try { SqlCommand cmd = new SqlCommand("BaiViet_timKiemPhanTrang"); cmd.Connection = con; con.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@Page", pageNum)); cmd.Parameters.Add(new SqlParameter("@Limit", limitPerPage)); cmd.Parameters.Add(new SqlParameter("@ChuDeID", ChuDeID)); cmd.Parameters.Add(new SqlParameter("@lophocid", LopHocID)); SqlDataReader reader = cmd.ExecuteReader(); SmartDataReader smartReader = new SmartDataReader(reader); while (smartReader.Read()) { BaiViet bv = new BaiViet(); bv.ID = smartReader.GetInt32("ID"); bv.TieuDe = smartReader.GetString("TieuDe"); bv.SoLuoc = smartReader.GetString("SoLuoc"); bv.URL = smartReader.GetString("URL"); bv.LopHocID = smartReader.GetInt32("lophocid"); l_BaiViet.Add(bv); } smartReader.disposeReader(reader); } catch (Exception ex) { throw ex; } finally { db.closeConnection(con); } return l_BaiViet; } public int GetTotalPage(short limitPerPage, byte ChuDeID, int lophocid) { int out0 = 0; try { SqlCommand cmd = new SqlCommand("BaiViet_totalPage"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@Limit", limitPerPage)); cmd.Parameters.Add(new SqlParameter("@ChuDeID", ChuDeID)); cmd.Parameters.Add(new SqlParameter("@lophocid", lophocid)); cmd.Parameters.Add("@out", SqlDbType.Int).Direction = ParameterDirection.Output; db.ExecuteSQL(cmd); out0 = Convert.ToInt32(cmd.Parameters["@out"].Value); } catch (Exception ex) { throw ex; } return out0; } } }
// Copyright (c) Christopher Clayton. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace praxicloud.core.metrics.simpleprovider { #region Using Clauses using System.Threading; using System.Threading.Tasks; #endregion /// <summary> /// A metric that can be notified to invoke a callback /// </summary> public interface ISimpleMetric { /// <summary> /// Write the information to the metric sink /// </summary> /// <param name="cancellationToken">A token to monitor for abort requests</param> Task WriteAsync(CancellationToken cancellationToken); } }
using System; using Xamarin.Forms; using UserLogin; using Views; namespace SMSAuthentication { public class SMSAuthentication : Application { public SMSAuthentication () { MainPage = new NavigationPage (new ContactsListView()); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class DocumentDataStatus { public bool BookingConfirmationFromProvider { get; set; } public bool BookingConfirmationToCustomer { get; set; } public bool BookingPartialPayment { get; set; } public bool BookingCompletePayment { get; set; } public bool VoucherSent { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Uintra.Features.Likes.Models { public class LikesViewModel { public Guid MemberId { get; set; } public Guid EntityId { get; set; } public int Count { get; set; } public bool LikedByCurrentUser { get; set; } public IEnumerable<string> Users { get; set; } = Enumerable.Empty<string>(); public bool IsReadOnly { get; set; } public bool ShowTitle { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data.MySqlClient; using AccountOBJ; namespace MDMUtils { class DBUtils { private string DBNAME = "mdmdb"; private string DBSERVER = "localhost"; private string USERID = "root"; private string PASSWORD = "wesley"; private uint PORT = 3306; private MySqlConnection dbConnection; public DBUtils() { MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.Server = this.DBSERVER; builder.Port = this.PORT; builder.UserID = this.USERID; builder.Password = this.PASSWORD; builder.Database = this.DBNAME; dbConnection = new MySqlConnection(builder.ToString()); } public void closeConnection() { this.dbConnection.Close(); } public List<Account> searchAccount(string JDA) { string query = "select clienti.nome AS Cliente , tipologia.tipoaccount AS Tipologia , account.accountAD AS AccountAD from tipologia, account, clienti where clienti.idcliente = account.idcliente AND tipologia.idtype = account.idtipologia AND account.JDA = '60120'"; dbConnection.Open(); MySqlCommand cmdGetUser = new MySqlCommand(query, dbConnection); MySqlDataReader getUserReader = cmdGetUser.ExecuteReader(); while (getUserReader.Read()) { Console.WriteLine(getUserReader[0] + " " + getUserReader[1] + " " + getUserReader [2]); } getUserReader.Close(); return null; } } }
using System; using System.Collections.Generic; namespace SpaceHosting.Index.Sparnn.Helpers { internal static class ArrayExtensions { private class PairComparer : IComparer<(int, double)> { public int Compare((int, double) x, (int, double) y) { return x.Item2.CompareTo(y.Item2); } } public static List<(int, double)> TakeKBest(this double[] elements, int k) { var comparer = new PairComparer(); var size = Math.Min(k, elements.Length); var temp = new List<(int, double)>(size + 1); for (var i = 0; i < size; i++) { temp.Add((i, elements[i])); } for (var i = temp.Count; i < elements.Length; i++) { if (!(elements[i] < temp[^1].Item2)) { continue; } var pair = (i, elements[i]); var index = temp.BinarySearch(pair, comparer); if (index < 0) { temp.Insert(~index, pair); } else if (index < size) { temp.Insert(index, pair); } temp.RemoveAt(temp.Count - 1); } return temp; } public static double JaccardBinaryDistance(this int[] v1, int[] v2) { var match = 0; var cardinality = 0; var i = 0; var j = 0; for (; i < v1.Length && j < v2.Length;) { var comp = v1[i].CompareTo(v2[j]); switch (comp) { case 0: match++; i++; j++; break; case -1: i++; break; default: j++; break; } cardinality++; } if (i < v1.Length) cardinality += v1.Length - i; if (j < v2.Length) cardinality += v2.Length - j; var result = 1.0 - (double)match / cardinality; return result; } } }
 using EPI.Arrays; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.Arrays { [TestClass] public class FurthestReachUnitTest { [TestMethod] public void CanReachFurthestArrayItem() { FurthestReach.CanReachEnd(new [] {3, 3, 1, 0, 2, 0, 1}).Should().BeTrue(); FurthestReach.CanReachEnd(new[] { 3,2,0,0,2,0,1}).Should().BeFalse(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Fuzzing.Fuzzers.Impl { public class EnumFuzzer : IFuzzer { private readonly UnsignedIntegerFuzzer _intFuzzer = new UnsignedIntegerFuzzer(); public Type FuzzedType { get { return null; } } public object Fuzz(Type type) { var values = Enum.GetValues(type); var count = values.Length; var i = _intFuzzer.Fuzz() % count; return values.GetValue(i); } public IEnumerable<object> Fuzz(Type type, int count) { return Enumerable.Range(0, count) .Select(x => Fuzz(type)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace LP { [CreateAssetMenu(fileName = "New State", menuName = "LittlePrince/Ability/Movement")] public class Movement : StateData { public float Speed; public float rotSpeed; public override void UpdateAbiltiy(CharacterStateBase characterStateBase, Animator animator, AnimatorStateInfo stateInfo) { Player p = characterStateBase.GetCharacterController(animator); if (!VirtualInputManager.Instance.Right && !VirtualInputManager.Instance.Left && !VirtualInputManager.Instance.Up && !VirtualInputManager.Instance.Down) { animator.SetBool(Transition.Move.ToString(), false); } if (VirtualInputManager.Instance.Right) { p.transform.Translate(Vector3.forward * Speed * Time.deltaTime); p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 90f, 0f), Time.deltaTime * rotSpeed); } if (VirtualInputManager.Instance.Left) { p.transform.Translate(Vector3.forward * Speed * Time.deltaTime); p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 270f, 0f), Time.deltaTime * rotSpeed); } if (VirtualInputManager.Instance.Up) { p.transform.Translate(Vector3.forward * Speed * Time.deltaTime); p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 0f, 0f), Time.deltaTime * rotSpeed); } if (VirtualInputManager.Instance.Down) { p.transform.Translate(Vector3.forward * Speed * Time.deltaTime); p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 180f, 0f), Time.deltaTime * rotSpeed); } if (VirtualInputManager.Instance.Right && VirtualInputManager.Instance.Left) { animator.SetBool(Transition.Move.ToString(), false); return; } if (VirtualInputManager.Instance.Up && VirtualInputManager.Instance.Down) { animator.SetBool(Transition.Move.ToString(), false); return; } if (VirtualInputManager.Instance.Sprint) { animator.SetBool(Transition.Sprint.ToString(), true); Speed = 8f; if (VirtualInputManager.Instance.Sprint && VirtualInputManager.Instance.Right && VirtualInputManager.Instance.Up) { Speed = 4f; } else if (VirtualInputManager.Instance.Right && VirtualInputManager.Instance.Down && VirtualInputManager.Instance.Sprint) { Speed = 4f; } else if (VirtualInputManager.Instance.Left && VirtualInputManager.Instance.Up && VirtualInputManager.Instance.Sprint) { Speed = 4f; } else if (VirtualInputManager.Instance.Left && VirtualInputManager.Instance.Down && VirtualInputManager.Instance.Sprint) { Speed = 4f; } } else { animator.SetBool(Transition.Sprint.ToString(), false); Speed = 3.5f; if (VirtualInputManager.Instance.Right && VirtualInputManager.Instance.Up) { Speed = 1.75f; rotSpeed = 2.5f; p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 45f, 0f), Time.deltaTime * rotSpeed); } else if (VirtualInputManager.Instance.Right && VirtualInputManager.Instance.Down) { Speed = 1.75f; rotSpeed = 2.5f; p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 135f, 0f), Time.deltaTime * rotSpeed); } else if (VirtualInputManager.Instance.Left && VirtualInputManager.Instance.Up) { Speed = 1.75f; rotSpeed = 2.5f; p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 315f, 0f), Time.deltaTime * rotSpeed); } else if (VirtualInputManager.Instance.Left && VirtualInputManager.Instance.Down) { Speed = 1.75f; rotSpeed = 2.5f; p.transform.rotation = Quaternion.Slerp(p.transform.rotation, Quaternion.Euler(0f, 225f, 0f), Time.deltaTime * rotSpeed); } else { Speed = 3.5f; rotSpeed = 5f; } } } } }
using System; using System.Collections.Generic; using System.Text; namespace Kupid { public class Chat { #region Atributi protected List<Korisnik> korisnici; protected List<Poruka> poruke; DateTime pocetakChata, najnovijaPoruka; #endregion #region Properties public List<Korisnik> Korisnici { get => korisnici; } public List<Poruka> Poruke { get => poruke; } public DateTime PocetakChata { get => pocetakChata; set { if (value > DateTime.Now) throw new InvalidOperationException("Datum početka ne može biti u budućnosti!"); pocetakChata = value; } } public DateTime NajnovijaPoruka { get => najnovijaPoruka; set { if (value > DateTime.Now) throw new InvalidOperationException("Datum najnovije poruke ne može biti u budućnosti!"); najnovijaPoruka = value; } } #endregion #region Konstruktor public Chat(Korisnik k1, Korisnik k2) { korisnici = new List<Korisnik>() { k1, k2 }; poruke = new List<Poruka>(); PocetakChata = DateTime.Now; } public Chat() { korisnici = new List<Korisnik>() { }; poruke = new List<Poruka>(); PocetakChata = DateTime.Now; } #endregion #region Metode /// <summary> /// Metoda u kojoj se registruje nova poruka. /// Ukoliko je neki od parametara pogrešan, dolazi do pojave izuzetka prema postojećoj programskoj logici. /// Potrebno je dodati poruku u listu poruka i registrovati trenutak dolaska najnovije poruke. /// </summary> /// <param name="primalac"></param> /// <param name="posiljalac"></param> /// <param name="sadrzaj"></param> public void DodajNovuPoruku(Korisnik primalac, Korisnik posiljalac, string sadrzaj) { if (primalac == null || posiljalac == null || String.IsNullOrWhiteSpace(sadrzaj)) throw new Exception("Neispravni parametri!"); poruke.Add(new Poruka(posiljalac, primalac, sadrzaj)); najnovijaPoruka = DateTime.Now; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SoundManagerVolume : MonoBehaviour { [SerializeField] Slider volumeSlider; public AudioSource touch; void Start() { if (!PlayerPrefs.HasKey("musicVolume")) { PlayerPrefs.SetFloat("musicVolume", 1); Load(); } else { Load(); } } void OnMouseDown() { touch.Play(); } public void ChangeVolume() { AudioListener.volume = volumeSlider.value; Save(); } public void Load() { volumeSlider.value = PlayerPrefs.GetFloat("musicVolume"); } public void Save() { PlayerPrefs.SetFloat("musicVolume", volumeSlider.value); } }
using Microsoft.AspNetCore.Identity; namespace Justa.Job.Backend.Api.Identity.Models { public class ApplicationUser : IdentityUser { } }
using DocumentsApproval.Events; using EventLite; namespace DocumentsApproval.Model { public partial class DocumentAggregate : AggregateBase<Document>, IEventHandler<DocumentCreated>, IEventHandler<DocumentRenamed>, IEventHandler<ArtifactsUpdated>, IEventHandler<DocumentDeleted>, IEventHandler<DocumentApproved>, IEventHandler<DocumentRejected> { protected override int CommitsBeforeSnapshot => 10; public DocumentAggregate() : base() { AggregateDataStructure = null; } public override Document AggregateDataStructure { get; set; } public void Apply(DocumentCreated @event) { AggregateDataStructure = @event.Document; } public void Apply(DocumentRenamed @event) { AggregateDataStructure.Name = @event.Name; } public void Apply(DocumentDeleted @event) { AggregateDataStructure.DateDeleted = @event.Timstamp; } public void Apply(ArtifactsUpdated @event) { foreach (var removedArtifact in @event.ArtifactsRemoved) { AggregateDataStructure.Artifacts.Remove(removedArtifact); } foreach (var addedArtifact in @event.ArtifactsAdded) { AggregateDataStructure.Artifacts.Add(addedArtifact); } } public void Apply(DocumentApproved @event) { AggregateDataStructure.DateRejected = null; AggregateDataStructure.RejectedBy = null; AggregateDataStructure.DateApproved = @event.DateApproved; AggregateDataStructure.ApprovedBy = @event.ApprovedBy; } public void Apply(DocumentRejected @event) { AggregateDataStructure.DateRejected = @event.DateRejected; AggregateDataStructure.RejectedBy = @event.RejectedBy; AggregateDataStructure.DateApproved = null; AggregateDataStructure.ApprovedBy = null; } } }
namespace ChangeList { using System; using System.Linq; public class StartUp { public static void Main() { var numbers = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToList(); var input = Console.ReadLine(); while (input != "Odd" && input != "Even") { var command = input .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToList(); if (command[0] == "Delete") { var number = int.Parse(command[1]); numbers.RemoveAll(x => x == number); } else if (command[0] == "Insert") { var number = int.Parse(command[1]); var index = int.Parse(command[2]); numbers.Insert(index, number); } input = Console.ReadLine(); } if (input == "Even") { numbers = numbers.Where(x => x % 2 == 0).ToList(); } else { numbers = numbers.Where(x => x % 2 == 1).ToList(); } Console.WriteLine(string.Join(" ", numbers)); } } }
using Alabo.Domains.Services; using Alabo.Industry.Shop.Activitys.Domain.Entities; namespace Alabo.Industry.Shop.Activitys.Domain.Services { public interface IActivityRecordService : IService<ActivityRecord, long> { } }
using FrHello.NetLib.Core.Security; namespace ScanRepeatFiles { internal class Program { static async Task Main(string[] args) { var fileNameDic = new Dictionary<string, List<string>>(); var md5Dic = new Dictionary<string, List<string>>(); var dir = @"C:\Users\fengr\OneDrive"; var files = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories); foreach (var file in files) { try { await using var stream = File.OpenRead(file); var md5 = await SecurityHelper.Hash.Md5.ComputeHashFast(stream); var fileName = Path.GetFileName(file); if (md5Dic.ContainsKey(md5)) { md5Dic[md5].Add(fileName); } else { md5Dic.Add(md5, new List<string> { fileName }); } if (fileNameDic.ContainsKey(fileName)) { fileNameDic[fileName].Add(fileName); } else { fileNameDic.Add(fileName, new List<string> { fileName }); } } catch { Console.WriteLine(file + " 读取异常"); } } Console.WriteLine("文件名重复:"); foreach (var item in fileNameDic) { if (item.Value.Count > 1) { Console.WriteLine(string.Join("---", item.Value)); } } Console.WriteLine(); Console.WriteLine("Md5 重复:"); foreach (var item in md5Dic) { if (item.Value.Count > 1) { Console.WriteLine(string.Join("---", item.Value)); } } Console.WriteLine("Hello, World!"); } } }
using System; using System.Collections.Generic; using System.Linq; namespace ChartComposite { public class ChartItem : IChart, IEquatable<ChartItem> { public ChartItem(int code, string name, int point) { Code = code; Name = name; Point = point; } public int Code {get;private set;} public string Name { get; } public int Point { get; } public void Add(IChart chart) { throw new System.InvalidOperationException(); } public object Clone() { return (ChartItem)MemberwiseClone(); } public IEnumerable<IChart> Get() { return new List<IChart> { this }; } public int GetPoint() { return Point; } public void Remove(IChart chart) { // } public bool Equals(ChartItem item) { if (Object.ReferenceEquals(this, item)) return true; if (item == null) return false; if (item.GetType() != this.GetType()) return false; return this.Name == item.Name && this.Code == item.Code && this.Point == item.Point; } public override bool Equals(object obj) { return this.Equals(obj as ChartItem); } public override int GetHashCode() { return Name.GetHashCode() ^ Code.GetHashCode() ^ Point.GetHashCode(); } public void Print() { this.Print(4); } public void Print(int indent) { var space = string.Concat(Enumerable.Repeat(" ", indent)); Console.WriteLine($"{space}{Name}"); } } }
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 lab_019 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Text = "Щелкните по ссылке"; linkLabel1.Text = "google.com"; linkLabel2.Text = @"Папка C:\Windows\"; linkLabel3.Text = "Вырезать \"Блокнот\""; this.Font = new Font("Consolas", 12.0F); linkLabel1.LinkVisited = true; linkLabel2.LinkVisited = true; linkLabel3.LinkVisited = true; linkLabel1.LinkClicked += Link; linkLabel2.LinkClicked += Link; linkLabel3.LinkClicked += Link; } private void Link(object sender, LinkLabelLinkClickedEventArgs e) { LinkLabel linkLabel = (LinkLabel)sender; switch (linkLabel.Name) { case "linkLable1": System.Diagnostics.Process.Start("IExplore.exe", "http://google.com"); break; case "linkLable2": System.Diagnostics.Process.Start("C:\\Windows\\"); break; case "linkLable3": System.Diagnostics.Process.Start("Notepad", "text.txt"); break; } } } }
using System.Collections.Generic; using System.Windows; using CODE.Framework.Wpf.Mvvm; namespace CODE.Framework.Wpf.TestBench { /// <summary> /// Interaction logic for ViewActionMenuTest.xaml /// </summary> public partial class ViewActionMenuTest : Window { public ViewActionMenuTest() { InitializeComponent(); var model = new ViewActionMenuTestViewModel(); menu.Model = model; ribbon.Model = model; button.Actions = model.Actions; } } public class ViewActionMenuTestViewModel : ViewModel { public ViewActionMenuTestViewModel() { Actions.Add(new ViewAction("Open", category: "File", execute: (a, o) => MessageBox.Show("Open!"))); Actions.Add(new ViewAction("File 1", execute: (a, o) => MessageBox.Show("File 1!")) { Categories = new List<ViewActionCategory> { new ViewActionCategory("File"), new ViewActionCategory("Recent Files"), new ViewActionCategory("Very Recent Files") } }); } } }
using UnityEngine; using UnityEngine.Audio; using System.Collections; public class AudioVolume : MonoBehaviour { public AudioClip clipMusic; public AudioMixerSnapshot volumeUp; public AudioMixerSnapshot volumeDown; public AudioSource soundEffect; private AudioSource musicSource; // Use this for initialization void Start () { musicSource = GetComponent<AudioSource>(); } public void PlayMusic() { musicSource.clip = clipMusic; musicSource.Play(); } public void VolumeUp(float Volume) { volumeUp.TransitionTo(Volume); } public void VolumeDown(float Volume) { volumeDown.TransitionTo(Volume); } }
using System; using System.Collections.Generic; using System.Linq; namespace ApartmentApps.Api.Modules { public class DashboardPieViewModel : ComponentViewModel { private Type _dataType; public ChartData[] Data { get; set; } public class ChartData { public string label { get; set; } public int data { get; set; } } public string Subtitle { get; set; } public Type DataType { get { if (_dataType == null) { var firstItem = ListData.FirstOrDefault(); if (firstItem != null) return firstItem.GetType(); } return _dataType; } set { _dataType = value; } } public IEnumerable<object> ListData { get; set; } public DashboardPieViewModel(string title, string subTitle, decimal row, params ChartData[] chartData) { Data = chartData; Stretch = "col-md-12"; Title = title; Subtitle = subTitle; Row = row; } } }
using System; using System.Collections.Generic; namespace EPI.Sorting { /// <summary> /// Design an algorithm that takes as input a set of intervals and outputs their union expressed as a set of disjoint intervals. /// </summary> /// <example> /// {} => open interval, [] => closed interval /// {0,3},[1,1],[3,4},[2,4],[5,7},[7,8},[8,11},{9,11], [12,14],{12,16],{13,15},{16,17} returns /// {0,4],[5,11],[12,17} /// </example> public static class UnionOfIntervals { public struct Entry { public int value; public bool isOpenInterval; } public struct Interval { public Entry left; public Entry right; } private class EntryType : IComparable { public Entry entry; public bool isRightInterval; public int CompareTo(object obj) { EntryType entryType = obj as EntryType; if (entryType != null) { return (entry.value != entryType.entry.value) ? entry.value.CompareTo(entryType.entry.value) : // first sort entry's with lowest value (isRightInterval != entryType.isRightInterval) ? isRightInterval.CompareTo(entryType.isRightInterval) : // then sort by entry type which are left (isRightInterval) ? (!entry.isOpenInterval).CompareTo(!entryType.entry.isOpenInterval) : entry.isOpenInterval.CompareTo(entryType.entry.isOpenInterval); //then sort by closed interval entry } throw new InvalidOperationException(); } } public static List<Interval> FindUnionOfIntervals(List<Interval> intervals) { List<Interval> result = new List<Interval>(); EntryType[] entries = new EntryType[intervals.Count * 2]; for (int i = 0; i < intervals.Count; i++) { entries[2 * i] = new EntryType() { entry = intervals[i].left, isRightInterval = false }; entries[2*i + 1] = new EntryType() { entry = intervals[i].right, isRightInterval = true }; } QuickSort<EntryType>.Sort(entries); Stack<EntryType> stackedEntries = new Stack<EntryType>(); foreach (EntryType entryType in entries) { if (!entryType.isRightInterval) { stackedEntries.Push(entryType); } else { EntryType oldestEntryInSet = stackedEntries.Pop(); if (stackedEntries.Count == 0) // set is complete { result.Add(new Interval() { left = oldestEntryInSet.entry, right = entryType.entry }); } } } return result; } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.App.Share.Rewards.Domain.Enums { /// <summary> /// 分润触发类型 /// </summary> [ClassProperty(Name = "分润触发类型")] public enum TeamlLivenessType { /// <summary> /// 自身 /// </summary> [Display(Name = "总团队")] [LabelCssClass(BadgeColorCalss.Warning)] Self = 0, /// <summary> /// 子团队 /// </summary> [Display(Name = "子团队")] [LabelCssClass(BadgeColorCalss.Primary)] Child } }
using ReactMusicStore.Core.Domain.Entities; using ReactMusicStore.Core.Domain.Interfaces.Service.Common; namespace ReactMusicStore.Core.Domain.Interfaces.Service { public interface IGenreService : IService<Genre> { Genre GetWithAlbums(string genre); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EaseBrush : Brush { public override float[,] CalculateBrushUp(float[,] currentBrushValues) { return CSHandler.CalculateWihtShader(currentBrushValues, Value, EasingFunctions.Cubic); } public override float[,] CalculateBrushDown(float[,] currentBrushValues) { return CSHandler.CalculateWihtShader(currentBrushValues, -Value, EasingFunctions.Cubic); } }
using System; using Phenix.Core.Dictionary; using Phenix.Core.Windows; using Phenix.Security.Business; namespace Phenix.Security.Windows.FormClassManage { public partial class FormClassManageForm : Phenix.Core.Windows.BaseForm { public FormClassManageForm() { InitializeComponent(); } #region 属性 private AssemblyClassCriteria AssemblyClassCriteria { get { return BindingSourceHelper.GetDataSourceCurrent(this.assemblyClassCriteriaBindingSource) as AssemblyClassCriteria; } } private SelectableRoleForAssemblyClassMethodList AssemblyClassMethodSelectableRoles { get { return BindingSourceHelper.GetDataSourceList(this.assemblyClassMethodSelectableRolesBindingSource) as SelectableRoleForAssemblyClassMethodList; } } private SelectableRoleForAssemblyClassList AssemblyClassSelectableRoles { get { return BindingSourceHelper.GetDataSourceList(this.assemblyClassSelectableRolesBindingSource) as SelectableRoleForAssemblyClassList; } } private AssemblyClass WorkingAssemblyClass { get { return BindingSourceHelper.GetDataSourceCurrent(this.assemblyClassListBindingSource) as AssemblyClass; } } #endregion #region 方法 private void Humanistic() { businessGroupControl.Text = String.Format("类信息:{0}", WorkingAssemblyClass != null ? String.Format("{0}.{1}", WorkingAssemblyClass.Name, WorkingAssemblyClass.Caption) : "无"); } #endregion private void assemblyClassMethodSelectAllRolesButton_Click(object sender, System.EventArgs e) { AssemblyClassMethodSelectableRoles.SelectAll(); } private void assemblyClassMethodInverseAllRolesButton_Click(object sender, System.EventArgs e) { AssemblyClassMethodSelectableRoles.InverseAll(); } private void assemblyClassSelectAllRolesButton_Click(object sender, System.EventArgs e) { AssemblyClassSelectableRoles.SelectAll(); } private void assemblyClassInverseAllRolesButton_Click(object sender, System.EventArgs e) { AssemblyClassSelectableRoles.InverseAll(); } private void assemblyClassesBindingSource_PositionChanged(object sender, System.EventArgs e) { Humanistic(); } private void assemblyClassesBindingSource_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) { Humanistic(); } private void barManager_Fetching(object sender, Phenix.Windows.BarItemClickEventArgs e) { AssemblyClassCriteria.AddType(AssemblyClassType.Form); } private void barManager_Saved(object sender, Phenix.Windows.BarItemSaveEventArgs e) { DataDictionaryHub.AssemblyInfoHasChanged(); DataDictionaryHub.RoleInfoHasChanged(); } } }
using UnityEngine; using System.Collections; public class Health : MonoBehaviour { public int hp = 100; private bool ko = false; public void Damage(int damage) { hp -= damage; if (hp <= 0) { ko = true; } } public bool isKo() { return ko; } public void setKo(bool x) { ko = x; } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Timer : MonoBehaviour { public Text user; public Text ai; float timeLeft = 120; public Text text; void Update() { int user_score = int.Parse(user.text); int ai_score = int.Parse(ai.text); //timeLeft--; //timeLeft -= Time.deltaTime; timeLeft = timeLeft-Time.deltaTime; text.text = "" + Mathf.Round(timeLeft); if ((timeLeft < 0 )&&(user_score>ai_score)) { Application.LoadLevel("UserWon"); } else if((timeLeft < 0) && (user_score < ai_score)) { Application.LoadLevel("AIWon"); } else if((timeLeft < 0) && (user_score == ai_score)) { Application.LoadLevel("draw"); } } }
using Presenter.Core.Entities; using Presenter.Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Drawing; using System.IO; namespace Presenter.Core.ScreeenManager { public class ScreenManager : IScreenManager, IObserver { private IDataManager _dataManager; private List<Presentation> _presentations; private string _slideShowApplicationExecutable; private string _defaultHtmlTemplatePath; public ScreenManager(IConfigurationManager configurationManager, IDataManager dataManager) { _dataManager = dataManager; _presentations = configurationManager.Configuration.Presentations; _slideShowApplicationExecutable = configurationManager.Configuration.SlideShowApplicationExecutable; _defaultHtmlTemplatePath = configurationManager.Configuration.DefaultHtmlTemplatePath; foreach (var presentation in _presentations) { presentation.Products = _dataManager.GetProductsByFamily(presentation.FamilyId); presentation.Start(this); } } public void Notify() { throw new NotImplementedException(); } public Process StartPresentation(Presentation presentation) { var process = new Process(); Rectangle screen; process.StartInfo.FileName = _slideShowApplicationExecutable; process.StartInfo.Arguments = BuildPresentationFiles(presentation); process.Start(); // Get the handle for window this is neccesary for get the handle process.WaitForInputIdle(); //Thread.Sleep(100); if (Screen.AllScreens.Length < presentation.Screen) throw new ArgumentException($"The screen {presentation.Screen} doesn't exist"); if (presentation.Screen >= 1) { screen = Screen.AllScreens[presentation.Screen - 1].WorkingArea; //change the window to the second monitor SetWindowPos(process.MainWindowHandle, 0, screen.Left, screen.Top, screen.Width, screen.Height, 0); } return process; } private string BuildPresentationFiles(Presentation presentation) { var presentationDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Presenter", "Presentations", $"p_{presentation.FamilyId}"); if (!Directory.Exists(presentationDataDirectory)) { Directory.CreateDirectory(presentationDataDirectory); } var di = new DirectoryInfo(presentationDataDirectory); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } var htmlTemplatePath = presentation.HtmlTemplatePath ?? _defaultHtmlTemplatePath; var htmlTemplate = File.ReadAllText(htmlTemplatePath); // TODO: Add extra logic: HTML Wrappers/ javascript logic var filePath = Path.Combine(presentationDataDirectory, "presentation.html"); using (var file = new StreamWriter(filePath, true)) { foreach (var product in presentation.Products) { file.WriteLine(string.Format(htmlTemplate, product.Name, product.Price, product.ImagePath)); } } return filePath; } private string CreateFileContentFromProduct(Product product) { return $"{product.Name} | {product.Price} | {product.ImagePath}"; } /// <summary> /// Functions por set the position of a window /// </summary> [DllImport("user32")] public static extern long SetWindowPos(IntPtr hwnd, int hWndInsertAfter, int X, int y, int cx, int cy, int wFlagslong); const short SWP_NOSIZE = 0x0001; const short SWP_NOMOVE = 0x0002; const int SWP_NOZORDER = 0x0004; const int SWP_SHOWWINDOW = 0x0040; [DllImport("user32.dll", EntryPoint = "GetWindowLong")] public static extern int GetWindowLong( IntPtr hwnd, int nIndex ); const int WS_THICKFRAME = 0x00040000; const int GWL_STYLE = -16; [DllImport("user32.dll", EntryPoint = "SetWindowLong")] public static extern int SetWindowLong( IntPtr hwnd, int nIndex, int dwNewLong ); } }
using System; using System.IO; using System.Linq; using FluentAssertions; using Leprechaun.Configuration; using Leprechaun.Logging; using Xunit; namespace Leprechaun.Tests { public class ConfigurationImportPathResolverTests { [Fact] public void ResolveImportPaths_ShouldWorkWithAbsolutePath() { var path = Path.Combine(AbsoluteTestRoot, "Directory2", "Bar.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(1).And.Subject.First().Should().Be(path); } [Fact] public void ResolveImportPaths_ShouldWorkWithRelativePath() { var path = Path.Combine(RelativeTestRoot, "Directory2", "Bar.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(1).And.Subject.First().Should().Be(path); } [Fact] public void ResolveImportPaths_ShouldWorkWithDirectoryWildcard() { var path = Path.Combine(AbsoluteTestRoot, "*", "Bar.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(1).And.Subject.First().Should().Be(AbsolutePathToBarConfig); } [Fact] public void ResolveImportPaths_ShouldWorkWithPartialDirectoryWildcard() { var path = Path.Combine(AbsoluteTestRoot, "Dir*", "Bar.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(1).And.Subject.First().Should().Be(AbsolutePathToBarConfig); } [Fact] public void ResolveImportPaths_ShouldWorkWithMultipleWildcard() { var path = Path.Combine(AbsoluteTestRoot, "*", "*.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(1).And.Subject.First().Should().Be(AbsolutePathToBarConfig); } [Fact] public void ResolveImportPaths_ShouldWorkWithMultipleDirectoryWildcard() { var path = Path.Combine(AbsoluteTestRoot, "*", "*", "*.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(1).And.Subject.First().Should().Be(AbsolutePathToFooConfig); } [Fact] public void ResolveImportPaths_ShouldWorkWithRecursiveDirectoryWildcard() { var path = Path.Combine(AbsoluteTestRoot, "**", "*.config"); var sut = CreateTestResolver(); sut.ResolveImportPaths(path).Should().HaveCount(2).And.Contain(AbsolutePathToFooConfig, AbsolutePathToBarConfig); } private string AbsoluteTestRoot => Path.Combine(Environment.CurrentDirectory, "ConfigurationImportPathResolverTests"); private string RelativeTestRoot => $".{Path.DirectorySeparatorChar}ConfigurationImportPathResolverTests"; private string AbsolutePathToBarConfig => Path.Combine(AbsoluteTestRoot, "Directory2", "Bar.config"); private string AbsolutePathToFooConfig => Path.Combine(AbsoluteTestRoot, "Directory1", "Directory1.1", "Foo.config"); private ConfigurationImportPathResolver CreateTestResolver() { return new ConfigurationImportPathResolver(new NullLogger()); } private class NullLogger : ILogger { public void Info(string message) { } public void Debug(string message) { } public void Warn(string message) { } public void Error(string message) { } public void Error(Exception exception) { } public void Error(string message, Exception exception) { } } } }
using System; using System.Data.Entity; using System.Linq; using Futbol5.Entities; using System.Data.Entity.ModelConfiguration; namespace Futbol5.DAL { public class Futbol5Entities : DbContext { public Futbol5Entities() : base("name=Futbol5Entities") { } public virtual DbSet<Campeonato> Campeonatos { get; set; } public virtual DbSet<Equipo> Equipos { get; set; } public virtual DbSet<Jugador> Jugadores { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //modelBuilder.Entity<Campeonato>() // .HasMany(c => c.Equipos) // .WithMany(e => e.Campeonatos) // .Map(m => // { // m.ToTable("CampeonatosEquipos"); // m.MapLeftKey("CampeonatoId"); // m.MapRightKey("EquipoId"); // }); //modelBuilder.Entity<Equipo>() // .HasMany(e => e.Jugadores) // .WithRequired(j => j.Equipo) // .WillCascadeOnDelete(); } } public class Futbol5DbInitializer : DropCreateDatabaseIfModelChanges<Futbol5Entities> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PrimeNumber { /// <summary> /// Вспомогательный класс, используется для распределения числовых интервалов при многопоточной проверке числа на простоту /// </summary> internal class PrimeDivisorManager { private readonly long _end; private readonly long _intervalLength; private object _locker; /// <summary> /// Последний отданный делитель, /// используется так же как начальное значение для 1го интервала /// </summary> private long _lastGiverDivisor; internal PrimeDivisorManager(long start, long end, long intervalLength) { if (end < start) throw new ArgumentOutOfRangeException($"{nameof(end)} must be > {nameof(start)}"); if (intervalLength < 1) throw new ArgumentOutOfRangeException($"{nameof(intervalLength)} must be >= 1"); _lastGiverDivisor = start - 1; _end = end; _intervalLength = intervalLength; _locker = new object(); } internal Tuple<long, long> GetSearchInterval() { lock (_locker) { long start = _lastGiverDivisor + 1; if (start > _end) return null; long end = _lastGiverDivisor + _intervalLength * 2; if (end > _end) end = _end; _lastGiverDivisor = end; return new Tuple<long, long>(start, end); } } } }
using NRaas.CommonSpace.Options; using NRaas.MasterControllerSpace.SelectionCriteria; using Sims3.Gameplay; using Sims3.Gameplay.Abstracts; using Sims3.Gameplay.Actors; using Sims3.Gameplay.Autonomy; using Sims3.Gameplay.CAS; using Sims3.Gameplay.Core; using Sims3.Gameplay.Interactions; using Sims3.Gameplay.Interfaces; using Sims3.Gameplay.MapTags; using Sims3.Gameplay.Objects; using Sims3.SimIFace; using Sims3.SimIFace.CAS; using Sims3.UI; using System; using System.Collections.Generic; using System.Text; namespace NRaas.MasterControllerSpace.Sims.Tags { public class RemoveTag : SimFromList, ITagsOption { public override string GetTitlePrefix() { return "RemoveTag"; } protected override int GetMaxSelection() { return 0; } protected override bool CanApplyAll() { return true; } protected override bool AutoApplyAll() { return true; } protected override bool Allow(GameHitParameters<GameObject> parameters) { MapTagManager manager = MapTagManager.ActiveMapTagManager; if (manager == null) return false; return base.Allow(parameters); } protected override bool PrivateAllow(SimDescription me) { if (me.CreatedSim == null) return false; MapTagManager manager = MapTagManager.ActiveMapTagManager; if (manager == null) return false; AddTag.TagItem tag = manager.GetTag(me.CreatedSim) as AddTag.TagItem; return (tag != null); } public static bool Perform(Sim me) { foreach (Sim sim in CommonSpace.Helpers.Households.AllSims(Household.ActiveHousehold)) { MapTagManager manager = sim.MapTagManager; if (manager == null) continue; AddTag.TagItem tag = manager.GetTag(me) as AddTag.TagItem; if (tag == null) continue; manager.RemoveTag(me); } return true; } protected override bool Run(SimDescription me, bool singleSelection) { return Perform(me.CreatedSim); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace test.Models { public class Post { public long Id { get; set; } /// <summary> /// För att få routningen att fungera för posts /// </summary> public string Key { get { if(Title == null) { return null; } var key = Regex.Replace(Title, @"[^a-zA-Z0-9\- ]", string.Empty); return key.Replace(" ", "-").ToLower(); } } [Required(ErrorMessage ="Du måste ha en titel")] [DataType(DataType.Text)] [Display(Name="Titel")] [StringLength(100, MinimumLength = 5, ErrorMessage = "Titeln måste vara mellan 5 - 100 tecken långt")] public string Title { get; set; } public string Author { get; set; } public DateTime PostedDate { get; set; } [Required(ErrorMessage = "Du måste ha text i ditt inlägg")] [DataType(DataType.MultilineText)] [Display(Name="Inlägg")] [MinLength(5, ErrorMessage = "Inlägget måste vara minst 5 tecken långt")] public string Body { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Rwd.Framework { public static class Dates { private static DateTime currentDate = DateTime.Now; public static DateTime CurrentDate { get { return currentDate; } set { currentDate = value; } } /// <summary> /// /// </summary> /// <returns></returns> public static DateTime Default { get { return new DateTime(1, 1, 1); } } /// <summary> /// /// </summary> /// <returns></returns> public static bool IsDefault(DateTime? date) { if (date == null || date == Dates.Default) return true; else if (date == new DateTime(1800, 1, 1)) return true; else if (date == new DateTime(1900, 1, 1)) return true; else return false; } /// <summary> /// /// </summary> /// <returns></returns> public static bool IsNotDefault(DateTime? date) { return !Dates.IsDefault(date); } /// <summary> /// Returns date of given day of the current week /// </summary> /// <returns></returns> public static DateTime DayOfCurrentWeek(DayOfWeek day) { int diff = Dates.CurrentDate.DayOfWeek - day; if (diff < 0) { diff += 7; } return Dates.CurrentDate.AddDays(-1 * diff).Date; } /// <summary> /// /// </summary> /// <param name="month"></param> /// <param name="year"></param> /// <returns></returns> public static DateTime GetFirstDateCurrentMonth() { return DateTime.Parse(Dates.CurrentDate.Month.ToString() + "/1/" + Dates.CurrentDate.Year.ToString()); } /// <summary> /// /// </summary> /// <param name="month"></param> /// <param name="year"></param> /// <returns></returns> public static DateTime GetFirstDateOfMonth(int month, int year) { return DateTime.Parse(month.ToString() + "/1/" + year.ToString()); } /// <summary> /// /// </summary> /// <param name="month"></param> /// <param name="year"></param> /// <returns></returns> public static DateTime GetFirstDayOfNextMonth(int month, int year) { var firstDayOfMonth = Dates.GetFirstDateOfMonth(month, year); return firstDayOfMonth.AddMonths(1); } /// <summary> /// /// </summary> /// <param name="month"></param> /// <param name="year"></param> /// <returns></returns> public static DateTime GetFirstDayOfNextMonth(DateTime now) { return Dates.GetFirstDayOfNextMonth(now.Month, now.Year); } /// <summary> /// Converts the given month int to month name /// </summary> ///<param name="month">month in</param> /// <param name="abbrev">return abbreviated or not</param> /// <returns>Short or long month name</returns> public static string GetMonthName(int month, bool abbrev) { DateTime date = new DateTime(1900, month, 1); if (abbrev) return date.ToString("MMM"); return date.ToString("MMMM"); } /// <summary> /// /// </summary> /// <param name="quarter"></param> /// <param name="year"></param> /// <returns></returns> public static DateRange GetDateRangeByQuarter(int fromQuarter, int toQuarter, int year) { var startDate = Dates.CurrentDate; var endDate = Dates.CurrentDate; switch (fromQuarter) { case 1: startDate = DateTime.Parse("1/1/" + year.ToString()); break; case 2: startDate = DateTime.Parse("4/1/" + year.ToString()); break; case 3: startDate = DateTime.Parse("7/1/" + year.ToString()); break; case 4: startDate = DateTime.Parse("10/1/" + year.ToString()); break; } switch (toQuarter) { case 1: endDate = DateTime.Parse("3/31/" + year.ToString()); break; case 2: endDate = DateTime.Parse("6/30/" + year.ToString()); break; case 3: endDate = DateTime.Parse("9/30/" + year.ToString()); break; case 4: endDate = DateTime.Parse("12/31/" + year.ToString()); break; } return new DateRange(startDate, endDate); } /// <summary> /// /// </summary> /// <param name="quarter"></param> /// <param name="year"></param> /// <returns></returns> public static DateRange GetDateRangeByQuarter(string fromQuarter, string toQuarter, int year) { return GetDateRangeByQuarter(int.Parse(fromQuarter), int.Parse(toQuarter), year); } /// <summary> /// /// </summary> /// <param name="quarter"></param> /// <param name="year"></param> /// <returns></returns> public static DateRange GetDateRangeByYear(string fromYear, string toYear) { return GetDateRangeByYear(int.Parse(fromYear), int.Parse(toYear)); } /// <summary> /// /// </summary> /// <param name="quarter"></param> /// <param name="year"></param> /// <returns></returns> public static DateRange GetDateRangeByYear(int fromYear, int toYear) { return new DateRange(DateTime.Parse("1/1/" + fromYear.ToString()), DateTime.Parse("12/31/" + toYear.ToString())); } /// <summary> /// /// </summary> /// <param name="quarter"></param> /// <returns></returns> public static List<int> GetMonthsInQuarter(int quarter) { var month = new List<int>(); switch (quarter) { case 1: month.Add(1); month.Add(2); month.Add(3); break; case 2: month.Add(4); month.Add(5); month.Add(6); break; case 3: month.Add(7); month.Add(8); month.Add(9); break; case 4: month.Add(10); month.Add(11); month.Add(12); break; } return month; } /// <summary> /// /// </summary> /// <param name="range"></param> /// <returns></returns> public static int GetQuarterByDate(DateTime date) { var quarter = 0; var m = date.Month; if (m == 1 || m == 2 || m == 3) quarter = 1; else if (m == 4 || m == 5 || m == 6) quarter = 2; else if (m == 7 || m == 8 || m == 9) quarter = 3; else if (m == 10 || m == 11 || m == 12) quarter = 4; return quarter; } /// <summary> /// /// </summary> /// <param name="date"></param> /// <param name="dayOfWeek"></param> /// <returns></returns> public static List<DateTime> GetUniqueDaysOfWeekInAMonth(DateTime date, DayOfWeek dayOfWeek) { var dates = Enumerable.Range(1, DateTime.DaysInMonth(date.Year, date.Month)) .Select(n => new DateTime(date.Year, date.Month, n)); // then filter the only the start of weeks return (from d in dates where d.DayOfWeek == dayOfWeek select d).ToList(); } /// <summary> /// /// </summary> /// <param name="range"></param> /// <returns></returns> public static List<DateTime> GetUniqueMonthsinDateRange(DateRange range) { var months = new List<DateTime>(); if (range.StartDate != null && range.EndDate != null) { var lastMonth = ((DateTime)(range.EndDate)).Month; var currentMonth = ((DateTime)(range.StartDate)).Month; for (int m = currentMonth; m <= lastMonth; m++) months.Add(DateTime.Parse(m + "/1/" + ((DateTime)(range.EndDate)).Year)); } return months; } /// <summary> /// /// </summary> /// <param name="range"></param> /// <returns></returns> public static List<int> GetUniqueQuartersinDateRange(DateRange range) { var quarters = new List<int>(); if (range.StartDate != null && range.EndDate != null) { var lastMonth = ((DateTime)(range.EndDate)).Month; var currentMonth = ((DateTime)(range.StartDate)).Month; for (int m = currentMonth; m <= lastMonth; m++) { int quarter = 0; if (m == 1 || m == 2 || m == 3) quarter = 1; else if (m == 4 || m == 5 || m == 6) quarter = 2; else if (m == 7 || m == 8 || m == 9) quarter = 3; else if (m == 10 || m == 11 || m == 12) quarter = 4; if (!quarters.Exists(n => n == quarter)) quarters.Add(quarter); } } return quarters; } /// <summary> /// /// </summary> /// <param name="range"></param> /// <returns></returns> public static List<int> GetUniqueYearsinDateRange(DateRange range) { var years = new List<int>(); if (range.StartDate != null && range.EndDate != null) { var lastYear = ((DateTime)(range.EndDate)).Year; var firstYear = ((DateTime)(range.StartDate)).Year; for (int y = firstYear; y <= lastYear; y++) years.Add(y); } return years; } } public class DateRange : IEquatable<DateRange> { Nullable<DateTime> startDate, endDate; public DateRange() : this(new Nullable<DateTime>(), new Nullable<DateTime>()) { } public DateRange(Nullable<DateTime> startDate, Nullable<DateTime> endDate) { AssertStartDateFollowsEndDate(startDate, endDate); this.startDate = startDate; this.endDate = endDate; } public DateRange(string strStartDate, string strEndDate) { DateTime? startDate = null; DateTime? endDate = null; if (strStartDate.Length > 0) startDate = DateTime.Parse(strStartDate); if (strEndDate.Length > 0) endDate = DateTime.Parse(strEndDate); AssertStartDateFollowsEndDate(startDate, endDate); this.startDate = startDate; this.endDate = endDate; } public Nullable<TimeSpan> TimeSpan { get { return endDate - startDate; } } public Nullable<DateTime> StartDate { get { return startDate; } set { AssertStartDateFollowsEndDate(value, this.endDate); startDate = value; } } public Nullable<DateTime> EndDate { get { return endDate; } set { AssertStartDateFollowsEndDate(this.startDate, value); endDate = value; } } private void AssertStartDateFollowsEndDate(Nullable<DateTime> startDate, Nullable<DateTime> endDate) { if ((startDate.HasValue && endDate.HasValue) && (endDate.Value < startDate.Value)) throw new InvalidOperationException("Start Date must be less than or equal to End Date"); } public DateRange GetIntersection(DateRange other) { if (!Intersects(other)) throw new InvalidOperationException("DateRanges do not intersect"); return new DateRange(GetLaterStartDate(other.StartDate), GetEarlierEndDate(other.EndDate)); } private Nullable<DateTime> GetLaterStartDate(Nullable<DateTime> other) { return Nullable.Compare<DateTime>(startDate, other) >= 0 ? startDate : other; } private Nullable<DateTime> GetEarlierEndDate(Nullable<DateTime> other) { //!endDate.HasValue == +infinity, not negative infinity //as is the case with !startDate.HasValue if (Nullable.Compare<DateTime>(endDate, other) == 0) return other; if (endDate.HasValue && !other.HasValue) return endDate; if (!endDate.HasValue && other.HasValue) return other; return (Nullable.Compare<DateTime>(endDate, other) >= 0) ? other : endDate; } public bool Intersects(DateRange other) { if ((this.startDate.HasValue && other.EndDate.HasValue && other.EndDate.Value < this.startDate.Value) || (this.endDate.HasValue && other.StartDate.HasValue && other.StartDate.Value > this.endDate.Value) || (other.StartDate.HasValue && this.endDate.HasValue && this.endDate.Value < other.StartDate.Value) || (other.EndDate.HasValue && this.startDate.HasValue && this.startDate.Value > other.EndDate.Value)) { return false; } return true; } public bool Equals(DateRange other) { if (object.ReferenceEquals(other, null)) return false; return ((startDate == other.StartDate) && (endDate == other.EndDate)); } } public class DateRangeComparerByStartDate : System.Collections.IComparer, System.Collections.Generic.IComparer<DateRange> { public int Compare(object x, object y) { if (!(x is DateRange) || !(y is DateRange)) throw new System.ArgumentException("Value not a DateRange"); return Compare((DateRange)x, (DateRange)y); } public int Compare(DateRange x, DateRange y) { if (x.StartDate < y.StartDate) { return -1; } if (x.StartDate > y.StartDate) { return 1; } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CreditasChallenge.Domain.Entities { public abstract class EntityBase { public int Id { get; set; } //TODO: outras propriedades que serão comuns a todas as entidades } }
using UnityEngine; using UnityEditor; namespace BanSupport { [CustomPropertyDrawer(typeof(IntConditionAttribute))] public class IntConditionPropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { IntConditionAttribute condHAtt = (IntConditionAttribute)attribute; bool enabled = IsShow(condHAtt, property); if (enabled) { EditorGUI.PropertyField(position, property, label, true); } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { IntConditionAttribute condHAtt = (IntConditionAttribute)attribute; if (IsShow(condHAtt, property)) { return EditorGUI.GetPropertyHeight(property, label); } else { return -EditorGUIUtility.standardVerticalSpacing; } } private bool IsShow(IntConditionAttribute conditionAttribute, SerializedProperty property) { bool enabled = true; string propertyPath = property.propertyPath; string conditionPath = propertyPath.Replace(property.name, conditionAttribute.intField); SerializedProperty sourcePropertyValue = property.serializedObject.FindProperty(conditionPath); if (sourcePropertyValue != null) { enabled = sourcePropertyValue.intValue == conditionAttribute.expertValue; } else { Debug.LogWarning("Attempting to use a ConditionAttribute but no matching SourcePropertyValue found in object: " + conditionAttribute.intField); } return enabled; } } }
using UnityEngine; public class InAdvanceCreateField : MonoBehaviour { #if UNITY_EDITOR [SerializeField, Range(1, 8)] int stageNumber = 1; void Update() { if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { if (Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftControl)) { AllCreateSelectField(); } else { CreateSelectField(stageNumber); } } } void AllCreateSelectField() { for (int i = 0; i < 8; ++i) { CreateSelectField(i + 1); } } void CreateSelectField(int num) { Debug.Log("Stage" + num + ":CreateStart"); GameObject field = new GameObject("field" + num); BlockMap blockMap = new BlockMap(); //マップ生成 BlockCreater.GetInstance().CreateField("Stage" + num, field.transform, blockMap, null); GameObject combineField = new GameObject("field" + num); //中身のrendererをOff blockMap.BlockRendererUpdate(); //統合 MeshCombine.Combine(field, combineField); Destroy(field); CreateAsset("Assets/Models/SelectField/Field" + num, "Assets/Prefabs/SelectField", combineField, num); Destroy(combineField); Debug.Log("Stage" + num + ":CreateEnd"); } void CreateAsset(string modelPath, string prefabPath, GameObject obj, int num) { System.IO.Directory.CreateDirectory(modelPath); System.IO.Directory.CreateDirectory(prefabPath); obj.transform.position = new Vector3(25, 0, 25); //メッシュの生成 foreach (var filter in obj.GetComponentsInChildren<MeshFilter>()) { filter.transform.position = Vector3.zero; string[] names = filter.GetComponent<MeshRenderer>().material.name.Split('('); UnityEditor.AssetDatabase.CreateAsset(filter.mesh, modelPath + "/" + names[0] + ".asset"); } //prefab化 UnityEditor.PrefabUtility.SaveAsPrefabAsset(obj, prefabPath + "/Field" + num + ".prefab"); } #endif }
using DFC.ServiceTaxonomy.PageLocation.Models; using OrchardCore.ContentManagement; using YesSql.Indexes; namespace DFC.ServiceTaxonomy.PageLocation.Indexes { public class PageLocationPartIndex : MapIndex { public string? ContentItemId { get; set; } public string? Url { get; set; } } public class PageLocationPartIndexProvider : IndexProvider<ContentItem> { public override void Describe(DescribeContext<ContentItem> context) { context.For<PageLocationPartIndex>() .Map(contentItem => { var url = contentItem.As<PageLocationPart>()?.FullUrl; if (!string.IsNullOrEmpty(url) && (contentItem.Published || contentItem.Latest)) { return new PageLocationPartIndex { ContentItemId = contentItem.ContentItemId, Url = url }; } #pragma warning disable CS8603 // Possible null reference return. return null; #pragma warning restore CS8603 // Possible null reference return. }); } } }
/******************************************************************************\ * Copyright (C) 2012-2016 Leap Motion, Inc. All rights reserved. * * Leap Motion proprietary and confidential. Not for distribution. * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * \******************************************************************************/ namespace Leap { using System; /** * The LeapTransform class represents a transform in three dimensional space. * * Note that the LeapTransform class replaces the Leap.Matrix class. * @since 3.1.2 */ public struct LeapTransform { /** * Constructs a new transform from the specified translation and rotation. * @param translation the translation vector. * @param rotation the rotation quaternion. * @since 3.1.2 */ public LeapTransform(Vector translation, LeapQuaternion rotation) : this(translation, rotation, Vector.Ones) { } /** * Constructs a new transform from the specified translation, rotation and scale. * @param translation the translation vector. * @param rotation the rotation quaternion. * @param scale the scale vector. * @since 3.1.2 */ public LeapTransform(Vector translation, LeapQuaternion rotation, Vector scale) : this() { _scale = scale; // these are non-trival setters. this.translation = translation; this.rotation = rotation; // Calls validateBasis } /** * Transforms the specified position vector, applying translation, rotation and scale. * @param point the position vector to transform. * @returns the new position vector. * @since 3.1.2 */ public Vector TransformPoint(Vector point) { return _xBasisScaled * point.x + _yBasisScaled * point.y + _zBasisScaled * point.z + translation; } /** * Transforms the specified direction vector, applying rotation only. * @param direction the direction vector to transform. * @returns the new direction vector. * @since 3.1.2 */ public Vector TransformDirection(Vector direction) { return _xBasis * direction.x + _yBasis * direction.y + _zBasis * direction.z; } /** * Transforms the specified velocity vector, applying rotation and scale. * @param point the velocity vector to transform. * @returns the new velocity vector. * @since 3.1.2 */ public Vector TransformVelocity(Vector velocity) { return _xBasisScaled * velocity.x + _yBasisScaled * velocity.y + _zBasisScaled * velocity.z; } /** * Transforms the specified quaternion. * Multiplies the quaternion representing the rotational part of this transform by the specified * quaternion. * * **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in * an indeterminate state. Neither this function nor the LeapTransform.rotation quaternion can be used after * the basis vectors are set. * * @param rhs the quaternion to transform. * @returns the new quaternion. * @since 3.1.2 */ public LeapQuaternion TransformQuaternion(LeapQuaternion rhs) { if (_quaternionDirty) throw new InvalidOperationException("Calling TransformQuaternion after Basis vectors have been modified."); if (_flip) { // Mirror the axis of rotation accross the flip axis. rhs.x *= _flipAxes.x; rhs.y *= _flipAxes.y; rhs.z *= _flipAxes.z; } LeapQuaternion t = _quaternion.Multiply(rhs); return t; } /** * Mirrors this transform's rotation and scale across the x-axis. Translation is not affected. * @since 3.1.2 */ public void MirrorX() { _xBasis = -_xBasis; _xBasisScaled = -_xBasisScaled; _flip = true; _flipAxes.y = -_flipAxes.y; _flipAxes.z = -_flipAxes.z; } /** * Mirrors this transform's rotation and scale across the z-axis. Translation is not affected. * @since 3.1.2 */ public void MirrorZ() { _zBasis = -_zBasis; _zBasisScaled = -_zBasisScaled; _flip = true; _flipAxes.x = -_flipAxes.x; _flipAxes.y = -_flipAxes.y; } /** * The x-basis of the transform. * * **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in * an indeterminate state. Neither the TransformQuaternion() function nor the LeapTransform.rotation quaternion * can be used after the basis vectors are set. * * @since 3.1.2 */ public Vector xBasis { get { return _xBasis; } set { _xBasis = value; _xBasisScaled = value * scale.x; _quaternionDirty = true; } } /** * The y-basis of the transform. * * **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in * an indeterminate state. Neither the TransformQuaternion() function nor the LeapTransform.rotation quaternion * can be used after the basis vectors are set. * * @since 3.1.2 */ public Vector yBasis { get { return _yBasis; } set { _yBasis = value; _yBasisScaled = value * scale.y; _quaternionDirty = true; } } /** * The z-basis of the transform. * * **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in * an indeterminate state. Neither the TransformQuaternion() function nor the LeapTransform.rotation quaternion * can be used after the basis vectors are set. * * @since 3.1.2 */ public Vector zBasis { get { return _zBasis; } set { _zBasis = value; _zBasisScaled = value * scale.z; _quaternionDirty = true; } } /** * The translation component of the transform. * @since 3.1.2 */ public Vector translation { get { return _translation; } set { _translation = value; } } /** * The scale factors of the transform. * Scale is kept separate from translation. * @since 3.1.2 */ public Vector scale { get { return _scale; } set { _scale = value; _xBasisScaled = _xBasis * scale.x; _yBasisScaled = _yBasis * scale.y; _zBasisScaled = _zBasis * scale.z; } } /** * The rotational component of the transform. * * **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in * an indeterminate state. This rotation quaternion cannot be accessed after * the basis vectors are modified directly. * * @since 3.1.2 */ public LeapQuaternion rotation { get { if (_quaternionDirty) throw new InvalidOperationException("Requesting rotation after Basis vectors have been modified."); return _quaternion; } set { _quaternion = value; float d = value.MagnitudeSquared; float s = 2.0f / d; float xs = value.x * s, ys = value.y * s, zs = value.z * s; float wx = value.w * xs, wy = value.w * ys, wz = value.w * zs; float xx = value.x * xs, xy = value.x * ys, xz = value.x * zs; float yy = value.y * ys, yz = value.y * zs, zz = value.z * zs; _xBasis = new Vector(1.0f - (yy + zz), xy + wz, xz - wy); _yBasis = new Vector(xy - wz, 1.0f - (xx + zz), yz + wx); _zBasis = new Vector(xz + wy, yz - wx, 1.0f - (xx + yy)); _xBasisScaled = _xBasis * scale.x; _yBasisScaled = _yBasis * scale.y; _zBasisScaled = _zBasis * scale.z; _quaternionDirty = false; _flip = false; _flipAxes = new Vector(1.0f, 1.0f, 1.0f); } } /** * The identity transform. * @since 3.1.2 */ public static readonly LeapTransform Identity = new LeapTransform(Vector.Zero, LeapQuaternion.Identity, Vector.Ones); private Vector _translation; private Vector _scale; private LeapQuaternion _quaternion; private bool _quaternionDirty; private bool _flip; private Vector _flipAxes; private Vector _xBasis; private Vector _yBasis; private Vector _zBasis; private Vector _xBasisScaled; private Vector _yBasisScaled; private Vector _zBasisScaled; } }
using System; using System.Linq; using System.Windows; using System.Windows.Controls; namespace Simple.Wpf.Composition.Workspaces { public partial class WorkspaceHost : UserControl { public static readonly DependencyProperty WorkspaceProperty = DependencyProperty.Register("Workspace", typeof(Workspace), typeof(WorkspaceHost), new PropertyMetadata(null, WorkspaceChanged)); public WorkspaceHost() { InitializeComponent(); SetNoWorkspaceContent(); } public Workspace Workspace { get => (Workspace) GetValue(WorkspaceProperty); set => SetValue(WorkspaceProperty, value); } private static void WorkspaceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (e.OldValue == e.NewValue) return; var host = (WorkspaceHost) d; var oldWorkspace = (Workspace) e.OldValue; var newWorkspace = (Workspace) e.NewValue; host.Visibility = Visibility.Hidden; host.UnloadWorkspace(oldWorkspace); host.LoadWorkspace(newWorkspace); host.Visibility = Visibility.Visible; } private void LoadWorkspace(Workspace newWorkspace) { if (newWorkspace != null) { LoadResources(newWorkspace.Resources); WorkspacePresenter.Content = newWorkspace.Content; } else { SetNoWorkspaceContent(); } } private void UnloadWorkspace(Workspace workspace) { if (workspace != null) UnloadResources(workspace.Resources); } private void LoadResources(Uri uri) { if (uri == null) return; var newResourceDictionary = new ResourceDictionary { Source = uri }; Resources.MergedDictionaries.Add(newResourceDictionary); } private void UnloadResources(Uri uri) { if (uri == null) return; var index = Resources.MergedDictionaries.Where(x => x.Source == uri) .Select((x, i) => i) .Single(); if (index != -1) Resources.MergedDictionaries.RemoveAt(index); } private void SetNoWorkspaceContent() { WorkspacePresenter.ContentTemplateSelector = null; WorkspacePresenter.Content = new TextBlock { Text = "No workspace selected!", Margin = new Thickness(5), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity.Core; using PagedList; namespace CNWTT.Models.DAO { public class BillDAO { //private static bill bill = null; public static int addBill(bill bill) { int id = -1; using (var db = new cnwttEntities()) { try { db.bills.Add(bill); db.SaveChanges(); id = bill.id; } catch (EntityCommandExecutionException e){ } catch (EntityException e){ } } return id; } public static bill getBillById(int id) { bill bill = null; using(var db = new cnwttEntities()) { try { bill = db.bills.Find(id); } catch (InvalidOperationException e) { } catch (EntityCommandExecutionException e) { } catch (EntityException e) { } } return bill; } public static IEnumerable<bill> getListPage(int page, int pageSize) { IEnumerable<bill> list = null; using(var db = new cnwttEntities()) { try { //list = db. } catch (EntityCommandExecutionException e){ } catch (EntityException e){ } } return list; } public static IEnumerable<bill> getListProductByCreateDate(string startDate, string endDate, int page, int size) { IEnumerable<bill> list = null; using (var db = new cnwttEntities()) { string sql = " SELECT * " + " FROM bill b " + " WHERE CONVERT(datetime, b.create_at, 105) " + " BETWEEN CONVERT(datetime,'" + startDate + "', 105) " + " AND CONVERT(datetime,'" + endDate + "', 105) "; try { list = db.bills .SqlQuery(sql) .OrderByDescending(b => b.id) .ToPagedList(page, size); } catch (InvalidOperationException e) { } catch (EntityCommandExecutionException e) { } catch (EntityException e) { } } return list; } } }
using gView.Framework.Data.Fields.FieldDomains; using gView.Framework.system; using System; using System.Windows.Forms; namespace gView.Framework.Data.Fields.UI.FieldDomains { public partial class Control_SimpleValueDomain : UserControl, IInitializeClass { private SimpleValuesDomain _domain; public Control_SimpleValueDomain() { InitializeComponent(); } #region IInitializeClass Member async public void Initialize(object parameter) { _domain = parameter as SimpleValuesDomain; if (_domain != null && await _domain.ValuesAsync() != null) { foreach (object val in await _domain.ValuesAsync()) { if (val == null) { continue; } if (!String.IsNullOrEmpty(txtValues.Text)) { txtValues.Text += "\r\n"; } txtValues.Text += val.ToString(); } } } #endregion private void txtValues_TextChanged(object sender, EventArgs e) { if (_domain == null) { return; } string txt = txtValues.Text.Replace("\n", ""); _domain.SetValues(txt.Split('\r')); } } }
using UnityEngine; using System.Collections; public class StalkerSwitch : MonoBehaviour { // public GameObject stalker = null; public bool debugFlag = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter(Collider col){ GameObject g = col.gameObject; if (g.tag == "stalker") { if(debugFlag) { Debug.Log ("Stalker has touched button"); } } } }
using System; namespace Uintra.Features.Notification.Entities.Base { public interface IReminderable { Guid Id { get; set; } DateTime StartDate { get; } } }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using WorkWithDatabase; using WorkWithRegistry; namespace IS_Restoran { /// <summary> /// Логика взаимодействия для OficForm.xaml /// </summary> public partial class OficForm : Window { string DataSource; string UserID; string Password; string InitialCatalog; //SqlConnection conOfic = new SqlConnection(@"server=JSAY; database=Restoran; Integrated Security = true;"); public OficForm() { InitializeComponent(); RegistryKey AuthInfo = RegistryInfo.Key(); if (AuthInfo.ValueCount.Equals(0)) { AuthInfo.SetValue("DataSource", @"KINPC\MSSQLSERVER1"); AuthInfo.SetValue("UserID", "sa"); AuthInfo.SetValue("Password", "1234"); AuthInfo.SetValue("InitialCatalog", "Restoran"); } DataSource = AuthInfo.GetValue("DataSource").ToString(); UserID = AuthInfo.GetValue("UserID").ToString(); Password = AuthInfo.GetValue("Password").ToString(); InitialCatalog = AuthInfo.GetValue("InitialCatalog").ToString(); } private void otrisOfic() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); //SqlConnection conOfic = new SqlConnection(@"server=JSAY; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand MenuCom = new SqlCommand("SELECT * FROM Menu", con); //создание выборки username и pass из таблицы tbl_log SqlCommand ZakazKlCom = new SqlCommand("SELECT * FROM Zakaz", con); SqlCommand Sost_zakaz_klCom = new SqlCommand("SELECT * FROM Sost_zakaz", con); SqlCommand ChekCom = new SqlCommand("SELECT * FROM Chek", con); SqlCommand StolCom = new SqlCommand("SELECT * FROM Stol", con); SqlCommand KlientCom = new SqlCommand("SELECT * FROM Klient", con); SqlCommand BronCom = new SqlCommand("SELECT * FROM Bron", con); SqlCommand StrafCom = new SqlCommand("SELECT * FROM Straf", con); con.Open(); //открытие подключения DataTable MenuDT = new DataTable(); DataTable ZakazKlDT = new DataTable(); DataTable Sost_zakaz_klDT = new DataTable(); DataTable ChekDT = new DataTable(); DataTable StolDT = new DataTable(); DataTable KlientDT = new DataTable(); DataTable BronDT = new DataTable(); DataTable StrafDT = new DataTable(); MenuDT.Load(MenuCom.ExecuteReader()); ZakazKlDT.Load(ZakazKlCom.ExecuteReader()); Sost_zakaz_klDT.Load(Sost_zakaz_klCom.ExecuteReader()); ChekDT.Load(ChekCom.ExecuteReader()); StolDT.Load(StolCom.ExecuteReader()); KlientDT.Load(KlientCom.ExecuteReader()); BronDT.Load(BronCom.ExecuteReader()); StrafDT.Load(StrafCom.ExecuteReader()); MenuTbl.ItemsSource = MenuDT.DefaultView; ZakazKlTbl.ItemsSource = ZakazKlDT.DefaultView; Sost_zakaz_klTbl.ItemsSource = Sost_zakaz_klDT.DefaultView; ChekTbl.ItemsSource = ChekDT.DefaultView; StolTbl.ItemsSource = StolDT.DefaultView; KlientTbl.ItemsSource = KlientDT.DefaultView; BronTbl.ItemsSource = BronDT.DefaultView; StrafTbl.ItemsSource = StrafDT.DefaultView; } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { //conOfic.Close(); } } private void Window_Loaded(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); //SqlConnection conOfic = new SqlConnection(@"server=JSAY; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand MenuCom = new SqlCommand("SELECT * FROM Menu", con); //создание выборки username и pass из таблицы tbl_log SqlCommand ZakazKlCom = new SqlCommand("SELECT * FROM Zakaz", con); SqlCommand Sost_zakaz_klCom = new SqlCommand("SELECT * FROM Sost_zakaz", con); SqlCommand ChekCom = new SqlCommand("SELECT * FROM Chek", con); SqlCommand StolCom = new SqlCommand("SELECT * FROM Stol", con); SqlCommand KlientCom = new SqlCommand("SELECT * FROM Klient", con); SqlCommand BronCom = new SqlCommand("SELECT * FROM Bron", con); SqlCommand StrafCom = new SqlCommand("SELECT * FROM Straf", con); con.Open(); //открытие подключения DataTable MenuDT = new DataTable(); DataTable ZakazKlDT = new DataTable(); DataTable Sost_zakaz_klDT = new DataTable(); DataTable ChekDT = new DataTable(); DataTable StolDT = new DataTable(); DataTable KlientDT = new DataTable(); DataTable BronDT = new DataTable(); DataTable StrafDT = new DataTable(); MenuDT.Load(MenuCom.ExecuteReader()); ZakazKlDT.Load(ZakazKlCom.ExecuteReader()); Sost_zakaz_klDT.Load(Sost_zakaz_klCom.ExecuteReader()); ChekDT.Load(ChekCom.ExecuteReader()); StolDT.Load(StolCom.ExecuteReader()); KlientDT.Load(KlientCom.ExecuteReader()); BronDT.Load(BronCom.ExecuteReader()); StrafDT.Load(StrafCom.ExecuteReader()); MenuTbl.ItemsSource = MenuDT.DefaultView; ZakazKlTbl.ItemsSource = ZakazKlDT.DefaultView; Sost_zakaz_klTbl.ItemsSource = Sost_zakaz_klDT.DefaultView; ChekTbl.ItemsSource = ChekDT.DefaultView; StolTbl.ItemsSource = StolDT.DefaultView; KlientTbl.ItemsSource = KlientDT.DefaultView; BronTbl.ItemsSource = BronDT.DefaultView; StrafTbl.ItemsSource = StrafDT.DefaultView; } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { //conOfic.Close(); } } private void MenuTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (MenuTbl.SelectedItem == null) return; DataRowView row = (DataRowView)MenuTbl.SelectedItem; Name_bludo.Text = row["Name_bludo"].ToString(); Opis_bludo.Text = row["Opis_bludo"].ToString(); Cena_bludo.Text = row["Cena"].ToString(); } private void GetSotrFKZak() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektSotrFKZAkcmd = new SqlCommand("SELECT [ID_Sotr], [Fam_sotr] FROM [dbo].[Sotr]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable SotrFKZak = new DataTable(); SotrFKZak.Load(SelektSotrFKZAkcmd.ExecuteReader()); ID_SotrFKZak.Items.Clear(); foreach (DataRow Row in SotrFKZak.Rows) { ID_SotrFKZak.Items.Add(new IDComboBoxItem((int)Row["ID_Sotr"], Row["Fam_sotr"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetStolFKZak() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektStolFKZakcmd = new SqlCommand("SELECT [ID_Stol], [Nomer_stola] FROM [dbo].[Stol]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable StolFKZak = new DataTable(); StolFKZak.Load(SelektStolFKZakcmd.ExecuteReader()); ID_StolFKZak.Items.Clear(); foreach (DataRow Row in StolFKZak.Rows) { ID_StolFKZak.Items.Add(new IDComboBoxItem((int)Row["ID_Stol"], Row["Nomer_stola"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetKlientFKZak() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektKlientFKZakcmd = new SqlCommand("SELECT [ID_Klient], [FamKl] FROM [dbo].[Klient]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable KlientFKZak = new DataTable(); KlientFKZak.Load(SelektKlientFKZakcmd.ExecuteReader()); ID_KlientFKZak.Items.Clear(); foreach (DataRow Row in KlientFKZak.Rows) { ID_KlientFKZak.Items.Add(new IDComboBoxItem((int)Row["ID_Klient"], Row["FamKl"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void ID_KlientFKZak_DropDownOpened(object sender, EventArgs e) { GetKlientFKZak(); } private void ID_StolFKZak_DropDownOpened(object sender, EventArgs e) { GetStolFKZak(); } private void ID_SotrFKZak_DropDownOpened(object sender, EventArgs e) { GetSotrFKZak(); } private void ZakazKlTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (ZakazKlTbl.SelectedItem == null) return; DataRowView row = (DataRowView)ZakazKlTbl.SelectedItem; Summ_zak.Text = row["Summ_zack"].ToString(); Nom_zak.Text = row["Nom_zack"].ToString(); Time_vid.Text = row["Time_vid"].ToString(); Time_prin.Text = row["Time_prin"].ToString(); GetSotrFKZak(); GetStolFKZak(); GetKlientFKZak(); foreach (IDComboBoxItem item in ID_SotrFKZak.Items) { if (item.ID == (int)row["ID_Sotr"]) { ID_SotrFKZak.SelectedIndex = ID_SotrFKZak.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_StolFKZak.Items) { if (item.ID == (int)row["ID_Stol"]) { ID_StolFKZak.SelectedIndex = ID_StolFKZak.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_KlientFKZak.Items) { if (item.ID == (int)row["ID_Klient"]) { ID_KlientFKZak.SelectedIndex = ID_KlientFKZak.Items.IndexOf(item); } } } private void AddZakazKl_Click(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand AddZakazKlCom = new SqlCommand("AddZakaz", con); //создание выборки username и pass из таблицы tbl_log AddZakazKlCom.CommandType = CommandType.StoredProcedure; con.Open(); //открытие подключения AddZakazKlCom.Parameters.AddWithValue("@Summ_zack", Summ_zak.Text); AddZakazKlCom.Parameters.AddWithValue("@Nom_zack", Nom_zak.Text); AddZakazKlCom.Parameters.AddWithValue("@Time_vid", Time_vid.Text); AddZakazKlCom.Parameters.AddWithValue("@Time_prin", Time_prin.Text); AddZakazKlCom.Parameters.AddWithValue("@ID_Sotr", (int)(ID_SotrFKZak.SelectedItem as IDComboBoxItem).ID); AddZakazKlCom.Parameters.AddWithValue("@ID_Klient", (int)(ID_KlientFKZak.SelectedItem as IDComboBoxItem).ID); AddZakazKlCom.Parameters.AddWithValue("@ID_Stol", (int)(ID_StolFKZak.SelectedItem as IDComboBoxItem).ID); AddZakazKlCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void UpdZakazKl_Click(object sender, RoutedEventArgs e) { if (ID_SotrFKZak.SelectedItem == null) return; if (ID_KlientFKZak.SelectedItem == null) return; if (ID_StolFKZak.SelectedItem == null) return; if (ZakazKlTbl.SelectedItem == null) return; DataRowView ZakazKl = (DataRowView)ZakazKlTbl.SelectedItem; try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); SqlCommand UpdZakazCom = new SqlCommand("UpdateZakaz", con); UpdZakazCom.CommandType = CommandType.StoredProcedure; //MessageBox.Show(con.ConnectionString.ToString()); con.Open(); //открытие подключения UpdZakazCom.Parameters.AddWithValue("@ID_Zak", (int)ZakazKl["ID_Zack"]); UpdZakazCom.Parameters.AddWithValue("@Summ_zack", Summ_zak.Text); UpdZakazCom.Parameters.AddWithValue("@Nom_zack", Nom_zak.Text); UpdZakazCom.Parameters.AddWithValue("@Time_vid", Time_vid.Text); UpdZakazCom.Parameters.AddWithValue("@Time_prin", Time_prin.Text); UpdZakazCom.Parameters.AddWithValue("@ID_Sotr", (int)(ID_SotrFKZak.SelectedItem as IDComboBoxItem).ID); UpdZakazCom.Parameters.AddWithValue("@ID_Klient", (int)(ID_KlientFKZak.SelectedItem as IDComboBoxItem).ID); UpdZakazCom.Parameters.AddWithValue("@ID_Stol", (int)(ID_StolFKZak.SelectedItem as IDComboBoxItem).ID); UpdZakazCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void DelZakazKl_Click(object sender, RoutedEventArgs e) { if (ZakazKlTbl.SelectedItem == null) return; DataRowView ZakazKl = (DataRowView)ZakazKlTbl.SelectedItem; if (!(MessageBox.Show("Вы точно хотите удалить запись?", "Удаление", MessageBoxButton.YesNo) == MessageBoxResult.Yes)) return; try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); SqlCommand DelZakazCom = new SqlCommand("DelZakaz", con); DelZakazCom.CommandType = CommandType.StoredProcedure; //MessageBox.Show(con.ConnectionString.ToString()); con.Open(); //открытие подключения DelZakazCom.Parameters.AddWithValue("@ID_Zakaz", (int)ZakazKl["ID_Zack"]); DelZakazCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void GetZakKlFKBludo() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektZakKlFKBludocmd = new SqlCommand("SELECT [ID_Zack], [Nom_zack] FROM [dbo].[Zakaz]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable ZakKlFKBludo = new DataTable(); ZakKlFKBludo.Load(SelektZakKlFKBludocmd.ExecuteReader()); ID_ZakKlFKBludo.Items.Clear(); foreach (DataRow Row in ZakKlFKBludo.Rows) { ID_ZakKlFKBludo.Items.Add(new IDComboBoxItem((int)Row["ID_Zack"], Row["Nom_zack"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetBludoFKSostZak() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektBludoFKSostZakcmd = new SqlCommand("SELECT [ID_Bludo], [Name_bludo] FROM [dbo].[Menu]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable BludoFKSostZak = new DataTable(); BludoFKSostZak.Load(SelektBludoFKSostZakcmd.ExecuteReader()); ID_BludoFKSostZak.Items.Clear(); foreach (DataRow Row in BludoFKSostZak.Rows) { ID_BludoFKSostZak.Items.Add(new IDComboBoxItem((int)Row["ID_Bludo"], Row["Name_bludo"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void ID_BludoFKSostZak_DropDownOpened(object sender, EventArgs e) { GetBludoFKSostZak(); } private void ID_ZakKlFKBludo_DropDownOpened(object sender, EventArgs e) { GetZakKlFKBludo(); } private void Sost_zakaz_klTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (Sost_zakaz_klTbl.SelectedItem == null) return; DataRowView row = (DataRowView)Sost_zakaz_klTbl.SelectedItem; Kolvo_blud.Text = row["Kolvo"].ToString(); GetBludoFKSostZak(); GetZakKlFKBludo(); foreach (IDComboBoxItem item in ID_BludoFKSostZak.Items) { if (item.ID == (int)row["ID_Bludo"]) { ID_BludoFKSostZak.SelectedIndex = ID_BludoFKSostZak.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_ZakKlFKBludo.Items) { if (item.ID == (int)row["ID_Zack"]) { ID_ZakKlFKBludo.SelectedIndex = ID_ZakKlFKBludo.Items.IndexOf(item); } } } private void AddSost_zakaz_kl_Click(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand AddSost_zakaz_klCom = new SqlCommand("AddSost_zakaz", con); //создание выборки username и pass из таблицы tbl_log AddSost_zakaz_klCom.CommandType = CommandType.StoredProcedure; con.Open(); //открытие подключения AddSost_zakaz_klCom.Parameters.AddWithValue("@Kolvo", Kolvo_blud.Text); AddSost_zakaz_klCom.Parameters.AddWithValue("@ID_Bludo", (int)(ID_BludoFKSostZak.SelectedItem as IDComboBoxItem).ID); AddSost_zakaz_klCom.Parameters.AddWithValue("@ID_Zack", (int)(ID_ZakKlFKBludo.SelectedItem as IDComboBoxItem).ID); AddSost_zakaz_klCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void UpdSost_zakaz_kl_Click(object sender, RoutedEventArgs e) { if (ID_BludoFKSostZak.SelectedItem == null) return; if (ID_ZakKlFKBludo.SelectedItem == null) return; if (Sost_zakaz_klTbl.SelectedItem == null) return; DataRowView Sost_zakaz_kl = (DataRowView)Sost_zakaz_klTbl.SelectedItem; try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); SqlCommand UpdSost_zakaz_klCom = new SqlCommand("UpdateSost_zakaz", con); UpdSost_zakaz_klCom.CommandType = CommandType.StoredProcedure; //MessageBox.Show(con.ConnectionString.ToString()); con.Open(); //открытие подключения UpdSost_zakaz_klCom.Parameters.AddWithValue("@ID_SostZak", (int)Sost_zakaz_kl["ID_Sost_zakaz"]); UpdSost_zakaz_klCom.Parameters.AddWithValue("@Kolvo", Kolvo_blud.Text); UpdSost_zakaz_klCom.Parameters.AddWithValue("@ID_Bludo", (int)(ID_BludoFKSostZak.SelectedItem as IDComboBoxItem).ID); UpdSost_zakaz_klCom.Parameters.AddWithValue("@ID_Zack", (int)(ID_ZakKlFKBludo.SelectedItem as IDComboBoxItem).ID); UpdSost_zakaz_klCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic (); } private void DelSost_zakaz_kl_Click(object sender, RoutedEventArgs e) { if (Sost_zakaz_klTbl.SelectedItem == null) return; DataRowView Sost_zakaz_kl = (DataRowView)Sost_zakaz_klTbl.SelectedItem; if (!(MessageBox.Show("Вы точно хотите удалить запись?", "Удаление", MessageBoxButton.YesNo) == MessageBoxResult.Yes)) return; try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); SqlCommand DelSost_zakaz_klCom = new SqlCommand("DelSost_zakaz", con); DelSost_zakaz_klCom.CommandType = CommandType.StoredProcedure; //MessageBox.Show(con.ConnectionString.ToString()); con.Open(); //открытие подключения DelSost_zakaz_klCom.Parameters.AddWithValue("@ID_SostZak", (int)Sost_zakaz_kl["ID_Sost_zakaz"]); DelSost_zakaz_klCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void GetZakazKlFK() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektZakazKlFKcmd = new SqlCommand("SELECT [ID_Zack], [Nom_zack] FROM [dbo].[Zakaz]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable ZakazKlFK = new DataTable(); ZakazKlFK.Load(SelektZakazKlFKcmd.ExecuteReader()); ID_ZakazKlFK.Items.Clear(); foreach (DataRow Row in ZakazKlFK.Rows) { ID_ZakazKlFK.Items.Add(new IDComboBoxItem((int)Row["ID_Zack"], Row["Nom_zack"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetShtrafFKChek() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektShtrafFKChekcmd = new SqlCommand("SELECT [ID_Straf], [Summ_str] FROM [dbo].[Straf]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable ShtrafFKChek = new DataTable(); ShtrafFKChek.Load(SelektShtrafFKChekcmd.ExecuteReader()); ID_ShtrafFKChek.Items.Clear(); foreach (DataRow Row in ShtrafFKChek.Rows) { ID_ShtrafFKChek.Items.Add(new IDComboBoxItem((int)Row["ID_Straf"], Row["Summ_str"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void ID_ZakazKlFK_DropDownOpened(object sender, EventArgs e) { GetZakazKlFK(); } private void ID_ShtrafFKChek_DropDownOpened(object sender, EventArgs e) { GetShtrafFKChek(); } private void ChekTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (ChekTbl.SelectedItem == null) return; DataRowView row = (DataRowView)ChekTbl.SelectedItem; Nomer_chek.Text = row["Nomer_chek"].ToString(); TIme_chek.Text = row["Time_chek"].ToString(); Summ_chek.Text = row["Summ_chek"].ToString(); GetZakazKlFK(); GetShtrafFKChek(); foreach (IDComboBoxItem item in ID_ZakazKlFK.Items) { if (item.ID == (int)row["ID_Zack"]) { ID_ZakazKlFK.SelectedIndex = ID_ZakazKlFK.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_ShtrafFKChek.Items) { if (item.ID == (int)row["ID_Straf"]) { ID_ShtrafFKChek.SelectedIndex = ID_ShtrafFKChek.Items.IndexOf(item); } } } private void AddChek_Click(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand AddChek_klCom = new SqlCommand("AddChek", con); //создание выборки username и pass из таблицы tbl_log AddChek_klCom.CommandType = CommandType.StoredProcedure; con.Open(); //открытие подключения AddChek_klCom.Parameters.AddWithValue("@Nomer_chek", Nomer_chek.Text); AddChek_klCom.Parameters.AddWithValue("@Time_chek", TIme_chek.Text); AddChek_klCom.Parameters.AddWithValue("@Summ_chek", Summ_chek.Text); AddChek_klCom.Parameters.AddWithValue("@ID_Zack", (int)(ID_ZakazKlFK.SelectedItem as IDComboBoxItem).ID); AddChek_klCom.Parameters.AddWithValue("@ID_Straf", (int)(ID_ShtrafFKChek.SelectedItem as IDComboBoxItem).ID); AddChek_klCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void StolTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (StolTbl.SelectedItem == null) return; DataRowView row = (DataRowView)StolTbl.SelectedItem; Ststus_stol.Text = row["Status_stol"].ToString(); Nomer_stol.Text = row["Nomer_stola"].ToString(); } private void UpdStol_Click(object sender, RoutedEventArgs e) { if (StolTbl.SelectedItem == null) return; DataRowView Vidkvit = (DataRowView)StolTbl.SelectedItem; try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); //SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); SqlCommand UpdStolCom = new SqlCommand("UpdateStol", con); UpdStolCom.CommandType = CommandType.StoredProcedure; //MessageBox.Show(con.ConnectionString.ToString()); con.Open(); //открытие подключения UpdStolCom.Parameters.AddWithValue("@ID_Stol", (int)Vidkvit["ID_Stol"]); UpdStolCom.Parameters.AddWithValue("@Status_stol", Ststus_stol.Text); UpdStolCom.Parameters.AddWithValue("@Nomer_stola", Nomer_stol.Text); UpdStolCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } otrisOfic(); } private void KlientTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (KlientTbl.SelectedItem == null) return; DataRowView row = (DataRowView)KlientTbl.SelectedItem; Fam_Kl.Text = row["FamKl"].ToString(); Im_Kl.Text = row["ImKl"].ToString(); Otch_Kl.Text = row["OtKl"].ToString(); Date_vnes.Text = row["Date_Vn"].ToString(); } private void AddKlient_Click(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand AddKlientCom = new SqlCommand("[dbo].[AddKlient]", con); //создание выборки username и pass из таблицы tbl_log AddKlientCom.CommandType = CommandType.StoredProcedure; con.Open(); //открытие подключения AddKlientCom.Parameters.AddWithValue("@FamKl", Fam_Kl.Text); AddKlientCom.Parameters.AddWithValue("@ImKl", Im_Kl.Text); AddKlientCom.Parameters.AddWithValue("@OtKl", Otch_Kl.Text); AddKlientCom.Parameters.AddWithValue("@Date_Vn", Date_vnes.Text); //AddOtpCom.Parameters.AddWithValue("@ID_Sotr", (int)(ID_SotrFKOtp.SelectedItem as IDComboBoxItem).ID); AddKlientCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { //con.Close(); } otrisOfic(); } private void GetStolFK() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand SelektStolcmd = new SqlCommand("SELECT ID_Stol, Nomer_stola FROM [dbo].[Stol]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable StolFK = new DataTable(); StolFK.Load(SelektStolcmd.ExecuteReader()); ID_StolFKBron.Items.Clear(); foreach (DataRow Row in StolFK.Rows) { ID_StolFKBron.Items.Add(new IDComboBoxItem((int)Row["ID_Stol"], Row["Nomer_stola"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetKlientFK() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektKlientFKZakcmd = new SqlCommand("SELECT [ID_Klient], [FamKl] FROM [dbo].[Klient]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable KlientFKZak = new DataTable(); KlientFKZak.Load(SelektKlientFKZakcmd.ExecuteReader()); ID_KlientFKBron.Items.Clear(); foreach (DataRow Row in KlientFKZak.Rows) { ID_KlientFKBron.Items.Add(new IDComboBoxItem((int)Row["ID_Klient"], Row["FamKl"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetSotrFKBron() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand SelektSotrFKUchcmd = new SqlCommand("SELECT [ID_Sotr], [Fam_sotr] FROM [dbo].[Sotr]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable SotrFKUch = new DataTable(); SotrFKUch.Load(SelektSotrFKUchcmd.ExecuteReader()); ID_SotrFKBron.Items.Clear(); foreach (DataRow Row in SotrFKUch.Rows) { ID_SotrFKBron.Items.Add(new IDComboBoxItem((int)Row["ID_Sotr"], Row["Fam_sotr"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void ID_StolFKBron_DropDownOpened(object sender, EventArgs e) { GetStolFK(); } private void ID_KlientFKBron_SelectionChanged(object sender, SelectionChangedEventArgs e) { GetKlientFK(); } private void ID_SotrFKBron_DropDownOpened(object sender, EventArgs e) { GetSotrFKBron(); } private void BronTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (BronTbl.SelectedItem == null) return; DataRowView row = (DataRowView)BronTbl.SelectedItem; Date_Bron.Text = row["DateBr"].ToString(); GetStolFK(); GetSotrFKBron(); GetKlientFK(); foreach (IDComboBoxItem item in ID_StolFKBron.Items) { if (item.ID == (int)row["ID_Stol"]) { ID_StolFKBron.SelectedIndex = ID_StolFKBron.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_KlientFKBron.Items) { if (item.ID == (int)row["ID_Klient"]) { ID_KlientFKBron.SelectedIndex = ID_KlientFKBron.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_SotrFKBron.Items) { if (item.ID == (int)row["ID_Sotr"]) { ID_SotrFKBron.SelectedIndex = ID_SotrFKBron.Items.IndexOf(item); } } } private void AddBron_Click(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand AddBronCom = new SqlCommand("[dbo].[AddBron]", con); //создание выборки username и pass из таблицы tbl_log AddBronCom.CommandType = CommandType.StoredProcedure; con.Open(); //открытие подключения AddBronCom.Parameters.AddWithValue("@DateBr", Date_Bron.Text); AddBronCom.Parameters.AddWithValue("@ID_Sotr", (int)(ID_SotrFKBron.SelectedItem as IDComboBoxItem).ID); AddBronCom.Parameters.AddWithValue("@ID_Klient", (int)(ID_KlientFKBron.SelectedItem as IDComboBoxItem).ID); AddBronCom.Parameters.AddWithValue("@ID_Stol", (int)(ID_StolFKBron.SelectedItem as IDComboBoxItem).ID); AddBronCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { //con.Close(); } otrisOfic(); } private void GetMebelFKSht() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand SelektStolcmd = new SqlCommand("SELECT ID_Mebel, Nomer_mebel FROM [dbo].[Mebel]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable StolFK = new DataTable(); StolFK.Load(SelektStolcmd.ExecuteReader()); ID_MebelFKStraf.Items.Clear(); foreach (DataRow Row in StolFK.Rows) { ID_MebelFKStraf.Items.Add(new IDComboBoxItem((int)Row["ID_Mebel"], Row["Nomer_mebel"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetKlientFKSht() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); // SqlConnection con = new SqlConnection(@"server=KINPC\MSSQLSERVER1; database=Restoran; Integrated Security = true;"); //создание подключения к БД SqlCommand SelektKlientFKZakcmd = new SqlCommand("SELECT [ID_Klient], [FamKl] FROM [dbo].[Klient]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable KlientFKZak = new DataTable(); KlientFKZak.Load(SelektKlientFKZakcmd.ExecuteReader()); ID_KlientFKStraf.Items.Clear(); foreach (DataRow Row in KlientFKZak.Rows) { ID_KlientFKStraf.Items.Add(new IDComboBoxItem((int)Row["ID_Klient"], Row["FamKl"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void GetSotrFKSht() { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand SelektSotrFKUchcmd = new SqlCommand("SELECT [ID_Sotr], [Fam_sotr] FROM [dbo].[Sotr]", con); //создание выборки username и pass из таблицы tbl_log con.Open(); //открытие подключения DataTable SotrFKUch = new DataTable(); SotrFKUch.Load(SelektSotrFKUchcmd.ExecuteReader()); ID_SotrFKStraf.Items.Clear(); foreach (DataRow Row in SotrFKUch.Rows) { ID_SotrFKStraf.Items.Add(new IDComboBoxItem((int)Row["ID_Sotr"], Row["Fam_sotr"].ToString())); } } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { // con.Close(); } } private void ID_KlientFKStraf_DropDownOpened(object sender, EventArgs e) { GetKlientFKSht(); } private void ID_SotrFKStraf_DropDownOpened(object sender, EventArgs e) { GetSotrFKSht(); } private void ID_MebelFKStraf_DropDownOpened(object sender, EventArgs e) { GetMebelFKSht(); } private void StrafTbl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (StrafTbl.SelectedItem == null) return; DataRowView row = (DataRowView)StrafTbl.SelectedItem; Summ_Shtraf.Text = row["Summ_str"].ToString(); Usherb.Text = row["Usherb"].ToString(); GetKlientFKSht(); GetSotrFKSht(); GetMebelFKSht(); foreach (IDComboBoxItem item in ID_KlientFKStraf.Items) { if (item.ID == (int)row["ID_Klient"]) { ID_KlientFKStraf.SelectedIndex = ID_KlientFKStraf.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_SotrFKStraf.Items) { if (item.ID == (int)row["ID_Sotr"]) { ID_SotrFKStraf.SelectedIndex = ID_SotrFKStraf.Items.IndexOf(item); } } foreach (IDComboBoxItem item in ID_MebelFKStraf.Items) { if (item.ID == (int)row["ID_Mebel"]) { ID_MebelFKStraf.SelectedIndex = ID_MebelFKStraf.Items.IndexOf(item); } } } private void AddStraf_Click(object sender, RoutedEventArgs e) { try { SqlConnection con = Connector.Connection(DataSource, UserID, Password, InitialCatalog); SqlCommand AddStrafCom = new SqlCommand("[dbo].[AddStraf]", con); //создание выборки username и pass из таблицы tbl_log AddStrafCom.CommandType = CommandType.StoredProcedure; con.Open(); //открытие подключения AddStrafCom.Parameters.AddWithValue("@Summ_str", Summ_Shtraf.Text); AddStrafCom.Parameters.AddWithValue("@Usherb", Usherb.Text); AddStrafCom.Parameters.AddWithValue("@ID_Klient", (int)(ID_KlientFKStraf.SelectedItem as IDComboBoxItem).ID); AddStrafCom.Parameters.AddWithValue("@ID_Sotr", (int)(ID_SotrFKStraf.SelectedItem as IDComboBoxItem).ID); AddStrafCom.Parameters.AddWithValue("@ID_Mebel", (int)(ID_MebelFKStraf.SelectedItem as IDComboBoxItem).ID); AddStrafCom.ExecuteNonQuery(); } catch (Exception ex) //показываем ошибку { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButton.OK); //выводим сообщение с ошибкой } finally { //con.Close(); } otrisOfic(); } } }