text
stringlengths
13
6.01M
using UnityEngine; public class Instancing : MonoBehaviour { const float BATCH_MAX_FLOAT = 1023f; const int BATCH_MAX = 1023; public GameObject prefab; public Material meshMaterial; public int width; public int depth; public float spacing; private MeshFilter mMeshFilter; private MeshRenderer mMeshRenderer; private Matrix4x4[] matrices; void Start () { mMeshFilter = prefab.GetComponent<MeshFilter>(); mMeshRenderer = prefab.GetComponent<MeshRenderer>(); InitData(); } private void InitData() { int count = width * depth; matrices = new Matrix4x4[count]; Vector3 pos = new Vector3(); Vector3 scale = new Vector3(1, 1, 1); for (int i = 0; i < width; ++i) { for (int j = 0; j < depth; ++j) { int idx = i * depth + j; matrices[idx] = Matrix4x4.identity; pos.x = i * spacing; pos.y = 0; pos.z = j * spacing; matrices[idx].SetTRS(pos, Quaternion.identity, scale); } } } void Update () { int total = width * depth; int batches = Mathf.CeilToInt(total / BATCH_MAX_FLOAT); for (int i = 0; i < batches; ++i) { int batchCount = Mathf.Min(BATCH_MAX, total - (BATCH_MAX * i)); int start = Mathf.Max(0, (i - 1) * BATCH_MAX); Matrix4x4[] batchedMatrices = GetBatchedMatrices(start, batchCount); Graphics.DrawMeshInstanced(mMeshFilter.sharedMesh, 0, meshMaterial, batchedMatrices, batchCount); } } private Matrix4x4[] GetBatchedMatrices(int offset, int batchCount) { Matrix4x4[] batchedMatrices = new Matrix4x4[batchCount]; for(int i = 0; i < batchCount; ++i) { batchedMatrices[i] = matrices[i + offset]; } return batchedMatrices; } }
#if !UNITY_2018_3_OR_NEWER using System; using System.Reflection; using UnityEditor; namespace PumpEditor { public static class ProjectSettingsTypeHelper { private static Type inputManagerType; private static Type tagManagerType; private static Type audioManagerType; private static Type timeManagerType; private static Type playerSettingsType; private static Type physicsManagerType; private static Type physics2DSettingsType; private static Type qualitySettingsType; private static Type graphicsSettingsType; private static Type networkManagerType; private static Type editorSettingsType; private static Type monoManagerType; private static Type presetManagerType; static ProjectSettingsTypeHelper() { var editorAssembly = Assembly.GetAssembly(typeof(EditorWindow)); var engineAssembly = Assembly.GetAssembly(typeof(UnityEngine.Object)); inputManagerType = editorAssembly.GetType("UnityEditor.InputManager"); tagManagerType = editorAssembly.GetType("UnityEditor.TagManager"); audioManagerType = editorAssembly.GetType("UnityEditor.AudioManager"); timeManagerType = editorAssembly.GetType("UnityEditor.TimeManager"); playerSettingsType = editorAssembly.GetType("UnityEditor.PlayerSettings"); physicsManagerType = editorAssembly.GetType("UnityEditor.PhysicsManager"); physics2DSettingsType = editorAssembly.GetType("UnityEditor.Physics2DSettings"); qualitySettingsType = engineAssembly.GetType("UnityEngine.QualitySettings"); graphicsSettingsType = engineAssembly.GetType("UnityEngine.Rendering.GraphicsSettings"); // Failed to find full type name for object used in // network manager project settings. Though debugger // shows UnityEngine.NetworkManager type value, getting // it from engine assembly returns null. Using plain // UnityEngine.Object is dangerous for other objects // like network manager settings one as IsProjectSettingsType // will return true for such objects. networkManagerType = typeof(UnityEngine.Object); editorSettingsType = editorAssembly.GetType("UnityEditor.EditorSettings"); monoManagerType = editorAssembly.GetType("UnityEditor.MonoManager"); presetManagerType = editorAssembly.GetType("UnityEditor.Presets.PresetManager"); } public static bool IsProjectSettingsType(UnityEngine.Object obj) { var objType = obj.GetType(); return objType == inputManagerType || objType == tagManagerType || objType == audioManagerType || objType == timeManagerType || objType == playerSettingsType || objType == physicsManagerType || objType == physics2DSettingsType || objType == qualitySettingsType || objType == graphicsSettingsType || objType == networkManagerType || objType == editorSettingsType || objType == monoManagerType || objType == presetManagerType; } // Ideal solution would be getting title via // ProjectSettingsBaseEditor's targetTitle property. public static string GetProjectSettingsTargetTitle(UnityEngine.Object obj) { var objType = obj.GetType(); if (objType == inputManagerType) { return "InputManager"; } else if (objType == tagManagerType) { return "Tags & Layers"; } else if (objType == audioManagerType) { return "AudioManager"; } else if (objType == timeManagerType) { return "TimeManager"; } else if (objType == playerSettingsType) { return "PlayerSettings"; } else if (objType == physicsManagerType) { return "PhysicsManager"; } else if (objType == physics2DSettingsType) { return "Physics2DSettings"; } else if (objType == qualitySettingsType) { return "QualitySettings"; } else if (objType == graphicsSettingsType) { return "GraphicsSettings"; } else if (objType == networkManagerType) { return "NetworkManager"; } else if (objType == editorSettingsType) { return "Editor Settings"; } else if (objType == monoManagerType) { return "Script Execution Order"; } else if (objType == presetManagerType) { return "PresetManager"; } return null; } } } #endif
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; namespace CleanArchitecture.Infra.Dados.Contextos { public class AplicacaoBDContextoFabrica : IDesignTimeDbContextFactory<AplicacaoBDContexto> { /* * Vamos ter que criar o AplicacaoDbContexto em tempo de projeto para gerar as migrações. Para isso, * implementamos a interface IDesignTimeDbContextFactory<TContext>, pois, por convenção, se uma * classe que implementa esta interface for encontrada no mesmo projeto que o DbContext ou no * projeto de inicialização do aplicativo, as ferramentas contornam as outras maneiras de criar o * DbContext e usam a fábrica em tempo de projeto no seu lugar. */ public AplicacaoBDContexto CreateDbContext(string[] args) { IConfiguration configuration = new ConfigurationBuilder() .AddUserSecrets("3d6b4c3d-cbec-4ff6-a303-a8575892d9da") .Build(); var optionsBuilder = new DbContextOptionsBuilder<AplicacaoBDContexto>(); optionsBuilder.UseMySql(configuration.GetConnectionString("CleanArchitecture")); return new AplicacaoBDContexto(optionsBuilder.Options); } } }
using System.IO; using System.Web; using System.Web.Mvc; namespace GIFU.Controllers { public class UploadController : Controller { private Tools.AttachmentHandler attachmentHandler = new Tools.AttachmentHandler(); // GET: Upload public ActionResult Index() { return View(); } [HttpPost] public ActionResult Upload(HttpPostedFileBase file, FormCollection forms) { if (file != null) { if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName); var path = attachmentHandler.GetFolderPath(Server.MapPath("~/FileUploads"), "123"); path = Path.Combine(path, fileName); file.SaveAs(path); } } return RedirectToAction("Index"); } } }
using System; using System.Windows; using MainTool.WPF; namespace MainTool.ViewModels { public class CustomMessageBoxViewModel : BindableBase { public event EventHandler WindowDrag; public CustomMessageBoxViewModel(string title, string message) { WindowTitle = title; Message = message; WindowDragCommand = new DelegateCommand(WindowDragAction); WindowMaximizeCommand = new DelegateCommand(WindowMaximizeAction); } public string WindowTitle { get; } public string Message { get; } public WindowState WindowState { get => windowState; set { windowState = value; RaisePropertyChanged(nameof(WindowState)); } } public SizeToContent WindowSizeToContent { get => windowSizeToContent; set { windowSizeToContent = value; RaisePropertyChanged(nameof(WindowSizeToContent)); } } public DelegateCommand WindowDragCommand { get; } public DelegateCommand WindowMaximizeCommand { get; } private void WindowDragAction() { WindowDrag?.Invoke(this, null); } private void WindowMaximizeAction() { if (WindowSizeToContent != SizeToContent.Manual) { WindowSizeToContent = SizeToContent.Manual; } WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; } private WindowState windowState = WindowState.Normal; private SizeToContent windowSizeToContent = SizeToContent.WidthAndHeight; } }
using System; using System.Collections.Generic; using System.Linq; namespace CursoCsharp.TopicosAvancados { public class Aluno { public string Nome; public int Idade; public double Nota; } class LINQ01 { public static void Executar() { var alunos = new List<Aluno> { new Aluno() {Nome = "Pedro", Idade = 22, Nota = 8.1}, new Aluno() {Nome = "Henrique", Idade = 21, Nota = 6.1}, new Aluno() {Nome = "Ana", Idade = 23, Nota = 9.4}, new Aluno() {Nome = "Nathalia", Idade = 22, Nota = 9.8}, new Aluno() {Nome = "Nancy", Idade = 17, Nota = 7.7}, new Aluno() {Nome = "Ivan", Idade = 29, Nota = 4.8}, new Aluno() {Nome = "Gabriel", Idade = 20, Nota = 3.1}, new Aluno() {Nome = "Fernanda", Idade = 25, Nota = 6.5} }; Console.WriteLine("Aprovados acima de 5"); var aprovados = alunos.Where(a => a.Nota >= 5).OrderBy(a => a.Nome); foreach (var aluno in aprovados) { Console.WriteLine(aluno.Nome); } Console.WriteLine("Aprovado acima de 8"); var aprovado = alunos.Where(a => a.Nota >= 8); foreach (var aluno in aprovado) { Console.WriteLine(aluno.Nota); } Console.WriteLine("\n Chamada de alunos"); var chamada = alunos.OrderBy(a => a.Nome).Select(a => a.Nome); foreach (var aluno in chamada) { Console.WriteLine(aluno); } Console.WriteLine("\nAprovado (por idade)"); var alunosAprovados = from aluno in alunos where aluno.Nota >= 7 orderby aluno.Idade select aluno.Nome; foreach(var aluno in alunosAprovados) { Console.WriteLine(aluno); } } } }
using System; using System.Collections.Generic; using KellermanSoftware.CompareNetObjects; using NHibernate.Envers; using NHibernate.Envers.Query; using Profiling2.Domain.Contracts.Queries.Audit; using Profiling2.Domain.Prf.Careers; using Profiling2.Domain.Prf.Persons; namespace Profiling2.Infrastructure.Queries.Audit { public class CareerRevisionsQuery : NHibernateAuditQuery, IPersonAuditable<Career>, IHistoricalCareerQuery { public new CompareLogic CompareLogic { get { // For some reason using ElementsToInclude won't compare child attributes past the first level. //this._compareObjects.ElementsToInclude = new List<string>() { // "Career", "Organization", "Location", "Rank", "Role", "Function", "Unit", "Job", // "DayOfStart", "MonthOfStart", "YearOfStart", "DayOfEnd", "MonthOfEnd", "YearOfEnd", // "Commentary", "Archive", "Notes", "DayAsOf", "MonthAsOf", "YearAsOf", // "IsCurrentCareer", "Defected", "Acting" //}; //this._compareObjects.ShowBreadcrumb = true; base.CompareLogic.Config.MembersToIgnore.AddRange(new List<string>() { "Id", "Person", "AdminCareerImports", // Career "Careers", "OrganizationResponsibilities", "OrganizationRelationshipsAsSubject", "OrganizationRelationshipsAsObject", "OrganizationAliases", "UnitHierarchies", "OrganizationPhotos", // Organization "Events", // Location "AdminUnitImports", "UnitHierarchyChildren" // Unit }); return base.CompareLogic; } } public IList<object[]> GetRawRevisions(Person person) { return AuditReaderFactory.Get(Session).CreateQuery() .ForRevisionsOfEntity(typeof(Career), false, true) .Add(AuditEntity.Property("Person").Eq(person)) // don't process audit changes before baseline entities were initialised; some career.organization and career.unit // fields return as proxies and throw 'object not found' exceptions. .Add(AuditEntity.RevisionNumber().Ge(100)) .GetResultList<object[]>(); } public IList<Career> GetCareers(Person person, DateTime date) { return AuditReaderFactory.Get(Session).CreateQuery() .ForEntitiesAtRevision(typeof(Career), GetRevisionNumberForDate(date)) .Add(AuditEntity.Property("Person").Eq(person)) .GetResultList<Career>(); } public int GetCareerCount(DateTime date) { int revision = this.GetRevisionNumberForDate(date); return AuditReaderFactory.Get(Session).CreateQuery() .ForEntitiesAtRevision(typeof(Career), Convert.ToInt64(revision)) .Add(AuditEntity.Property("Archive").Eq(false)) .GetResultList().Count; } } }
using DB_CQRS.Shared.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; namespace DB_CQRS.DB.Driver.EntityFramework.Configuration { public class OrderConfiguration : IEntityTypeConfiguration<Order> { private const string TABLE_NAME = "Order"; public void Configure(EntityTypeBuilder<Order> builder) { builder.ToTable(TABLE_NAME); builder.HasData(new List<Order> { new Order { OrderId = Guid.NewGuid() } }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using DataAccess; using DataAccess.Entities; using Microsoft.AspNetCore.Identity; using Models; using Repository; using Models.ViewModels; namespace UI.Controllers { public class OrganisationItemController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly ApplicationDbContext _context; private OrganisationItemDTO OrgItemDTO = new OrganisationItemDTO(); public OrganisationItemController(ApplicationDbContext context, UserManager<ApplicationUser> userManager) { _context = context; _userManager = userManager; } // GET: OrganisationItem public async Task<IActionResult> Index(Guid id ) { UnitofWork _uofw = new UnitofWork(_context, _userManager.GetUserAsync(User).Result); var result = _uofw.Organisations.GetOrganisationbyIdandItems(id); return View(OrgItemDTO.ToIndexModel(result)); } // GET: OrganisationItem/Details/5 public async Task<IActionResult> Details(Guid? id) { if (id == null) { return NotFound(); } var result = await _context.OrganisationItems.FirstOrDefaultAsync(m => m.ID == id); if (result == null) { return NotFound(); } return View(OrgItemDTO.ToViewModel(result)); } // GET: OrganisationItem/Create public IActionResult Create(string Id) { OrganisationItemViewModel Item = new OrganisationItemViewModel(); Item.OrganisationId = Id; Item.Brand = ""; Item.Code = ""; Item.Description = ""; Item.Name = ""; Item.Price = ""; Item.RowVersionNo = ""; Item.TaxRate = ""; return View(Item); } // POST: OrganisationItem/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Name,Brand,Code,Description,Price,TaxRate,ID,RowVersionNo,OrganisationId")] OrganisationItemViewModel Item) { if (ModelState.IsValid) { Item.Id = Guid.NewGuid().ToString(); var result = OrgItemDTO.ToTableModel(Item); result.TblOrganisationId = Guid.Parse(Item.OrganisationId); _context.Add(result); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index), new { id = Item.OrganisationId }); } return View(Item); } // GET: OrganisationItem/Edit/5 public async Task<IActionResult> Edit(Guid? id) { if (id == null) { return NotFound(); } var tblOrganisationItem = await _context.OrganisationItems.FindAsync(id); if (tblOrganisationItem == null) { return NotFound(); } var result = OrgItemDTO.ToViewModel(tblOrganisationItem); return View(result); } // POST: OrganisationItem/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(Guid id, [Bind("Name,Brand,Code,Description,Price,TaxRate,RowVersionNo,OrganisationId")] OrganisationItemViewModel Item) { if (id == null) { return NotFound(); } if (ModelState.IsValid) { try { var result = _context.OrganisationItems.Find(id); OrgItemDTO.ToTableModel(result, Item); _context.Update(result); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { return NotFound(); } return RedirectToAction(nameof(Index), new {id = Item.OrganisationId }); } return View(Item); } // GET: OrganisationItem/Delete/5 public async Task<IActionResult> Delete(Guid? id) { if (id == null) { return NotFound(); } var result = await _context.OrganisationItems.FirstOrDefaultAsync(m => m.ID == id); if (result == null) { return NotFound(); } return View(OrgItemDTO.ToViewModel(result)); } // POST: OrganisationItem/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(Guid id) { var result = await _context.OrganisationItems.FindAsync(id); _context.OrganisationItems.Remove(result); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index), new { id = result.TblOrganisationId }); } private bool TblOrganisationItemExists(Guid id) { return _context.OrganisationItems.Any(e => e.ID == id); } } }
namespace Funding.Web.Areas.Admin.Controllers { using Funding.Common.Constants; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; [Area(Area.Admin)] [Authorize(Roles = Roles.Admin)] public class BaseController : Controller { } }
using System.Runtime.InteropServices; namespace ProcessTree.Models { internal static class NativeMethods { private const string DllName = @"..\..\..\Debug\NativeLibrary.dll"; [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern void MakeSnapshot(); [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] public static extern int ParentProcessId(int processId); } }
namespace WinAppDriver.Modern { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation; using System.Runtime.InteropServices; using System.Xml; [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1201:ElementsMustAppearInTheCorrectOrder", Justification = "Reviewed.")] internal class StoreApp : IStoreApp { private static ILogger logger = Logger.GetLogger("WinAppDriver"); private IDriverContext context; private Capabilities capabilities; private AppInfo infoCache; private IPackageInstaller installerCache; private IUtils utils; public StoreApp(IDriverContext context, Capabilities capabilities, IUtils utils) { // TODO verify capabilities this.context = context; this.capabilities = capabilities; this.utils = utils; } public string DriverAppID { get { return this.PackageName + " (Modern)"; } } public Capabilities Capabilities { get { return this.capabilities; } } public string StatesDir { get { return Path.Combine(this.context.GetAppWorkingDir(this), "States"); } } public IPackageInstaller Installer { get { if (this.installerCache == null) { this.installerCache = new StoreAppInstaller(this.context, this, this.utils); } return this.installerCache; } } public string PackageName { get { return this.capabilities.PackageName; } } public string AppUserModelId { get { return this.GetInstalledAppInfo().AppUserModelId; } } public string PackageFamilyName { get { return this.GetInstalledAppInfo().PackageFamilyName; } } public string PackageFullName { get { return this.GetInstalledAppInfo().PackageFullName; } } public string PackageFolderDir { get { return this.utils.ExpandEnvironmentVariables(@"%LOCALAPPDATA%\Packages\" + this.PackageFamilyName); } } public void Uninstall() { PowerShell ps = PowerShell.Create(); ps.AddCommand("Remove-AppxPackage"); ps.AddArgument(this.PackageFullName); ps.Invoke(); this.utils.DeleteDirectoryIfExists(this.StatesDir); } public bool IsInstalled() { if (this.infoCache != null) { return true; } else { return this.TryGetInstalledAppInfo(out this.infoCache); } } public void Activate() { logger.Info( "Activate the store app; current working directory = [{0}], " + "AppUserModelID = [{1}].", Environment.CurrentDirectory, this.AppUserModelId); var info = new ProcessStartInfo( Path.Combine(Environment.CurrentDirectory, "ActivateStoreApp.exe"), this.AppUserModelId); info.UseShellExecute = false; info.RedirectStandardOutput = true; info.RedirectStandardError = true; var process = Process.Start(info); logger.Debug("PID of ActivateStoreApp.exe = {0}.", process.Id); process.WaitForExit(); if (process.ExitCode == 0) { logger.Debug("STDOUT = [{0}].", process.StandardOutput.ReadToEnd()); } else { string msg = string.Format( "Error occurred while activating the store app; " + "code = {0}, STDOUT = [{1}], STDERR = [{2}].", process.ExitCode, process.StandardOutput.ReadToEnd(), process.StandardError.ReadToEnd()); throw new WinAppDriverException(msg); } } public void Terminate() { var api = (IPackageDebugSettings)new PackageDebugSettings(); api.TerminateAllProcesses(this.PackageFullName); } public bool BackupInitialStates(bool overwrite) { if (this.utils.DirectoryExists(this.StatesDir) && !overwrite) { return false; } if (overwrite) { this.utils.DeleteDirectoryIfExists(this.StatesDir); } this.utils.CopyDirectoryAndSecurity(this.PackageFolderDir, this.StatesDir); return true; } public void RestoreInitialStates() { var src = Path.Combine(this.StatesDir, Path.GetFileName(this.PackageFolderDir)); this.utils.CopyDirectoryAndSecurity(src, Path.GetDirectoryName(this.PackageFolderDir)); } private AppInfo GetInstalledAppInfo() { if (this.infoCache != null) { return this.infoCache; } if (this.TryGetInstalledAppInfo(out this.infoCache)) { return this.infoCache; } else { throw new InvalidOperationException(string.Format( "The package '{0}' is not installed yet.", this.PackageName)); } } private bool TryGetInstalledAppInfo(out AppInfo info) { string packageName, version, packageFamilyName, packageFullName, appUserModelId; using (var ps = PowerShell.Create()) { var results = ps.AddCommand("Get-AppxPackage").AddParameter("Name", this.PackageName).Invoke(); if (results.Count == 0) { info = null; return false; } var properties = results[0].Properties; packageName = (string)properties["Name"].Value; // normal version = (string)properties["Version"].Value; packageFamilyName = (string)properties["PackageFamilyName"].Value; packageFullName = (string)properties["PackageFullName"].Value; } using (var ps = PowerShell.Create()) { var manifest = ps.AddCommand("Get-AppxPackageManifest").AddParameter("Package", packageFullName).Invoke()[0]; var root = (XmlElement)manifest.Properties["Package"].Value; string appID = root["Applications"]["Application"].GetAttribute("Id"); appUserModelId = packageFamilyName + "!" + appID; } info = new AppInfo { PackageName = packageName, Version = version, PackageFamilyName = packageFamilyName, PackageFullName = packageFullName, AppUserModelId = appUserModelId }; return true; } private class AppInfo { public string PackageName { get; set; } public string Version { get; set; } public string PackageFamilyName { get; set; } public string PackageFullName { get; set; } public string AppUserModelId { get; set; } } [ComImport, Guid("B1AEC16F-2383-4852-B0E9-8F0B1DC66B4D")] private class PackageDebugSettings { } private enum PACKAGE_EXECUTION_STATE { PES_UNKNOWN, PES_RUNNING, PES_SUSPENDING, PES_SUSPENDED, PES_TERMINATED } [ComImport, Guid("F27C3930-8029-4AD1-94E3-3DBA417810C1")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Reviewed.")] private interface IPackageDebugSettings { int EnableDebugging( [MarshalAs(UnmanagedType.LPWStr)] string packageFullName, [MarshalAs(UnmanagedType.LPWStr)] string debuggerCommandLine, IntPtr environment); int DisableDebugging([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int Suspend([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int Resume([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int TerminateAllProcesses([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int SetTargetSessionId(int sessionId); int EnumerageBackgroundTasks( [MarshalAs(UnmanagedType.LPWStr)] string packageFullName, out uint taskCount, out int intPtr, [Out] string[] array); int ActivateBackgroundTask(IntPtr something); int StartServicing([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int StopServicing([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int StartSessionRedirection( [MarshalAs(UnmanagedType.LPWStr)] string packageFullName, uint sessionId); int StopSessionRedirection([MarshalAs(UnmanagedType.LPWStr)] string packageFullName); int GetPackageExecutionState( [MarshalAs(UnmanagedType.LPWStr)] string packageFullName, out PACKAGE_EXECUTION_STATE packageExecutionState); int RegisterForPackageStateChanges( [MarshalAs(UnmanagedType.LPWStr)] string packageFullName, IntPtr pPackageExecutionStateChangeNotification, out uint pdwCookie); int UnregisterForPackageStateChanges(uint dwCookie); } } }
using Alabo.App.Share.OpenTasks.Base; using Alabo.App.Share.OpenTasks.Modules; using Alabo.Data.People.Users.Domain.Services; using Alabo.Data.Things.Orders.Extensions; using Alabo.Data.Things.Orders.ResultModel; using Alabo.Domains.Enums; using Alabo.Extensions; using Alabo.Framework.Tasks.Queues.Models; using Alabo.Framework.Tasks.Schedules.Domain.Enums; using Alabo.Users.Dtos; using Alabo.Web.Mvc.Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using ZKCloud.Open.ApiBase.Models; namespace Alabo.App.Share.OpenTasks.Configs.UserRecommendedRelationship { /// <summary> /// 直推与管理收益 /// </summary> /// <seealso cref="ShareBaseConfig" /> [ClassProperty] public class RecommendedAndManagementConfig : ShareBaseConfig { /// <summary> /// 团队层数 /// </summary> [Field(ControlsType = ControlsType.TextBox, ListShow = true, EditShow = true, SortOrder = 1)] [Display(Name = "团队层数", Description = "团队层数")] public long TeamLevel { get; set; } = 100; /// <summary> /// 分润比例 /// </summary> [Field(ControlsType = ControlsType.TextBox, ListShow = true, EditShow = true, SortOrder = 1)] [Display(Name = "管理收益比例", Description = "管理收益比例,0.5表示50%")] public decimal ManagerRatio { get; set; } = 0.5m; } /// <summary> /// Class NLevelDistributionModule. /// </summary> [TaskModule(Id, ModelName, SortOrder = 999999, ConfigurationType = typeof(RecommendedAndManagementConfig), IsSupportMultipleConfiguration = true, FenRunResultType = FenRunResultType.Price, Intro = "直推与管理收益,比如A推荐了B,B推荐了C。C消费,B获得直推奖,A获得B直推奖的管理奖", RelationshipType = RelationshipType.UserRecommendedRelationship)] public class RecommendedAndManagementModule : AssetAllocationShareModuleBase<RecommendedAndManagementConfig> { /// <summary> /// The identifier /// </summary> public const string Id = "BD717F0D-AD00-4009-9005-597E0AE55000"; /// <summary> /// The model name /// </summary> public const string ModelName = "直推与管理收益"; // /// <summary> /// Initializes a new instance of the <see cref="NLevelDistributionModule" /> class. /// </summary> /// <param name="context">上下文</param> /// <param name="config">The configuration.</param> public RecommendedAndManagementModule(TaskContext context, RecommendedAndManagementConfig config) : base(context, config) { } /// <summary> /// 开始执行分润 /// 对module配置与参数进行基础验证,子类重写后需要显式调用并判定返回值,如返回值不为Success,则不再执行子类后续逻辑 /// </summary> /// <param name="parameter">参数</param> /// <returns>ExecuteResult&lt;ITaskResult[]&gt;.</returns> public override ExecuteResult<ITaskResult[]> Execute(TaskParameter parameter) { var baseResult = base.Execute(parameter); if (baseResult.Status != ResultStatus.Success) { return baseResult; } IList<ITaskResult> resultList = new List<ITaskResult>(); // 开始计算直推奖 //当前下单用户 var user = Resolve<IUserService>().GetSingle(ShareOrder.UserId); base.GetShareUser(user.ParentId, out var shareUser); //从基类获取分润用户 if (shareUser == null) { return ExecuteResult<ITaskResult[]>.Cancel("推荐用户不存在"); } var ratio = Convert.ToDecimal(Ratios[0]); var shareAmount = BaseFenRunAmount * ratio; //分润金额 CreateResultList(shareAmount, ShareOrderUser, shareUser, parameter, Configuration, resultList); //构建分润参数 // 开始计算管理分红 var userMap = Resolve<IUserMapService>().GetParentMapFromCache(shareUser.Id); var map = userMap.ParentMap.DeserializeJson<List<ParentMap>>(); if (map == null) { return ExecuteResult<ITaskResult[]>.Cancel("未找到触发会员的Parent Map."); } for (var i = 0; i < map.Count; i++) { // 如果大于团队层数 if (i + 1 > Configuration.TeamLevel) { break; } var item = map[i]; GetShareUser(item.UserId, out shareUser); //从基类获取分润用户 if (shareUser == null) { continue; } // 每上一级50% var itemRatio = Math.Pow(Convert.ToDouble(Configuration.ManagerRatio), Convert.ToDouble(i + 1)) .ToDecimal() * ratio; if (itemRatio <= 0) { continue; } shareAmount = BaseFenRunAmount * itemRatio; //分润金额 CreateResultList(shareAmount, ShareOrderUser, shareUser, parameter, Configuration, resultList); //构建分润参数 } return ExecuteResult<ITaskResult[]>.Success(resultList.ToArray()); } } }
namespace SoftUniStore.Services { using System.Linq; using Contracts; using Data.Common.Repositories; using Data.Models; using SimpleHttpServer.Models; using SimpleHttpServer.Utilities; public class AuthorizationService : IAuthorizationService { private readonly IRepository<Login> logins; public AuthorizationService(IRepository<Login> logins) { this.logins = logins; } public bool IsAuthenticatedUser(HttpSession session) { if (session == null) { return false; } var sess = this.logins .All() .FirstOrDefault(s => s.SessionId == session.Id && s.IsActive); return sess != null; } public User GetCurrentUser(HttpSession session) { var user = this.logins .All() .Where(l => l.SessionId == session.Id) .Select(l => l.User) .FirstOrDefault(); return user; } public string Logout(HttpSession session, HttpResponse response) { var login = this.logins .All() .FirstOrDefault(s => s.SessionId == session.Id && s.IsActive); login.IsActive = false; this.logins.SaveChanges(); this.ChangeBrowserSession(response); return "/store/login"; } public void ChangeBrowserSession(HttpResponse response) { var newSession = SessionCreator.Create().Id + "; HttpOnly; path=/"; response.Header.Cookies.Add(new Cookie("sessionId", newSession)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.ComponentModel.Design; namespace IRAP_UFMPS.UserControls { [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] public partial class UCWatchTypeNormal : UserControl { public UCWatchTypeNormal() { InitializeComponent(); } private void chkNormalKeepUndealFile_CheckedChanged(object sender, EventArgs e) { edtNormalKeepUndealFileFolder.Enabled = chkNormalKeepUndealFile.Checked; } private void edtNormalKeepUndealFileFolder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { edtNormalKeepUndealFileFolder.Text = Comm.Tools.SelectFolder( "请选择保存不处理文件的文件夹:", edtNormalKeepUndealFileFolder.Text); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Npgsql; namespace FormularioBDD2102A_106 { public partial class InicioSesion : Form { Formulario102A formulario; NpgsqlConnection conn; public InicioSesion() { InitializeComponent(); formulario = new Formulario102A(); conn = new NpgsqlConnection("Server = localhost; User Id = postgres; Password = kjsg19980501; Database = postgres"); } private string sql = null; private void button1_Click(object sender, EventArgs e) { } private void btnInicioS_Click(object sender, EventArgs e) { try { conn.Open(); sql = "select * from public.user where name_user = '" + txtusuario.Text + "' and pwd_user = '" + txtPwd.Text + "'"; NpgsqlCommand cmd = new NpgsqlCommand(sql, conn); NpgsqlDataReader dr = cmd.ExecuteReader(); if(dr.Read()) { formulario.Show(); this.Hide(); conn.Close(); } else { MessageBox.Show("Verifcar usuaio o contraseña"); conn.Close(); } } catch (Exception error) { MessageBox.Show("Error" + error); conn.Close(); } } } }
/*--------------------------------------------------------------------------------------- -- SOURCE FILE: Server.cs -- -- PROGRAM: server -- -- FUNCTIONS: -- public static void Main() -- public static void pregame() -- public static void startGame() -- private static bool isTick() -- private static void gameThreadFunction() -- private static void sendThreadFunction() -- private static byte generateTickPacketHeader(bool hasPlayer, bool hasBullet, bool hasWeapon, int players) -- private static void updateHealthPacket(Player player, byte[] snapshot) -- private static void buildSendPacket() -- private static void recvThreadFunction() -- private static void handleBuffer(byte[] inBuffer, EndPoint ep) -- private static void updateExistingPlayer(ref byte[] inBuffer) -- private static void handleIncomingBullet(byte playerId, int bulletId, byte bulletType) -- private static void handleIncomingWeapon(byte playerId, int weaponId, byte weaponType) -- private static void addNewPlayer(EndPoint ep) -- private static void sendInitPacket(Player newPlayer) -- private static void initTCPServer() -- private static void generateInitData() -- private static void listenThreadFunc() -- private static void transmitThreadFunc(object clientsockfd) -- -- DATE: Feb 18, 2018 -- -- REVISIONS: Mar 18, 2018 - Created separate repo for server -- Mar 30, 2018 - Moved the server off unity to a seperate script -- Apr 2, 2018 - Added bullet handling -- Apr 11, 2018 - Merged in danger zone -- -- DESIGNERS: Benny Wang, Tim Bruecker, Haley Booker, Alfred Swinton -- -- PROGRAMMER: Benny Wang, Tim Bruecker, Haley Booker, Alfred Swinton -- -- NOTES: -- This is the csharp class to start the server. It waits for a maximum of 30 players. -- After 30 seconds of running the game will be initiated if a minimum of 2 players have joined. -- The server keeps track of all players, bullets and weapons in the game. It sends the -- information of the players inventory, health and the other players coordinates to each player. ---------------------------------------------------------------------------------------*/ using System; using System.Collections; using System.Collections.Generic; using System.Threading; using Networking; using InitGuns; class Server { private static DateTime nextTick = DateTime.Now; private static Thread sendThread; private static Thread recvThread; private static Thread gameThread; private static bool running; private static Mutex mutex; private static Networking.Server server; private static byte[] sendBuffer = new byte[R.Net.Size.SERVER_TICK]; private static bool overtime = false; private static Random random = new Random(); private static byte nextPlayerId = 1; private static Dictionary<byte, Player> players; private static HashSet<byte> deadPlayers = new HashSet<byte>(); private static Stack<Bullet> newBullets = new Stack<Bullet>(); private static Dictionary<int, Bullet> bullets = new Dictionary<int, Bullet>(); private static Stack<Tuple<byte, int>> weaponSwapEvents = new Stack<Tuple<byte, int>>(); private static TerrainController tc = new TerrainController(); // Game generation variables private static Int32[] clientSockFdArr = new Int32[R.Net.MAX_PLAYERS]; private static Thread[] transmitThreadArr = new Thread[R.Net.MAX_PLAYERS]; private static Thread listenThread; private static byte[] itemData = new byte[R.Net.TCP_BUFFER_SIZE]; private static byte[] mapData = new byte[R.Net.TCP_BUFFER_SIZE]; private static Int32 numClients = 0; private static bool accepting = false; private static TCPServer tcpServer; private static DangerZone dangerZone; private static SpawnPointGenerator spawnPointGenerator = new SpawnPointGenerator(); /*------------------------------------------------------------------------------------------------- -- FUNCTION: Main() -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: public static void Main() -- -- RETURNS: void -- -- NOTES: -- The starting point of the server. Sets up the pregame and starts the game. -------------------------------------------------------------------------------------------------*/ public static void Main() { Console.WriteLine("Starting server"); mutex = new Mutex(); pregame(); startGame(); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: pregame -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: public static void pregame() -- -- RETURNS: void -- -- NOTES: -- Creates everything needed before the game can start. -------------------------------------------------------------------------------------------------*/ public static void pregame() { players = new Dictionary<byte, Player>(); initTCPServer(); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: startGame -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Haley Booker -- -- INTERFACE: public static void startGame() -- -- RETURNS: void -- -- NOTES: -- Starts the threads for the game. -------------------------------------------------------------------------------------------------*/ public static void startGame() { server = new Networking.Server(); server.Init(R.Net.PORT); sendThread = new Thread(sendThreadFunction); recvThread = new Thread(recvThreadFunction); gameThread = new Thread(gameThreadFunction); mutex.WaitOne(); running = true; mutex.ReleaseMutex(); sendThread.Start(); recvThread.Start(); gameThread.Start(); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: isTick -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: public static void isTick() -- -- RETURNS: Returns true if time has elapsed. Else it returns false -- -- NOTES: -- Checks if a new tick has occurred. It’s used to update the send thread. -------------------------------------------------------------------------------------------------*/ private static bool isTick() { if (DateTime.Now > nextTick) { nextTick = DateTime.Now.AddMilliseconds(R.Game.TICK_INTERVAL); return true; } return false; } /*------------------------------------------------------------------------------------------------- -- FUNCTION: gameThreadFunction -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Tim Bruecker, Haley Booker -- -- INTERFACE: private static void gameThreadFunction() -- -- RETURNS: void -- -- NOTES: -- Updates the the players based on collisions and the danger zone. The systems handles -- players outside the danger zone, collisions between bullets and players and expired bullets. -------------------------------------------------------------------------------------------------*/ private static void gameThreadFunction() { try { while (running) { if (isTick()) { dangerZone.Update(); Dictionary<int, int> bulletIds = new Dictionary<int, int>(); mutex.WaitOne(); foreach (KeyValuePair<int, Bullet> bullet in bullets) { if (tc.IsOccupied(bullet.Value)) { bulletIds[bullet.Key] = bullet.Key; } } mutex.ReleaseMutex(); mutex.WaitOne(); foreach (KeyValuePair<byte, Player> player in players) { dangerZone.HandlePlayer(player.Value); } mutex.ReleaseMutex(); // Loop through players foreach (KeyValuePair<byte, Player> player in players) { // Loop through bullets mutex.WaitOne(); foreach(KeyValuePair<int, Bullet> bullet in bullets) { // If bullet collides if (bullet.Value.PlayerId == player.Value.id) { continue; } if (bullet.Value.IsColliding(player.Value.x, player.Value.z, R.Game.Players.RADIUS)) { // Subtract health if (player.Value.h < bullet.Value.Damage) { player.Value.h = 0; } else { player.Value.TakeDamage(bullet.Value.Damage); } // Signal delete bulletIds[bullet.Key] = bullet.Key; } } mutex.ReleaseMutex(); } mutex.WaitOne(); foreach (KeyValuePair<int, Bullet> pair in bullets) { // Update bullet positions if (!pair.Value.Update()) { // Remove expired bullets bulletIds[pair.Key] = pair.Key; } } mutex.ReleaseMutex(); // Remove bullets mutex.WaitOne(); foreach (KeyValuePair<int, int> pair in bulletIds) { bullets[pair.Key].Event = R.Game.Bullet.REMOVE; newBullets.Push(bullets[pair.Key]); bullets.Remove(pair.Key); } mutex.ReleaseMutex(); } } } catch (Exception e) { LogError("Game Logic Thread Exception"); LogError(e.ToString()); } } /*------------------------------------------------------------------------------------------------- -- FUNCTION: sendThreadFunction -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Tim Bruecker, Haley Booker -- -- INTERFACE: private static void sendThreadFunction() -- -- RETURNS: void -- -- NOTES: -- Sends and packet to each connected player. The system sends each players -- health out after updating it. -------------------------------------------------------------------------------------------------*/ private static void sendThreadFunction() { Console.WriteLine("Starting Sending Thread"); while (running) { try { if (isTick()) { buildSendPacket(); byte[] snapshot = new byte[sendBuffer.Length]; Buffer.BlockCopy(sendBuffer, 0, snapshot, 0, sendBuffer.Length); foreach (KeyValuePair<byte, Player> pair in players) { updateHealthPacket(pair.Value, snapshot); server.Send(pair.Value.ep, snapshot, snapshot.Length); } } } catch (Exception e) { LogError("Send Thread Exception"); LogError(e.ToString()); } } } /*------------------------------------------------------------------------------------------------- -- FUNCTION: generateTickPacketHeader -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: private static byte generateTickPacketHeader(bool hasPlayer, bool hasBullet, bool hasWeapon, int players) -- bool hasPlayer: True if the packet is sending players -- bool hasBullet: True if the packet is sending bullets -- bool hasWeapon: True if the packet is sending weapons -- int players: The number of players in the game -- -- RETURNS: The header byte generated -- -- NOTES: -- Generates a byte for the header based on what it needs to send. The byte value will -- depend on the number of players and whether the packet will have players, bullets and/or -- weapons. -------------------------------------------------------------------------------------------------*/ private static byte generateTickPacketHeader(bool hasPlayer, bool hasBullet, bool hasWeapon, int players) { byte tmp = 0; if (hasPlayer) { tmp += 128; } if (hasBullet) { tmp += 64; } if (hasWeapon) { tmp += 32; } tmp += Convert.ToByte(players); return tmp; } /*------------------------------------------------------------------------------------------------- -- FUNCTION: updateHealthPacket -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker -- -- PROGRAMMER: Benny Wang, Tim Bruecker -- -- INTERFACE: private static void updateHealthPacket(Player player, byte[] snapshot) -- Player player: The player object -- byte[] snapshot: The byte array to be copied to -- -- RETURNS: void -- -- NOTES: -- Takes a players health value and copies it into a byte array. Used to update player’s health -------------------------------------------------------------------------------------------------*/ private static void updateHealthPacket(Player player, byte[] snapshot) { int offset = R.Net.Offset.HEALTH; mutex.WaitOne(); Array.Copy(BitConverter.GetBytes(player.h), 0, snapshot, offset, 1); mutex.ReleaseMutex(); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: buildSendPacket -- -- DATE: Feb 18, 2018 -- -- REVISIONS: Mar 27, 2018 - Refactored offsets for new packets -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Tim Bruecker, Haley Booker -- -- INTERFACE: private static void buildSendPacket() -- -- RETURNS: void -- -- NOTES: -- Builds the send packet with the players ids and coordinates. For any new bullets it adds -- them to the packet.The offset of the bullets is based on which player fired the bullet. If a -- player’s inventory has changed. The weapons on the map will be updated. -------------------------------------------------------------------------------------------------*/ private static void buildSendPacket() { int offset = R.Net.Offset.PLAYERS; int bulletOffset = R.Net.Offset.BULLETS; int weaponOffset = R.Net.Offset.WEAPONS; // Header mutex.WaitOne(); sendBuffer[0] = generateTickPacketHeader(true, newBullets.Count > 0, weaponSwapEvents.Count > 0, players.Count - deadPlayers.Count); // Danger zone Array.Copy(dangerZone.ToBytes(), 0, sendBuffer, R.Net.Offset.DANGER_ZONE, 16); // Player data foreach (KeyValuePair<byte, Player> pair in players) { byte id = pair.Key; Player player = pair.Value; sendBuffer[offset] = id; Array.Copy(BitConverter.GetBytes(player.x), 0, sendBuffer, offset + 1, 4); Array.Copy(BitConverter.GetBytes(player.z), 0, sendBuffer, offset + 5, 4); Array.Copy(BitConverter.GetBytes(player.r), 0, sendBuffer, offset + 9, 4); offset += R.Net.Size.PLAYER_DATA; } mutex.ReleaseMutex(); if (newBullets.Count > 0) { // Bullet data mutex.WaitOne(); sendBuffer[bulletOffset] = Convert.ToByte(newBullets.Count); bulletOffset++; while (newBullets.Count > 0) { Bullet bullet = newBullets.Pop(); if (bullet == null) { continue; } sendBuffer[bulletOffset] = bullet.PlayerId; Array.Copy(BitConverter.GetBytes(bullet.BulletId), 0, sendBuffer, bulletOffset + 1, 4); sendBuffer[bulletOffset + 5] = bullet.Type; if (bullet.Event != R.Game.Bullet.IGNORE) { sendBuffer[bulletOffset + 6] = bullet.Event; } else { LogError("Bullet event is set to ignore"); } bulletOffset += 7; } mutex.ReleaseMutex(); //Console.WriteLine(BitConverter.ToString(sendBuffer)); } if (weaponSwapEvents.Count > 0) { // Weapon swap event mutex.WaitOne(); sendBuffer[weaponOffset] = Convert.ToByte(weaponSwapEvents.Count); weaponOffset++; while (weaponSwapEvents.Count > 0) { Tuple<byte, int> weaponSwap = weaponSwapEvents.Pop(); sendBuffer[weaponOffset] = weaponSwap.Item1; Array.Copy(BitConverter.GetBytes(weaponSwap.Item2), 0, sendBuffer, weaponOffset + 1, 4); weaponOffset += 5; } mutex.ReleaseMutex(); } } /*------------------------------------------------------------------------------------------------- -- FUNCTION: recvThreadFunction -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Tim Bruecker, Haley Booker -- -- INTERFACE: private static void recvThreadFunction() -- -- RETURNS: void -- -- NOTES: -- Receives all incoming data from all clients. Checks to confirm the amount of data -- is accurate. -------------------------------------------------------------------------------------------------*/ private static void recvThreadFunction() { Console.WriteLine("Starting Receive Function"); try { while (running) { // if (isTick()) // { // Receive from up to 30 clients per tick for (int i = 0; i < R.Net.MAX_PLAYERS; i++) { // If there is not data continue if (!server.Poll()) { continue; } // Prepare to receive EndPoint ep = new EndPoint(); byte[] recvBuffer = new byte[R.Net.Size.CLIENT_TICK]; // Receive int n = server.Recv(ref ep, recvBuffer, R.Net.Size.CLIENT_TICK); // If invalid amount of data was received discard and continue if (n != R.Net.Size.CLIENT_TICK) { LogError("Server received an invalid amount of data."); continue; } // Handle incoming data if it is correct handleBuffer(recvBuffer, ep); } // } } } catch (Exception e) { LogError("Receive Thread Exception"); LogError(e.ToString()); } return; } /*------------------------------------------------------------------------------------------------- -- FUNCTION: handleBuffer -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: private static void handleBuffer(byte[] inBuffer, EndPoint ep) -- byte[] inBuffer: The buffer of recieved data -- EndPoint ep: The end point of who sent the data -- -- RETURNS: void -- -- NOTES: -- Checks to see if the data recieved is from a new or existing client. -------------------------------------------------------------------------------------------------*/ private static void handleBuffer(byte[] inBuffer, EndPoint ep) { switch (inBuffer[0]) { case R.Net.Header.ACK: LogError("ACK from " + ep.ToString()); addNewPlayer(ep); break; case R.Net.Header.TICK: updateExistingPlayer(ref inBuffer); break; default: LogError("Server received a valid amount of data but the header is incorrect."); break; } } /*------------------------------------------------------------------------------------------------- -- FUNCTION: updateExistingPlayer -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Haley Booker -- -- INTERFACE: private static void updateExistingPlayer(ref byte[] inBuffer) -- byte[] inBuffer: The buffer of recieved data -- -- RETURNS: void -- -- NOTES: -- Updates the coordinates of a player and handles bullets or weapons switching. -------------------------------------------------------------------------------------------------*/ private static void updateExistingPlayer(ref byte[] inBuffer) { byte id = inBuffer[R.Net.Offset.PID]; float x = BitConverter.ToSingle(inBuffer, R.Net.Offset.X); float z = BitConverter.ToSingle(inBuffer, R.Net.Offset.Z); float r = BitConverter.ToSingle(inBuffer, R.Net.Offset.R); int weaponId = BitConverter.ToInt32(inBuffer, R.Net.Offset.WEAPON_ID); byte weaponType = inBuffer[R.Net.Offset.WEAPON_TYPE]; handleIncomingWeapon(id, weaponId, weaponType); int bulletId = BitConverter.ToInt32(inBuffer, R.Net.Offset.BULLET_ID); byte bulletType = inBuffer[R.Net.Offset.BULLET_TYPE]; handleIncomingBullet(id, bulletId, bulletType); mutex.WaitOne(); if (players[id].IsDead()) { deadPlayers.Add(id); } players[id].x = x; //crashing here players[id].z = z; players[id].r = r; mutex.ReleaseMutex(); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: handleIncomingBullet -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: private static void handleIncomingBullet(byte playerId, int bulletId, byte bulletType) -- byte playerId: The id of the player -- int bulletId: The id of the bullet -- byte bulletType: The type of bullet -- -- RETURNS: void -- -- NOTES: -- Creates a new bullet and adds it to the bullet array. -------------------------------------------------------------------------------------------------*/ private static void handleIncomingBullet(byte playerId, int bulletId, byte bulletType) { if (bulletType != 0) { Player player = players[playerId]; Bullet bullet = new Bullet(bulletId, bulletType, player); bullet.Event = R.Game.Bullet.ADD; mutex.WaitOne(); newBullets.Push(bullet); bullets[bulletId] = bullet; mutex.ReleaseMutex(); } } /*------------------------------------------------------------------------------------------------- -- FUNCTION: handleIncomingWeapon -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang, Tim Bruecker -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: private static void handleIncomingWeapon(byte playerId, int weaponId, byte weaponType) -- byte playerId: The id of the player -- int weaponId: The id of the weapon -- byte weaponType: The type of weapon -- -- RETURNS: void -- -- NOTES: -- Handles a player picking up a weapon and updating the player’s inventory. -------------------------------------------------------------------------------------------------*/ private static void handleIncomingWeapon(byte playerId, int weaponId, byte weaponType) { if (weaponId != 0) { mutex.WaitOne(); if (players[playerId].currentWeaponId == weaponId) { mutex.ReleaseMutex(); return; } players[playerId].currentWeaponId = weaponId; players[playerId].currentWeaponType = weaponType; weaponSwapEvents.Push(Tuple.Create(playerId, weaponId)); mutex.ReleaseMutex(); Console.WriteLine("Player {0} changed weapon to -> Weapon: ID - {1}, Type - {2}", playerId, weaponId, weaponType); } } /*------------------------------------------------------------------------------------------------- -- FUNCTION: addNewPlayer -- -- DATE: Feb 18, 2018 -- -- REVISIONS: Mar 27, 2018 - Refactored offsets for new packets -- Mar 30, 2018 - Implemented better spawn points -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Benny Wang, Haley Booker -- -- INTERFACE: private static void addNewPlayer(EndPoint ep) -- EndPoint ep: The end point of a new connection -- -- RETURNS: void -- -- NOTES: -- Creates a new player and adds it to the player array. -------------------------------------------------------------------------------------------------*/ private static void addNewPlayer(EndPoint ep) { List<float> spawnPoint = spawnPointGenerator.GetNextSpawnPoint(); Player newPlayer = new Player(ep, nextPlayerId, spawnPoint[0], spawnPoint[1]); mutex.WaitOne(); nextPlayerId++; players[newPlayer.id] = newPlayer; mutex.ReleaseMutex(); sendInitPacket(newPlayer); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: sendInitPacket -- -- DATE: Feb 18, 2018 -- -- REVISIONS: Mar 27, 2018 - Refactored offsets for new packets -- -- DESIGNER: Benny Wang, Tim Bruecker, Haley Booker -- -- PROGRAMMER: Haley Booker -- -- INTERFACE: private static void sendInitPacket(Player newPlayer) -- Player newPlayer: The new player to be sent -- -- RETURNS: void -- -- NOTES: -- Sends an initial packet to client on connection. The packet contains the client’s -- player id. -------------------------------------------------------------------------------------------------*/ private static void sendInitPacket(Player newPlayer) { byte[] buffer = new byte[R.Net.Size.SERVER_TICK]; buffer[0] = R.Net.Header.INIT_PLAYER; buffer[1] = newPlayer.id; int offset = 2; // sets the coordinates for the new player Array.Copy(BitConverter.GetBytes(newPlayer.x), 0, buffer, offset, 4); Array.Copy(BitConverter.GetBytes(newPlayer.z), 0, buffer, offset + 4, 4); server.Send(newPlayer.ep, buffer, buffer.Length); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: initTCPServer -- -- DATE: Mar. 28, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: private static void initTCPServer() -- -- RETURNS: void -- -- NOTES: -- This function is called to initialize a TCPServer object which handles TCP connections. -- After creating the TCPServer object, it creates a thread which executes listenThreadFunc -- and joins on the thread's termination. -------------------------------------------------------------------------------------------------*/ private static void initTCPServer() { tcpServer = new TCPServer(); tcpServer.Init(R.Net.PORT, R.Net.TIMEOUT); listenThread = new Thread(listenThreadFunc); listenThread.Start(); listenThread.Join(); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: generateInitData -- -- DATE: Feb 18, 2018 -- -- REVISIONS: Mar 27, 2018 - Refactored offsets for new packets -- -- DESIGNER: Benny Wang, Tim Bruecker -- -- PROGRAMMER: Benny Wang -- Roger Zhang -- Alfred Swinton -- -- INTERFACE: private static void generateInitData() -- -- RETURNS: void -- -- NOTES: -- This function generates the valid initialization for the terrain and weapons. -------------------------------------------------------------------------------------------------*/ private static void generateInitData() { dangerZone = new DangerZone(); InitRandomGuns getItems = new InitRandomGuns(R.Net.MAX_PLAYERS); itemData = getItems.compressedpcktarray; while (!tc.GenerateEncoding()) ; int terrainDataLength = tc.CompressedData.Length; Array.Copy(tc.CompressedData, 0, mapData, 0, terrainDataLength); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: listenThreadFunc -- -- DATE: Mar. 28, 2018 -- -- REVISIONS: Apr. 9, 2018 -- - Added timeout to listen loop, hard coded to 30s -- Apr. 11, 2018 -- - Modified timeout to accept a value passed down from -- R.Net.TIMEOUT -- -- DESIGNER: Wilson Hu, Angus Lam, Benny Wang -- -- PROGRAMMER: Wilson Hu, Angus Lam, Benny Wang -- -- INTERFACE: private static void listenThreadFunc() -- -- RETURNS: void -- -- NOTES: -- This thread function performs a listen loop that continuously accepts up to -- 30 clients. -- -- It calls the game generation function upon timing out or receiving the max -- number of clients. -- -- It then creates n threads to handle transmitting game initialization data to each -- connected client, and joining on each thread's termination. -------------------------------------------------------------------------------------------------*/ private static void listenThreadFunc() { Int32 clientsockfd; accepting = true; Networking.EndPoint ep = new Networking.EndPoint(); // Accept loop, accepts incoming client requests if there are <30 clients or loop is broken while (accepting && numClients < R.Net.MAX_PLAYERS) { clientsockfd = tcpServer.AcceptConnection(ref ep); // Breaks loop only if there are >1 clients and AcceptConnection call times out if (clientsockfd == R.Net.TIMEOUT_ERRNO && numClients > 1) { LogError("Accept timeout: Breaking out of listen loop"); accepting = false; } // If AcceptConnection call returns an error if (clientsockfd <= 0) { LogError("Accept error: " + clientsockfd); } // AcceptConnection call passes else { clientSockFdArr[numClients] = clientsockfd; LogError("Connected client: " + ep.ToString()); //Add toString() for EndPoint numClients++; } } // Generate game initialization data - weapon spawns & map data generateInitData(); // Intialize and start transmit threads for (int i = 0; i < numClients; i++) { transmitThreadArr[i] = new Thread(transmitThreadFunc); transmitThreadArr[i].Start(clientSockFdArr[i]); } // Join each transmitThread foreach (Thread t in transmitThreadArr) { if (t != null) { t.Join(); } } LogError("All threads joined, Starting game"); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: transmitThreadFunc -- -- DATE: Mar. 28, 2018 -- -- REVISIONS: -- -- DESIGNER: Wilson Hu, Angus Lam, Benny Wang -- -- PROGRAMMER: Angus Lam, Wilson Hu, Benny Wang -- -- INTERFACE: private static void transmitThreadFunc(object clientsockfd) -- object clientsockfd: a socket descriptor value which is cast to an Int32 within the function -- -- RETURNS: void -- -- NOTES: -- This thread function sends the game initialization data to its input client socket descriptor. -------------------------------------------------------------------------------------------------*/ private static void transmitThreadFunc(object clientsockfd) { Int32 numSentMap; Int32 numSentItem; Int32 sockfd = (Int32)clientsockfd; // Send item spawn data to the client numSentItem = tcpServer.Send(sockfd, itemData, R.Net.TCP_BUFFER_SIZE); LogError("Num Item Bytes Sent: " + numSentItem); // Send map data to the client numSentMap = tcpServer.Send(sockfd, mapData, R.Net.TCP_BUFFER_SIZE); LogError("Num Map Bytes Sent: " + numSentMap); // Close client TCP socket tcpServer.CloseClientSocket(sockfd); } /*------------------------------------------------------------------------------------------------- -- FUNCTION: LogError -- -- DATE: Feb 18, 2018 -- -- REVISIONS: -- -- DESIGNER: Benny Wang -- -- PROGRAMMER: Benny Wang -- -- INTERFACE: private static void LogError() -- -- RETURNS: void -- -- NOTES: -- Prints a message to the screen with the timestamp prepended to the message. -------------------------------------------------------------------------------------------------*/ private static void LogError(String s) { Console.WriteLine(DateTime.Now + " - " + s); } }
using Ada.Framework.Expressions.Entities; namespace Ada.Framework.Expressions.Evaluators { public class EvaluadorDistintoQue : Evaluador { public EvaluadorDistintoQue() { codigo = "NEQ"; Parametros.Add("Value"); delegado = ((objeto, condicion) => { object valorExpresion = ObtenerValorExpresion(objeto, condicion.Expresion); return valorExpresion.ToString().Trim() != condicion.ObtenerParametro("Value").Valor.ToString().Trim(); }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameTimer : MonoBehaviour { [SerializeField] private Text _timeText; public int Minutes { get; private set; } public int Seconds { get; private set; } public int MaxMinutes { get; private set; } public int MaxSeconds { get; private set; } [SerializeField] private int _startMinutes; [SerializeField] private int _startSeconds; [SerializeField] private FinishGame _finishGame; private void Start() { SetTimer(_startMinutes, _startSeconds); } /// <summary> /// Sets the time /// </summary> /// <param name="iMinutes"></param> /// <param name="iSeconds"></param> private void SetTimer(int iMinutes, int iSeconds) { MaxMinutes = iMinutes; MaxSeconds = iSeconds; Minutes = iMinutes; Seconds = iSeconds + 1; StartCoroutine("TimerDelay"); } /// <summary> /// Updates the time each second /// </summary> /// <returns></returns> IEnumerator TimerDelay() { while (true) { TimeCalculation(); yield return new WaitForSeconds(1); } } /// <summary> /// Calculates the current time, updates the text in the UI and checks if time is 0 /// </summary> private void TimeCalculation() { if (Seconds != 0) { Seconds--; } else { if (Minutes != 0) { Minutes--; Seconds += 59; } else { _finishGame.GameFinished(); StopCoroutine("TimerDelay"); } } if (Seconds >= 10) { _timeText.text = Minutes + ":" + Seconds; } else { _timeText.text = Minutes + ":0" + Seconds; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using BikeDistributor.Data.Entities; using BikeDistributor.Models; namespace BikeDistributor.Interfaces.Services { public interface IOrderService { OrderModel CalculateTotals(OrderModel orderModel); OrderModel GetOne(Expression<Func<Order, bool>> filter = null, string includeProperties = null); void Create(OrderModel orderModel, string createdBy = null); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.ComponentModel; using mywowNet.Data; using WowModelExplorer.Services; using WowModelExplorer.Data; using mywowNet; namespace WowModelExplorer.Controls { public delegate void SpellVisualEffect_TreeViewSelectedEventHandler(object sender, TreeNodeEntry spellEffect); /// <summary> /// Interaction logic for SpellVisualEffectTreeViewSelect.xaml /// </summary> public partial class SpellVisualEffectTreeViewSelect : UserControl { private ICollectionView spellVisualEffectsView; public SpellVisualEffectTreeViewSelect() { InitializeComponent(); _TreeView.AddHandler(TreeViewItem.MouseDoubleClickEvent, new MouseButtonEventHandler(treeViewItemDbClicked)); _TreeView.KeyUp += new KeyEventHandler(treeView_KeyUp); } public TreeEntryCollection TreeViewFiles { get { return this._mainGrid.Resources["_spellVisualEffectTreeViewCollection"] as TreeEntryCollection; } } public void FillData(SpellVisualEffectCollection spellVisualEffects) { GetSpellTreeItemFiles(spellVisualEffects, "", new TreeNodeEntry()); spellVisualEffectsView = CollectionViewSource.GetDefaultView(TreeViewFiles); _TreeView.ExpandAll(); } private void GetSpellTreeItemFiles(SpellVisualEffectCollection spellVisualEffects, string path, TreeNodeEntry node) { WowEnvironment env = Engine.Instance.WowEnvironment; env.ClearOwnCascFiles(); foreach(SpellVisualEffect spell in spellVisualEffects) { string s = Engine.Instance.WowDatabase.GetSpellVisualEffectPath(spell.Id); env.AddOwnCascFile(s); } env.FinishOwnCascFiles(); TreeViewFiles.Clear(); TreeNodeEntry treeNode = TreeViewEntry.TraverseAllUseOwn(path, "*", node); for (int i = 0; i < treeNode.NodeEntrys.Count; i++) { TreeViewFiles.Add(treeNode.NodeEntrys[i]); } } public event SpellVisualEffect_TreeViewSelectedEventHandler SpellVisualEffectTreeView_Selected; private void treeView_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Return) LoadSpellVisualEffect(); } public void treeViewItemDbClicked(object sender, MouseButtonEventArgs e) { LoadSpellVisualEffect(); } private void LoadSpellVisualEffect() { TreeNodeEntry entry = _TreeView.SelectedItem as TreeNodeEntry; if (entry != null) { if (SpellVisualEffectTreeView_Selected != null) SpellVisualEffectTreeView_Selected.Invoke(this, entry); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SA { public class BattleResolve : Phase { public Element attackElement; public Element defenseElement; public override bool IsComplete() { if (forceExit) { forceExit = false; return true; } return false; } public override void OnEndPhase() { throw new System.NotImplementedException(); } public override void OnStartPhase() { PlayerHolder p = Settings.gameManager.currentPlayer; if(p.attackingCards.Count == 0) { forceExit = true; return; } for(int i = 0; i < p.attackingCards.Count; i++) { CardInstance inst = p.attackingCards[i]; Card c = inst.viz.cards; CardProperties attack = c.GetProperty(attackElement); if(attack == null) { Debug.LogError("This card cannot be attacked!"); continue; } //in Card.cs - line 14 add : //public CardProperties GetProperty(Element e){ // for(int i = 0; i < properties.Length; i++){ // { if(properties[i].element == e){ // return properties[i]; // } return null; //} } } } }
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual { /// <summary> /// Representa el objeto request de contrato bien /// </summary> /// <remarks> /// Creación : GMD 20150803 <br /> /// Modificación : <br /> /// </remarks> public class ContratoBienRequest : Filtro { /// <summary> /// Código de Contrato Bien /// </summary> public string CodigoContratoBien { get; set; } /// <summary> /// Código de Contrato /// </summary> public string CodigoContrato { get; set; } /// <summary> /// Código de Bien /// </summary> public string CodigoBien { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; namespace MyAngularSite { /// <summary> /// Class BundleConfig. /// </summary> public static class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/dependencies") .Include("~/components/jquery/dist/jquery.min.js") .Include("~/components/angular/angular.min.js") .Include("~/components/angular-route/angular-route.min.js") .Include("~/components/angular-resource/angular-resource.min.js") .Include("~/components/angular-cookies/angular-cookies.min.js") .Include("~/components/underscore/underscore.js") .Include("~/components/angular-bootstrap/ui-bootstrap.min.js") ); #if (DEBUG) BundleTable.EnableOptimizations = false; #else BundleTable.EnableOptimizations = true; #endif } } }
using System; using System.Collections.Generic; using System.Linq; using Alabo.Datas.Queries.Enums; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Entities; using Alabo.Domains.Query.Dto; using Alabo.Domains.Services; using Alabo.Extensions; using Alabo.Mapping; using MongoDB.Bson; using MongoDB.Driver; namespace Alabo.Industry.Cms.LightApps.Domain.Services { #pragma warning disable CS1591 // 缺少对公共可见类型或成员的 XML 注释 public class LightAppService : ServiceBase, ILightAppService { public LightAppService(IUnitOfWork unitOfWork) : base(unitOfWork) { } public ServiceResult Add(string tableName, string dataJson) { var modelBaseJson = new AutoDataBaseEntity().ToJsons(); var rsJoinJson = $"{dataJson.TrimEnd('}')},{modelBaseJson.TrimStart('{')}"; // dynamic object var model = LightAppStore.JsonToDynamicObject(rsJoinJson); LightAppStore.GetCollection(tableName).InsertOne(model); return ServiceResult.Success; } public long Count(string tableName) { return LightAppStore.Count(tableName); } public ServiceResult Delete(string tableName, ObjectId id) { var rs = LightAppStore.DeleteOne(tableName, id); return rs ? ServiceResult.Success : ServiceResult.Failed; } /// <summary> /// 按 字段 和 字段值 取List /// fieldName || fieldValue 为空则获取数据表的所有数据. /// </summary> /// <param name="tableName"></param> /// <param name="fieldName"></param> /// <param name="fieldValue"></param> /// <returns></returns> public List<dynamic> GetList(string tableName, string fieldName = "", string fieldValue = "") { // return all data. if (fieldName.IsNullOrEmpty() || fieldValue.IsNullOrEmpty()) { return LightAppStore.GetCollection(tableName).AsQueryable().ToList(); } var dic = new Dictionary<string, string> { {fieldName, fieldValue} }; var rsList = GetList(tableName, dic).ToList(); return rsList; } public List<dynamic> GetList(string tableName, object query) { throw new NotImplementedException(); } public dynamic GetSingle(string tableName, Dictionary<string, string> query) { if (tableName.IsNullOrEmpty()) { tableName = query.GetValue("TableName"); query.Remove("TableName"); } var listOp = new List<(string Field, Operator op, string Value)>(); foreach (var item in query) { var rs = LightAppStore.ComparisonParse(item); listOp.Add(rs); } var rsList = LightAppStore.QuerySingle(tableName, listOp); return rsList; } public List<dynamic> GetList(string tableName, Dictionary<string, string> query) { if (tableName.IsNullOrEmpty()) { tableName = query.GetValue("TableName"); query.Remove("TableName"); } var listOp = new List<(string Field, Operator op, string Value)>(); foreach (var item in query) { var rs = LightAppStore.ComparisonParse(item); listOp.Add(rs); } var rsList = LightAppStore.QueryList(tableName, listOp).ToList(); return rsList; } public List<dynamic> GetListByClassId(string tableName, long classId) { return GetList(tableName, "ClassId", classId.ToString()); } public List<dynamic> GetListByUserId(string tableName, long userId) { return GetList(tableName, "UserId", userId.ToString()); } public PagedList<dynamic> GetPagedList(string tableName, object paramater) { var pageSize = 0; var pageIndex = 0; var dictionary = paramater.DeserializeJson<Dictionary<string, string>>(); if (dictionary != null) { var pagedInput = AutoMapping.SetValue<PagedInputDto>(dictionary); if (pagedInput != null) { pageSize = (int) pagedInput.PageSize; pageIndex = (int) pagedInput.PageIndex; } } if (pageSize < 1) { pageSize = 1; } if (pageIndex < 1) { pageIndex = 1; } dictionary.Remove("PageSize"); dictionary.Remove("PageIndex"); var listOp = new List<(string Field, Operator op, string Value)>(); foreach (var item in dictionary) { var rs = LightAppStore.ComparisonParse(item); listOp.Add(rs); } var filter = LightAppStore.FilterParser(listOp); var fetchList = LightAppStore.GetCollection(tableName).Find(filter) .Skip(pageSize * (pageIndex - 1)).Limit(pageSize) .ToList(); var totalCount = LightAppStore.GetCollection(tableName).Find(filter).CountDocuments(); var pagedList = PagedList<dynamic>.Create(fetchList, totalCount, pageSize, pageIndex); return pagedList; } public dynamic GetSingle(string tableName, ObjectId id) { return LightAppStore.GetSingle(tableName, "_id", id.ToString()); } public dynamic GetSingle(string tableName, string fieldName, string fieldValue) { return LightAppStore.GetSingle(tableName, fieldName, fieldValue); } public ServiceResult Update(string tableName, string dataJson, ObjectId id) { var modelBaseJson = new AutoDataBaseEntity().ToJsons(); var rsJson = $"{dataJson.TrimEnd('}')},{modelBaseJson.TrimStart('{')}"; // dynamic object var model = LightAppStore.JsonToDynamicObject(rsJson); var filter = Builders<dynamic>.Filter.Eq("_id", id); LightAppStore.GetCollection(tableName).FindOneAndReplace<dynamic>(filter, model); return ServiceResult.Success; } public IList<dynamic> GetList(Dictionary<string, string> dictionary) { //var predicate = LinqHelper.DictionaryToLinq<object>(dictionary); return GetList(null); } } }
namespace Serilog.Tests.Core; public class ChildLoggerTests { public static IEnumerable<object?[]> GetMinimumLevelInheritanceTestCases() { // Visualizing the pipeline from left to right .... // // Event --> Root Logger --> restrictedTo --> Child Logger -> YES or // lvl min lvl param min lvl NO ? // static object?[] T(LogEventLevel el, int? rl, int? rt, int? cl, bool r) { return new object?[] { el, rl, rt, cl, r }; } // numbers are relative to incoming event level // Information + 1 = Warning // Information - 1 = Debug // Information + null = default // // - default case - nothing specified // equivalent to "Information+ allowed" yield return T(Verbose, null, null, null, false); yield return T(Debug, null, null, null, false); yield return T(Information, null, null, null, true); yield return T(Warning, null, null, null, true); yield return T(Error, null, null, null, true); yield return T(Fatal, null, null, null, true); // - cases where event level is high enough all along the pipeline // e --> --> --> = OK yield return T(Verbose, +0, +0, +0, true); yield return T(Debug, +0, +0, +0, true); yield return T(Information, +0, +0, +0, true); yield return T(Warning, +0, +0, +0, true); yield return T(Error, +0, +0, +0, true); yield return T(Fatal, +0, +0, +0, true); // - cases where event is blocked by root minimum level // e -x> - - = NO yield return T(Verbose, +1, +0, +0, false); yield return T(Debug, +1, +0, +0, false); yield return T(Information, +1, +0, +0, false); yield return T(Warning, +1, +0, +0, false); yield return T(Error, +1, +0, +0, false); // - cases where event is blocked by param restrictedToMinimumLevel // e --> -x> - = NO yield return T(Verbose, +0, +1, +0, false); yield return T(Debug, +0, +1, +0, false); yield return T(Information, +0, +1, +0, false); yield return T(Warning, +0, +1, +0, false); yield return T(Error, +0, +1, +0, false); // - cases where event is blocked by child minimum level // e --> --> -x> = NO yield return T(Verbose, +0, +0, +1, false); yield return T(Debug, +0, +0, +1, false); yield return T(Information, +0, +0, +1, false); yield return T(Warning, +0, +0, +1, false); yield return T(Error, +0, +0, +1, false); } [Theory] [MemberData(nameof(GetMinimumLevelInheritanceTestCases))] public void WriteToLoggerWithConfigCallbackMinimumLevelInheritanceScenarios( LogEventLevel eventLevel, int? rootMinimumLevelIncrement, int? sinkRestrictedToIncrement, int? childMinimumLevelIncrement, bool eventShouldGetToChild) { var rootMinimumLevel = eventLevel + rootMinimumLevelIncrement ?? Information; var sinkRestrictedToMinimumLevel = eventLevel + sinkRestrictedToIncrement ?? Verbose; var childMinimumLevel = eventLevel + childMinimumLevelIncrement ?? Information; LogEvent? evt = null; var sink = new DelegatingSink(e => evt = e); var logger = new LoggerConfiguration() .MinimumLevel.Is(rootMinimumLevel) .WriteTo.Logger(lc => lc .MinimumLevel.Is(childMinimumLevel) .WriteTo.Sink(sink), restrictedToMinimumLevel: sinkRestrictedToMinimumLevel) .CreateLogger(); logger.Write(Some.LogEvent(level: eventLevel)); if (eventShouldGetToChild) { Assert.NotNull(evt); } else { Assert.Null(evt); } } [Theory] [MemberData(nameof(GetMinimumLevelInheritanceTestCases))] public void WriteToLoggerMinimumLevelInheritanceScenarios( LogEventLevel eventLevel, int? rootMinimumLevelIncrement, int? sinkRestrictedToIncrement, int? childMinimumLevelIncrement, bool eventShouldGetToChild) { var rootMinimumLevel = eventLevel + rootMinimumLevelIncrement ?? Information; var sinkRestrictedToMinimumLevel = eventLevel + sinkRestrictedToIncrement ?? Verbose; var childMinimumLevel = eventLevel + childMinimumLevelIncrement ?? Information; LogEvent? evt = null; var sink = new DelegatingSink(e => evt = e); var childLogger = new LoggerConfiguration() .MinimumLevel.Is(childMinimumLevel) .WriteTo.Sink(sink) .CreateLogger(); var logger = new LoggerConfiguration() .MinimumLevel.Is(rootMinimumLevel) .WriteTo.Logger(childLogger, restrictedToMinimumLevel: sinkRestrictedToMinimumLevel) .CreateLogger(); logger.Write(Some.LogEvent(level: eventLevel)); if (eventShouldGetToChild) { Assert.NotNull(evt); } else { Assert.Null(evt); } } public static IEnumerable<object?[]> GetMinimumLevelOverrideInheritanceTestCases() { // Visualizing the pipeline from left to right .... // // Event --> Root Logger --> Child Logger -> YES or // lvl override/lvl override/lvl NO ? // static object?[] T(string? rs, int? rl, string? cs, int? cl, bool r, LogEventLevel dl = LevelAlias.Minimum) { return new object?[] { dl, rs, rl, cs, cl, r }; } // numbers are relative to incoming event level // Information + 1 = Warning // Information - 1 = Debug // // Incoming event is Information // with SourceContext Root.N1.N2 // // - default case - no overrides yield return T(null, 0, null, 0, true); // - root overrides with level lower or equal to event // ... and child logger is out of the way yield return T("Root", +0, null, +0, true); yield return T("Root", -1, null, +0, true); yield return T("Root", -1, null, +0, true, LevelAlias.Maximum); yield return T("Root.N1", +0, null, +0, true); yield return T("Root.N1", -1, null, +0, true); yield return T("Root.N1", -1, null, +0, true, LevelAlias.Maximum); yield return T("Root.N1.N2", +0, null, +0, true); yield return T("Root.N1.N2", -1, null, +0, true); yield return T("Root.N1.N2", -1, null, +0, true, LevelAlias.Maximum); // - root overrides on irrelevant namespaces yield return T("xx", +1, null, +0, true); yield return T("Root.xx", +1, null, +0, true); yield return T("Root.N1.xx", +1, null, +0, true); // - child overrides on irrelevant namespaces yield return T(null, +0, "xx", +1, true); yield return T(null, +0, "Root.xx", +1, true); yield return T(null, +1, "Root.N1.xx", +1, true); // - root overrides prevent all processing from children // even though children would happily accept it yield return T("Root", +1, null, +0, false); yield return T("Root", +1, "Root", +0, false); yield return T("Root.N1", +1, null, +0, false); yield return T("Root.N1", +1, "Root.N1", +0, false); yield return T("Root.N1.N2", +1, null, +0, false); yield return T("Root.N1.N2", +1, "Root.N1.N2", +0, false); } [Theory] [MemberData(nameof(GetMinimumLevelOverrideInheritanceTestCases))] public void WriteToLoggerWithConfigCallbackMinimumLevelOverrideInheritanceScenarios( LogEventLevel defaultRootLevel, string? rootOverrideSource, int rootOverrideLevelIncrement, string? childOverrideSource, int childOverrideLevelIncrement, bool eventShouldGetToChild) { const LogEventLevel incomingEventLevel = Information; var rootOverrideLevel = incomingEventLevel + rootOverrideLevelIncrement; var childOverrideLevel = incomingEventLevel + childOverrideLevelIncrement; LogEvent? evt = null; var sink = new DelegatingSink(e => evt = e); var rootLoggerConfig = new LoggerConfiguration() .MinimumLevel.Is(defaultRootLevel); if (rootOverrideSource != null) { rootLoggerConfig.MinimumLevel.Override(rootOverrideSource, rootOverrideLevel); } var logger = rootLoggerConfig .WriteTo.Logger(lc => { if (childOverrideSource != null) { lc.MinimumLevel.Override(childOverrideSource, childOverrideLevel); } lc.WriteTo.Sink(sink); }) .CreateLogger(); logger .ForContext(Constants.SourceContextPropertyName, "Root.N1.N2") .Write(Some.LogEvent(level: incomingEventLevel)); if (eventShouldGetToChild) { Assert.NotNull(evt); } else { Assert.Null(evt); } } [Theory] [MemberData(nameof(GetMinimumLevelOverrideInheritanceTestCases))] public void WriteToLoggerMinimumLevelOverrideInheritanceScenarios( LogEventLevel defaultRootLevel, string? rootOverrideSource, int rootOverrideLevelIncrement, string? childOverrideSource, int childOverrideLevelIncrement, bool eventShouldGetToChild) { const LogEventLevel incomingEventLevel = Information; var rootOverrideLevel = incomingEventLevel + rootOverrideLevelIncrement; var childOverrideLevel = incomingEventLevel + childOverrideLevelIncrement; LogEvent? evt = null; var sink = new DelegatingSink(e => evt = e); var childLoggerConfig = new LoggerConfiguration() .MinimumLevel.Is(LevelAlias.Minimum); if (childOverrideSource != null) { childLoggerConfig.MinimumLevel.Override(childOverrideSource, childOverrideLevel); } childLoggerConfig.WriteTo.Sink(sink); var childLogger = childLoggerConfig.CreateLogger(); var rootLoggerConfig = new LoggerConfiguration() .MinimumLevel.Is(defaultRootLevel); if (rootOverrideSource != null) { rootLoggerConfig.MinimumLevel.Override(rootOverrideSource, rootOverrideLevel); } var logger = rootLoggerConfig .WriteTo.Logger(childLogger) .CreateLogger(); logger .ForContext(Constants.SourceContextPropertyName, "Root.N1.N2") .Write(Some.LogEvent(level: incomingEventLevel)); if (eventShouldGetToChild) { Assert.NotNull(evt); } else { Assert.Null(evt); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using Xunit; namespace Westerhoff.Configuration.EnvironmentAliases.Test { public class ProviderTests { [Fact] public void MappingIsApplied() { // arrange var mapping = new Dictionary<string, string> { ["key1"] = "Foo:Bar:Baz", ["key2"] = "Foo:Bar:Qux", ["key3"] = "ConnectionStrings:Default", }; var environmentVariables = new Hashtable { ["key1"] = "Foo value", ["key2"] = "Bar value", ["key3"] = "Baz value", }; // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); // assert Assert.True(provider.TryGet("Foo:Bar:Baz", out string value)); Assert.Equal("Foo value", value); Assert.True(provider.TryGet("Foo:Bar:Qux", out value)); Assert.Equal("Bar value", value); Assert.True(provider.TryGet("ConnectionStrings:Default", out value)); Assert.Equal("Baz value", value); Assert.False(provider.TryGet("key1", out value)); Assert.False(provider.TryGet("key2", out value)); Assert.False(provider.TryGet("key3", out value)); } [Fact] public void UnconfiguredKeysAreIgnored() { // arrange var mapping = new Dictionary<string, string> { ["key2"] = "Foo:Bar", ["key4"] = "Foo:Baz", }; var environmentVariables = new Hashtable { ["key1"] = "Foo", ["key2"] = "Bar", ["key3"] = "Baz", ["key4"] = "Baz", }; // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); // assert var keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.Equal(2, keyCount); Assert.True(provider.TryGet("Foo:Bar", out _)); Assert.True(provider.TryGet("Foo:Baz", out _)); } [Fact] public void MissingEnvironmentVariablesAreIgnored() { // arrange var mapping = new Dictionary<string, string> { ["key1"] = "Foo:Bar:Baz", ["key2"] = "Foo:Bar:Qux", ["key3"] = "ConnectionStrings:Default", }; var environmentVariables = new Hashtable { ["key2"] = "Bar", }; // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); // assert var keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.Equal(1, keyCount); Assert.True(provider.TryGet("Foo:Bar:Qux", out var value)); Assert.Equal("Bar", value); } [Fact] public void EmptyMappingReturnsEmptyConfiguration() { // arrange var mapping = new Dictionary<string, string>(); var environmentVariables = new Hashtable { ["key1"] = "Foo", ["key2"] = "Bar", ["key3"] = "Baz", ["key4"] = "Baz", }; // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); // assert var keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.Equal(0, keyCount); } [Fact] public void EmptyEnvironmentVariablesReturnsEmptyConfiguration() { // arrange var mapping = new Dictionary<string, string> { ["key2"] = "Foo:Bar", ["key4"] = "Foo:Baz", }; var environmentVariables = new Hashtable(); // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); // assert var keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.Equal(0, keyCount); } [Fact] public void OverwritesPreviousData() { // arrange var mapping = new Dictionary<string, string> { ["key1"] = "Foo:Bar:Baz", ["key2"] = "Foo:Bar:Qux", ["key3"] = "ConnectionStrings:Default", }; var environmentVariables = new Hashtable { ["key1"] = "Foo value", ["key2"] = "Bar value", ["key3"] = "Baz value", }; // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); var keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.NotEqual(0, keyCount); environmentVariables = new Hashtable { ["key3"] = "Baz", }; provider.Load(environmentVariables); // assert keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.Equal(1, keyCount); Assert.True(provider.TryGet("ConnectionStrings:Default", out var value)); Assert.Equal("Baz", value); } [Fact] public void DuplicateKeysWithDifferentCasing() { // arrange var mapping = new Dictionary<string, string> { ["key1"] = "Foo:Bar:Baz", ["key2"] = "Foo:Bar:Qux", }; var environmentVariables = new Hashtable { ["key1"] = "Foo value 1", ["Key1"] = "Foo value 2", ["kEY1"] = "Foo value 3", }; // act var provider = new EnvironmentAliasesConfigurationProvider(mapping); provider.Load(environmentVariables); // assert var keyCount = provider.GetChildKeys(Enumerable.Empty<string>(), parentPath: null).Count(); Assert.Equal(1, keyCount); Assert.True(provider.TryGet("Foo:Bar:Baz", out var value)); Assert.Equal("Foo value", value.Substring(0, 9)); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Drawing; using System.Text; using System.Diagnostics; using System.Windows.Forms; namespace ImageQuantization { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } RGBPixel[,] ImageMatrix; private void btnOpen_Click(object sender, EventArgs e) { Stopwatch s = new Stopwatch(); s.Start(); OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (openFileDialog1.ShowDialog() == DialogResult.OK) { //Open the browsed image and display it string OpenedFilePath = openFileDialog1.FileName; ImageMatrix = ImageOperations.OpenImage(OpenedFilePath); ImageOperations.DisplayImage(ImageMatrix, pictureBox1); txtWidth.Text = ImageOperations.GetWidth(ImageMatrix).ToString(); txtHeight.Text = ImageOperations.GetHeight(ImageMatrix).ToString(); } else if (ImageMatrix != null) { txtWidth.Text = ImageOperations.GetWidth(ImageMatrix).ToString(); txtHeight.Text = ImageOperations.GetHeight(ImageMatrix).ToString(); } else MessageBox.Show(" Choose Image "); s.Stop(); txtTime.Text = Convert.ToString(s.Elapsed); } private void btnEncrypt_Click(object sender, EventArgs e) { Stopwatch s = new Stopwatch(); s.Start(); if (ImageMatrix != null && txtIntialSeed.Text.Length > 0 && txtTape.Text.Length > 0) { ImageOperations.Encrypt_Decrypt(ref ImageMatrix, txtIntialSeed.Text, Convert.ToInt32(txtTape.Text)); label4.Text = "Encrypt Image"; ImageOperations.DisplayImage(ImageMatrix, pictureBox2); } else if ((txtIntialSeed.Text.Length == 0 || txtTape.Text.Length == 0) && ImageMatrix != null) { MessageBox.Show("Enter Intial Seed & Tape Position"); } else MessageBox.Show(" Open Image "); s.Stop(); txtTime.Text = Convert.ToString(s.Elapsed); } private void btnDecrypt_Click(object sender, EventArgs e) { Stopwatch s = new Stopwatch(); s.Start(); if (ImageMatrix != null && txtIntialSeed.Text.Length > 0 && txtTape.Text.Length > 0) { ImageOperations.Encrypt_Decrypt(ref ImageMatrix, txtIntialSeed.Text, Convert.ToInt32(txtTape.Text)); label4.Text = "Decrypt Image"; ImageOperations.DisplayImage(ImageMatrix, pictureBox2); } else if ((txtIntialSeed.Text.Length == 0 || txtTape.Text.Length == 0) && ImageMatrix != null) MessageBox.Show("Enter Intial Seed & Tape Position"); else MessageBox.Show(" Open Image "); s.Stop(); txtTime.Text = Convert.ToString(s.Elapsed); } private void btnHuffman_Click(object sender, EventArgs e) { ImageOperations.Total_Bits = 0; Stopwatch s = new Stopwatch(); s.Start(); if (ImageMatrix != null) ImageOperations.Huffman_Code(ref ImageMatrix); else MessageBox.Show(" Open Image "); s.Stop(); txtTime.Text = Convert.ToString(s.Elapsed); MessageBox.Show("File Has been saved "); } private void button1_Click(object sender, EventArgs e) { ImageOperations.Huffman_Code(ref ImageMatrix); Stopwatch s = new Stopwatch(); s.Start(); ImageOperations.str_1(ImageMatrix); ImageOperations.compress_image(ImageOperations.R, ImageOperations.G, ImageOperations.B, ImageOperations.arr, ImageOperations.arr1, ImageOperations.arr2, Convert.ToInt32(txtTape.Text), txtIntialSeed.Text, Convert.ToInt32(txtWidth.Text), Convert.ToInt32(txtHeight.Text)); s.Stop(); txtTime.Text = Convert.ToString(s.Elapsed); MessageBox.Show("File Has Been Saved "); } private void button2_Click(object sender, EventArgs e) { Stopwatch s = new Stopwatch(); s.Start(); ImageMatrix = ImageOperations.decompress_image(); s.Stop(); txtTime.Text = Convert.ToString(s.Elapsed); txtIntialSeed.Text = ImageOperations.Initial_Seed; txtTape.Text = ImageOperations.Tape_Position.ToString(); ImageOperations.DisplayImage(ImageMatrix, pictureBox1); MessageBox.Show("Decompressed Done "); } private void button3_Click(object sender, EventArgs e) { saveFileDialog1.Title = "Save"; saveFileDialog1.Filter = "Bitmap (.bmp)|*.bmp|Gif (.gif)|*.gif|JPG (.jpg)|*.jpg |JPEG (.jpeg)|*.jpeg |Png (.png)|*.png |Tiff (.tiff)|*.tiff |Wmf (.wmf)|*.wmf"; saveFileDialog1.DefaultExt = "bmp"; saveFileDialog1.FileName = "Image.bmp"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { pictureBox1.Image.Save(saveFileDialog1.FileName); } } } }
 using System.Collections.Generic; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Docller.Core.Models; namespace Docller.Core.Common { public interface IDocllerContext { void Inject(Controller controller); void Inject(Controller controller, User user); void InjectFolder(IFolderContext folderContext); UrlHelper UrlContext { get; } IDocllerSession Session { get; } string UserName { get; } long CustomerId { get; } long ProjectId { get; } ICache Cache { get; } IFolderContext FolderContext { get; } RouteData RouteData { get; } HttpRequestBase Request { get; } ISecurityContext Security { get; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using ServerApp.Data; using System.Threading.Tasks; using System.Collections.Generic; using ServerApp.DTO; using AutoMapper; namespace ServerApp.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController:ControllerBase { private readonly ISocialRepository _repository; private readonly IMapper _mapper; public UsersController(ISocialRepository repository,IMapper mapper){ _repository=repository; _mapper=mapper; } public async Task<IActionResult> GetUsers(){ var users=await _repository.GetUsers(); var result= _mapper.Map<IEnumerable<UserForListDTO>>(users); return Ok(result); } [HttpGet("{id}")] public async Task<IActionResult> GetUser(int id){ var user=await _repository.GetUser(id); var result =_mapper.Map<UserForDetailsDTO>(user); return Ok(result); } } }
using System.Threading; using System.Threading.Tasks; namespace CQRS.MediatR.Event { public interface IEventBus { Task Publish(IEvent @event, CancellationToken cancellationToken = default); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using CapaNegocio; namespace CapaPresentacion { public partial class frmArticulo : Form { private bool IsNuevo = false; private bool IsEditar = false; private static frmArticulo _Instancia; public static frmArticulo GetInstancia () { if(_Instancia==null) { _Instancia = new frmArticulo(); } return _Instancia; } public void setCategoria (string idcategoria,string nombre) { this.txtIdcategoria.Text = idcategoria; this.txtCategoria.Text = nombre; } public frmArticulo() { InitializeComponent(); this.ttMensaje.SetToolTip(this.txtNombre, "Ingrese el nombre del artículo"); this.ttMensaje.SetToolTip(this.pxImagen, "Seleccione la imagen del artículo"); this.ttMensaje.SetToolTip(this.txtCategoria, "Seleccione la categoría del artículo"); this.ttMensaje.SetToolTip(this.cbIdpresentacion, "Seleccione la presentación del artículo"); this.txtIdcategoria.Visible = false; this.txtCategoria.ReadOnly = true; this.LlenarComboPresentacion(); } // Mostrar mensaje de Confirmación private void MensajeOk(string mensaje) { MessageBox.Show(mensaje, "Sistema de ventas", MessageBoxButtons.OK, MessageBoxIcon.Information); } // Mostrar mensaje de error private void MensajeError(string mensaje) { MessageBox.Show(mensaje, "Sistema de ventas", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Limpiar todos los controles del formulario private void Limpiar() { this.txtCodigo.Text = string.Empty; this.txtNombre.Text = string.Empty; this.txtDescripcion.Text = string.Empty; this.txtIdcategoria.Text = string.Empty; this.txtCategoria.Text = string.Empty; this.txtIdarticulo.Text = string.Empty; this.pxImagen.Image = global::CapaPresentacion.Properties.Resources._null; } // Habilitar los controles del formulario private void Habilitar(bool valor) { this.txtCodigo.ReadOnly=!valor; this.txtNombre.ReadOnly = !valor; this.txtDescripcion.ReadOnly = !valor; this.btnBuscarCategoria.Enabled = valor; this.cbIdpresentacion.Enabled = valor; this.btnCargar.Enabled = valor; this.btnLimpiar.Enabled = valor; this.txtIdarticulo.ReadOnly = !valor; } // Habilitar los botones del formulario private void Botones() { if (this.IsNuevo || this.IsEditar) { this.Habilitar(true); this.btnNuevo.Enabled = false; this.btnGuardar.Enabled = true; this.btnEditar.Enabled = false; this.btnCancelar.Enabled = true; } else { this.Habilitar(false); this.btnNuevo.Enabled = true; this.btnGuardar.Enabled = false; this.btnEditar.Enabled = true; this.btnCancelar.Enabled = false; } } // Ocultar columnas private void OcultarColumnas() { this.dataListado.Columns[0].Visible = false; this.dataListado.Columns[1].Visible = false; this.dataListado.Columns[6].Visible = false; this.dataListado.Columns[8].Visible = false; } // Método Mostrar private void Mostrar() { this.dataListado.DataSource = NArticulo.Mostrar(); this.OcultarColumnas(); lblTotal.Text = "Total de Registros: " + Convert.ToString(dataListado.Rows.Count); } // Método BuscarNombre private void BuscarNombre() { this.dataListado.DataSource = NArticulo.BuscarNombre(this.txtBuscar.Text); this.OcultarColumnas(); lblTotal.Text = "Total de Registros: " + Convert.ToString(dataListado.Rows.Count); } private void LlenarComboPresentacion () { cbIdpresentacion.DataSource = NPresentacion.Mostrar(); cbIdpresentacion.ValueMember = "idpresentacion"; cbIdpresentacion.DisplayMember = "nombre"; } private void label4_Click(object sender, EventArgs e) { } private void btnCargar_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); DialogResult result = dialog.ShowDialog(); if (result==DialogResult.OK) { this.pxImagen.SizeMode = PictureBoxSizeMode.StretchImage; this.pxImagen.Image = Image.FromFile(dialog.FileName); } } private void btnLimpiar_Click(object sender, EventArgs e) { this.pxImagen.SizeMode = PictureBoxSizeMode.StretchImage; this.pxImagen.Image = global::CapaPresentacion.Properties.Resources._null; } private void frmArticulo_Load(object sender, EventArgs e) { this.Top = 0; this.Left = 0; this.Mostrar(); this.Habilitar(false); this.Botones(); } private void btnBuscar_Click(object sender, EventArgs e) { this.BuscarNombre(); } private void txtBuscar_TextChanged(object sender, EventArgs e) { this.BuscarNombre(); } private void btnNuevo_Click(object sender, EventArgs e) { this.IsNuevo = true; this.IsEditar = false; this.Botones(); this.Limpiar(); this.Habilitar(true); this.txtNombre.Focus(); } private void BtnGuardar_Click(object sender, EventArgs e) { try { string rpta = ""; if (this.txtNombre.Text == string.Empty || this.txtCategoria.Text == string.Empty || this.txtCodigo.Text == string.Empty) { MensajeError("Falta ingresar los datos marcados"); errorIcono.SetError(txtNombre, "Ingrese un valor"); errorIcono.SetError(txtCodigo, "Ingrese un valor"); errorIcono.SetError(txtCategoria, "Ingrese un valor"); } else { System.IO.MemoryStream ms = new System.IO.MemoryStream(); this.pxImagen.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); byte[] imagen = ms.GetBuffer(); if (this.IsNuevo) { rpta = NArticulo.Insertar(this.txtCodigo.Text,this.txtNombre.Text.Trim().ToUpper(), this.txtDescripcion.Text.Trim(),imagen,Convert.ToInt32(this.txtIdcategoria.Text), Convert.ToInt32(this.cbIdpresentacion.SelectedValue)); } else { rpta = NArticulo.Editar(Convert.ToInt32(this.txtIdarticulo.Text), this.txtCodigo.Text, this.txtNombre.Text.Trim().ToUpper(), this.txtDescripcion.Text.Trim(), imagen, Convert.ToInt32(this.txtIdcategoria.Text), Convert.ToInt32(this.cbIdpresentacion.SelectedValue)); } if (rpta.Equals("OK")) { if (this.IsNuevo) { this.MensajeOk("Se insertó de forma correcta el registro"); } else { this.MensajeOk("Se actualizó de forma correcta el registro"); } } else { this.MensajeError(rpta); } this.IsNuevo = false; this.IsEditar = false; this.Botones(); this.Limpiar(); this.Mostrar(); } } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } } private void BtnEditar_Click(object sender, EventArgs e) { if (!this.txtIdarticulo.Text.Equals("")) { this.IsEditar = true; this.Botones(); this.Habilitar(true); } else { this.MensajeError("Primero seleccione el registo a modificar"); } } private void BtnCancelar_Click(object sender, EventArgs e) { this.IsNuevo = false; this.IsEditar = false; this.Botones(); this.Limpiar(); this.Habilitar(false); } private void DataListado_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == dataListado.Columns["Eliminar"].Index) { DataGridViewCheckBoxCell ChkEliminar = (DataGridViewCheckBoxCell)dataListado.Rows[e.RowIndex].Cells["Eliminar"]; ChkEliminar.Value = !Convert.ToBoolean(ChkEliminar.Value); } } private void DataListado_DoubleClick(object sender, EventArgs e) { this.txtIdarticulo.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["idarticulo"].Value); this.txtCodigo.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["codigo"].Value); this.txtNombre.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["nombre"].Value); this.txtDescripcion.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["descripcion"].Value); byte[] imagenBuffer = (byte[])this.dataListado.CurrentRow.Cells["imagen"].Value; System.IO.MemoryStream ms = new System.IO.MemoryStream(imagenBuffer); this.pxImagen.Image = Image.FromStream(ms); this.pxImagen.SizeMode = PictureBoxSizeMode.StretchImage; this.txtIdcategoria.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["idcategoria"].Value); this.txtCategoria.Text = Convert.ToString(this.dataListado.CurrentRow.Cells["categoria"].Value); this.cbIdpresentacion.SelectedValue = Convert.ToString(this.dataListado.CurrentRow.Cells["idpresentacion"].Value); this.tabControl1.SelectedIndex = 1; } private void ChkEliminar_CheckedChanged(object sender, EventArgs e) { if (chkEliminar.Checked) { this.dataListado.Columns[0].Visible = true; } else { this.dataListado.Columns[0].Visible = false; } } private void BtnEliminar_Click(object sender, EventArgs e) { try { DialogResult Opcion; Opcion = MessageBox.Show("Realmente desea eliminar los registros", "Sistema de ventas", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (Opcion == DialogResult.OK) { string Codigo; string Rpta = ""; foreach (DataGridViewRow row in dataListado.Rows) { if (Convert.ToBoolean(row.Cells[0].Value)) { Codigo = Convert.ToString(row.Cells[1].Value); Rpta = NArticulo.Eliminar(Convert.ToInt32(Codigo)); if (Rpta.Equals("OK")) { this.MensajeOk("Se eliminó el registro correctamente"); } else { this.MensajeError(Rpta); } } } this.Mostrar(); } } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } } private void BtnBuscarCategoria_Click(object sender, EventArgs e) { frmVistaCategoria_Articulo form = new frmVistaCategoria_Articulo(); form.ShowDialog(); } private void BtnImprimir_Click(object sender, EventArgs e) { FrmReporteArticulos frm = new FrmReporteArticulos(); frm.ShowDialog(); } private void frmArticulo_FormClosing(object sender, FormClosingEventArgs e) { _Instancia = null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoinsPositionSet : MonoBehaviour { public Transform midMainPosition; public Transform[] leftAndRightPositions; private GameController _gamecontroller; public bool onlyOnce = false; public void Set_GameController(GameController localgamecontroller) { _gamecontroller = localgamecontroller; } private void Start() { Assign_Gamecontroller_To_Children(); Assigning_Transform_To_Left_Right_Positions(); Assigning_Transform_To_Mid_Position(); Assign_Spawn_Points(); } private void Update() { Activate_Coins_After_Dissable(); } public void Activate_Child_Coins() { for (int i = 0; i < this.transform.childCount; i++) { this.transform.GetChild(i).gameObject.SetActive(true); this.transform.GetChild(i).transform.eulerAngles = new Vector3(0, 0, 0); } } public void Assign_Spawn_Points() { int localRandom = Random.Range(0, leftAndRightPositions.Length); this.transform.position = leftAndRightPositions[localRandom].position; } private void Assigning_Transform_To_Mid_Position() { midMainPosition = _gamecontroller.mainSpawnPoint; } private void Assigning_Transform_To_Left_Right_Positions() { for (int i = 0; i < leftAndRightPositions.Length; i++) { if (i == 0) { leftAndRightPositions[i] = _gamecontroller.leftSpawnPoint; } if (i == 1) { leftAndRightPositions[i] = _gamecontroller.middleSpawnPoint; } if(i == 2) { leftAndRightPositions[i] = _gamecontroller.rightSpawnPoint; } } } private void Assign_Gamecontroller_To_Children() { for (int i = 0; i < this.transform.childCount; i++) { this.transform.GetChild(i).GetComponent<CoinCollision>().Set_Gamecontroller(_gamecontroller); } } public void Disable_SpriteRenderer_For_Child() { for (int i = 0; i < transform.childCount; i++) { transform.GetChild(i).GetComponent<SpriteRenderer>().enabled = false; } } private void Enable_SpriteRenderer_For_Child() { for (int i = 0; i < transform.childCount; i++) { transform.GetChild(i).GetComponent<SpriteRenderer>().enabled = true; } } private void Activate_Coins_After_Dissable() { if (this.gameObject.active == true) { if (onlyOnce) { onlyOnce = false; Assign_Spawn_Points(); Enable_SpriteRenderer_For_Child(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.Entity { public class AdjustContractPriceItem:BaseEntity { public int AdjustContractPriceId { get; set; } public int ProductId { get; set; } /// <summary> /// 原售价 /// </summary> public decimal ContractPrice { get; set; } /// <summary> /// 调整价 /// </summary> public decimal AdjustPrice { get; set; } } }
using System.Collections.Generic; using IdentityServer4; using IdentityServer4.Models; namespace FR.IdentityServer.Infrastructure { public static class IdentityServerConfiguration { public static IEnumerable<IdentityResource> GetIdentityResources() { return new List<IdentityResource> { new IdentityResources.OpenId(), new IdentityResources.Email(), new IdentityResources.Profile(), }; } public static IEnumerable<ApiResource> GetApis() { return new List<ApiResource> { new ApiResource("FinanceManagerAPI", "Finance Manager service") }; } public static IEnumerable<Client> GetClients() { return new List<Client> { new Client() { ClientId = "spa", ClientName = "freelancer web app", AllowedGrantTypes = GrantTypes.Implicit, AllowAccessTokensViaBrowser = true, RedirectUris = {"http://localhost:4200/auth-callback"}, RequireConsent = false, PostLogoutRedirectUris = {"http://localhost:4200/"}, AllowedCorsOrigins = {"http://localhost:4200"}, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, IdentityServerConstants.StandardScopes.Email, "FinanceManagerAPI" } } }; } } }
using System; using MonoTouch.UIKit; using System.Threading.Tasks; using SignaturePad; namespace iPadPos { public class SignatureViewController : UIViewController { public Action<bool> HasSignature { get; set; } public SignatureViewController () { Title = "Please Sign"; EdgesForExtendedLayout = UIRectEdge.None; this.NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, (s, e) => { if(HasSignature != null) HasSignature(true); if(tcs != null) tcs.TrySetResult(true); }); this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Cancel, (s, e) => { if(HasSignature != null) HasSignature(false); if(tcs != null) tcs.TrySetResult(false); }); } public double Amount { set { view.Label.Text = value.ToString("C"); } } public override void LoadView () { View = new SigView (); } SigView view { get { return View as SigView; } } public SignaturePadView SignatureView { get{ return view.SignaturePadView; } } TaskCompletionSource<bool> tcs; public async Task<bool> GetSignature () { if (tcs == null) tcs = new TaskCompletionSource<bool> (); return await tcs.Task; } class SigView : UIView { public SignaturePadView SignaturePadView; public UILabel Label { get; set;} public SigView () { BackgroundColor = Color.DarkGray; Add(Label = new UILabel{ Font = UIFont.BoldSystemFontOfSize(60), TextAlignment = UITextAlignment.Center, TextColor = UIColor.White, Text = "$100", }); Label.SizeToFit(); Add(SignaturePadView = new SignaturePadView()); } public override void LayoutSubviews () { base.LayoutSubviews (); const float padding = 50f; var frame = Label.Frame; frame.X = 20; frame.Width = Bounds.Width - 40; frame.Y = padding; Label.Frame = frame; frame.Y = frame.Bottom + 10; frame.Height = Bounds.Height - (Frame.Y * 3); SignaturePadView.Frame = frame; } } } }
using AppLogic.Dto; using AppLogic.DtoCreate; using AppLogic.DtoUpdate; using AppLogic.Management; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace BeerShop.Controllers { public class BeerBottleController : ApiController { BeerBottleManager manager = new BeerBottleManager(); // GET: api/BeerBottle public List<ReadBeerBottle> Get() { return manager.GetAll(); } // GET: api/BeerBottle/5 public ReadBeerBottle Get(int id) { return manager.Get(id); } // POST: api/BeerBottle public void Post([FromBody]CreateBeerBottle create) { manager.Add(create); } // PUT: api/BeerBottle/5 public void Put(int id, [FromBody]UpdateBeerBottle update) { if(id == update.ID) { manager.Update(update); } } // DELETE: api/BeerBottle/5 public void Delete(int id) { manager.Remove(id); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Configy; using Configy.Containers; using Configy.Parsing; using Leprechaun.CodeGen; using Leprechaun.Execution; using Leprechaun.Filters; using Leprechaun.InputProviders; using Leprechaun.Logging; using Leprechaun.MetadataGeneration; using Leprechaun.TemplateReaders; using Leprechaun.Validation; using Newtonsoft.Json; namespace Leprechaun.Configuration { public class LeprechaunConfigurationBuilder : XmlContainerBuilder { private readonly XmlElement _configsElement; private readonly XmlElement _baseConfigElement; private readonly XmlElement _sharedConfigElement; private readonly string _configFilePath; private readonly ConfigurationImportPathResolver _configImportResolver; private IContainer _sharedConfig; private IContainer[] _configurations; public LeprechaunConfigurationBuilder(IContainerDefinitionVariablesReplacer variablesReplacer, XmlElement configsElement, XmlElement baseConfigElement, XmlElement sharedConfigElement, string configFilePath, ConfigurationImportPathResolver configImportResolver) : base(variablesReplacer) { Assert.ArgumentNotNull(variablesReplacer, nameof(variablesReplacer)); Assert.ArgumentNotNull(configsElement, nameof(configsElement)); Assert.ArgumentNotNull(baseConfigElement, nameof(baseConfigElement)); Assert.ArgumentNotNull(sharedConfigElement, nameof(sharedConfigElement)); _configsElement = configsElement; _baseConfigElement = baseConfigElement; _sharedConfigElement = sharedConfigElement; _configFilePath = configFilePath; _configImportResolver = configImportResolver; ProcessImports(); InitializeInputProvider(); } public virtual IContainer Shared { get { if (_sharedConfig == null) LoadSharedConfiguration(); return _sharedConfig; } } public virtual IContainer[] Configurations { get { if (_configurations == null) LoadConfigurations(); return _configurations; } } public string[] ImportedConfigFilePaths { get; protected set; } protected virtual void LoadConfigurations() { var parser = new XmlContainerParser(_configsElement, _baseConfigElement, new XmlInheritanceEngine()); var definitions = parser.GetContainers(); var configurations = GetContainers(definitions).ToArray(); foreach (var configuration in configurations) { // Assert that expected dependencies exist - and in the case of data stores are specifically singletons (WEIRD things happen otherwise) configuration.AssertSingleton(typeof(IFieldFilter)); configuration.AssertSingleton(typeof(ITemplatePredicate)); configuration.AssertSingleton(typeof(ITypeNameGenerator)); configuration.AssertSingleton(typeof(ITemplateReader)); configuration.Assert(typeof(ICodeGenerator)); // register the container with itself. how meta! configuration.Register(typeof(IContainer), () => configuration, true); } _configurations = configurations.ToArray(); } protected virtual void LoadSharedConfiguration() { var definition = new ContainerDefinition(_sharedConfigElement); try { var sharedConfiguration = GetContainer(definition); // Assert that expected dependencies exist - and in the case of data stores are specifically singletons (WEIRD things happen otherwise) sharedConfiguration.AssertSingleton(typeof(ITemplateMetadataGenerator)); sharedConfiguration.AssertSingleton(typeof(IArchitectureValidator)); sharedConfiguration.AssertSingleton(typeof(IInputProvider)); sharedConfiguration.Assert(typeof(ILogger)); _sharedConfig = sharedConfiguration; } catch (InvalidOperationException ex) { if (ex.Message.Contains("Leprechaun.InputProviders.Rainbow")) { new ConsoleLogger().Error("Unable to resolve dependency. If you are using Rainbow, ensure you have the /r switch in the command line arguments.", ex); } else { new ConsoleLogger().Error($"{ex.Message}.\n\nCheck your configuration files to make sure it is typed correctly. " + $"If so, ensure that the dlls are in the correct location. " + $"You may need to use the /p switch to specify this location", ex); } Environment.Exit(1); } } public void InitializeInputProvider() { Shared.Resolve<IInputProvider>().Initialize(this); } protected virtual void ProcessImports() { var imports = _configsElement.Attributes["import"]?.InnerText; if (imports == null) return; var allImportsGlobs = imports.Split(';'); var allImportsRepathedGlobs = allImportsGlobs.Select(glob => { // fix issues if "; " is used as a separator glob = glob.Trim(); // absolute path with drive letter, so use the path raw if (glob[0] == ':') return glob; // relative path (absolutize with root config file path as base) return Path.Combine(Path.GetDirectoryName(_configFilePath), glob); }); var allImportsFiles = allImportsRepathedGlobs .SelectMany(glob => _configImportResolver.ResolveImportPaths(glob)) .Concat(new[] {_configFilePath}) .ToList(); Queue<string> configsToProcess = new Queue<string>(allImportsFiles); while(configsToProcess.Count > 0) { var import = configsToProcess.Dequeue(); var xml = new XmlDocument(); XmlElement nodeToImport; if (Path.GetExtension(import) == ".json") { var xmlConfig = JsonConvert.DeserializeXmlNode(File.ReadAllText(import), "module"); nodeToImport = (XmlElement)xmlConfig.SelectSingleNode("/module/leprechaun")?.FirstChild; if (nodeToImport == null) { allImportsFiles.Remove(import); continue; } if (!nodeToImport.HasAttribute("name")) { var namespaceUri = xmlConfig.SelectSingleNode("/module/namespace")?.InnerText; if (string.IsNullOrEmpty(namespaceUri)) { throw new InvalidOperationException($"module does not have namespace: '{import}'"); } nodeToImport.SetAttribute("name", namespaceUri); } } else { xml.Load(import); nodeToImport = xml.DocumentElement; } var importedXml = _baseConfigElement.OwnerDocument.ImportNode(nodeToImport, true); _configsElement.AppendChild(importedXml); } // we'll use this to watch imports for changes later ImportedConfigFilePaths = allImportsFiles.ToArray(); } } }
using fileCrawlerWPF.Media; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fileCrawlerWPF.Filters { interface IFilter { bool Enabled { get; set; } Func<ProbeFile, object, bool> Func { get; } } }
using Backend.Model.DTO; using Backend.Model.PerformingExamination; using Backend.Service; using Backend.Service.ExaminationAndPatientCard; using GraphicalEditorServer.DTO; using GraphicalEditorServer.Mappers; using Microsoft.AspNetCore.Mvc; using Backend.Model.Exceptions; using System.Collections.Generic; using System.Collections.Generic; using System.Linq; namespace GraphicalEditorServer.Controllers { [Route("api/[controller]")] [ApiController] public class AppointmentController : ControllerBase { private readonly IFreeAppointmentSearchService _freeAppointmentSearchService; private readonly IScheduleAppointmenService _scheduleAppintmentService; private readonly IDoctorService _doctorService; private readonly IExaminationService _examinationService; public AppointmentController( IFreeAppointmentSearchService freeAppointmentSearchService, IScheduleAppointmenService scheduleAppintmentService, IDoctorService doctorService, IExaminationService examinationService) { _freeAppointmentSearchService = freeAppointmentSearchService; _scheduleAppintmentService = scheduleAppintmentService; _doctorService = doctorService; _examinationService = examinationService; } [HttpGet("{id}")] public IActionResult GetExaminationById(int id) { try { Examination examination = _examinationService.GetExaminationById(id); return Ok(ExaminationMapper.Examination_To_ExaminationDTO(examination)); } catch (DatabaseException e) { return StatusCode(500, e.Message); } catch (NotFoundException e) { return NotFound(e.Message); } } [HttpPost("schedule/")] public ActionResult ScheduleAppointmentByDoctor([FromBody] ExaminationDTO scheduleExaminationDTO) { Examination scheduleExamination = ExaminationMapper.ExmainationDTO_To_Examination(scheduleExaminationDTO); int idExamination = _scheduleAppintmentService.ScheduleAnAppointmentByDoctor(scheduleExamination); return Ok(idExamination); } [HttpDelete("deleteById/{id}")] public ActionResult DeleteExamination(int id) { _examinationService.CancelExamination(id); return Ok(); } [HttpPost("reschedule/")] public ActionResult ReScheduleAppointment([FromBody] RescheduleExaminationDTO rescheduleExaminationDTO) { Examination examinationForSchedule = ExaminationMapper.ExmainationDTO_To_Examination(rescheduleExaminationDTO.ExaminationForScheduleDTO); Examination examinationForReschedule = ExaminationMapper.ExmainationDTO_To_Examination(rescheduleExaminationDTO.ExaminationForRescheduleDTO); Examination shiftedExamination = ExaminationMapper.ExmainationDTO_To_Examination(rescheduleExaminationDTO.ShiftedExaminationDTO); _scheduleAppintmentService.ReScheduleAppointment(examinationForSchedule, examinationForReschedule, shiftedExamination); return Ok(); } [HttpPost] public ActionResult GetFreeAppointments(AppointmentSearchWithPrioritiesDTO appointmentDTO) { List<Examination> examinations = (List<Examination>)_freeAppointmentSearchService.SearchWithPriorities(appointmentDTO); examinations.ForEach(e => e.Doctor = _doctorService.GetDoctorByJmbg(e.DoctorJmbg)); List<ExaminationDTO> allExaminations = new List<ExaminationDTO>(); examinations.ForEach(e => allExaminations.Add(ExaminationMapper.Examination_To_ExaminationDTO(e))); return Ok(allExaminations); } [HttpPost("emergency")] public ActionResult GetEmergencyAppointments(AppointmentSearchWithPrioritiesDTO parameters) { _freeAppointmentSearchService.SetNewDateTimesForEmergency(parameters.InitialParameters); List<Examination> unchangedExaminations = (List<Examination>)_freeAppointmentSearchService.GetUnchangedAppointmentsForEmergency(parameters); if (unchangedExaminations.Count != 0) { List<EmergencyExaminationDTO> sortedAndAlignedExamination = GetSortedAndAlignedExaminations( new List<Examination>() { unchangedExaminations[0] }, new List<Examination>() { unchangedExaminations[0] } ); return Ok(sortedAndAlignedExamination); } unchangedExaminations.Clear(); unchangedExaminations = _freeAppointmentSearchService.GetOnlyAdequateAppointmentsForEmergency(parameters); List<Examination> shiftedExaminations = (List<Examination>)_freeAppointmentSearchService.GetShiftedAndSortedAppoinmentsForEmergency(parameters); List<EmergencyExaminationDTO> sortedAndAlignedExaminations = GetSortedAndAlignedExaminations(unchangedExaminations, shiftedExaminations); return Ok(sortedAndAlignedExaminations); } private List<EmergencyExaminationDTO> GetSortedAndAlignedExaminations(List<Examination> unchangedExaminations, List<Examination> shiftedExaminations) { List<EmergencyExaminationDTO> sortedExaminations = new List<EmergencyExaminationDTO>(); for (int i = 0; i < unchangedExaminations.Count; i++) { sortedExaminations.Add(new EmergencyExaminationDTO(unchangedExaminations[i], shiftedExaminations[i])); } sortedExaminations.OrderBy(e => e.ShiftedExamination.DateTime).ToList(); return sortedExaminations; } } }
using DChild.Gameplay; using DChild.Gameplay.Objects.Characters; using DChild.Gameplay.Player; using UnityEngine; public class PlayerCrouch : MonoBehaviour, ICrouch, IPlayerBehaviour { [SerializeField] private GroundMoveHandler m_moveHandler; private CharacterPhysics2D m_characterPhysics2D; private RaycastSensor m_headSensor; private Animator m_animator; private bool m_isCrouching; public bool Crouch(bool input) { if (input) { m_headSensor.enabled = true; //m_animator.SetBool("Crouch", true); m_isCrouching = true; } else if (m_isCrouching) { m_headSensor.enabled = true; var hit = m_headSensor.isDetecting; if (hit) { return m_isCrouching; } else { StopCrouch(); } } else { m_headSensor.enabled = false; } return m_isCrouching; } public void StopCrouch() { if (m_isCrouching) { //m_animator.SetBool("Crouch", false); m_isCrouching = false; } } public void Move(float direction) { if (m_isCrouching) { if (direction == 0) { m_moveHandler.Deccelerate(); } else { var moveDirection = direction > 0 ? Vector2.right : Vector2.left; m_moveHandler.SetDirection(moveDirection); m_moveHandler.Accelerate(); } } } public void UpdateVelocity() { var moveDirection = m_characterPhysics2D.velocity.x >= 0 ? Vector2.right : Vector2.left; m_moveHandler.SetDirection(moveDirection); } public void Initialize(IPlayer player) { m_characterPhysics2D = player.physics; m_moveHandler.SetPhysics(m_characterPhysics2D); m_headSensor = player.sensors.headSensor; m_animator = m_characterPhysics2D.GetComponentInChildren<Animator>(); m_headSensor.enabled = false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShrineTestController : MonoBehaviour { public ShrineGenerator Shrines; public ColorSchemer Colors; public int CurrentSeed { get; private set; } private void Start() { Generate(); } private void Update() { if (Input.GetKeyDown(KeyCode.Space)) Generate(); } public void Generate() { RandomizeSeed(); Colors.GenerateColors(CurrentSeed); Shrines.Generate(CurrentSeed); var pp = FindObjectOfType<PortalPool>(); if (pp != null) pp.Generate(CurrentSeed); pp.Uncover(); } private void RandomizeSeed() { CurrentSeed = Random.Range(int.MinValue, int.MaxValue); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using TinhLuongDAL; namespace TinhLuongBLL { public class QuyLuongBLL { QuyLuongDAL dal = new QuyLuongDAL(); public DataTable GetListQuyLuong(decimal thang, decimal nam, string donviId) { return dal.GetListQuyLuong(thang, nam, donviId); } public DataTable GetListQuyLuongByDonVi(decimal thang, decimal nam, string donviId) { return dal.GetListQuyLuongByDonVi(thang, nam, donviId); } public bool XoaQuyLuong(decimal thang, decimal nam, string donviId) { return dal.XoaQuyLuong(thang, nam, donviId); } public bool CapnhatQuyLuong(decimal thang, decimal nam, string donviId, decimal quygt, decimal quytt, decimal quythe, decimal chatluongthang, decimal htkh, decimal htcntt, decimal tylethe, decimal tylecuoc, decimal cstl, decimal stt, decimal quygt_kh, decimal quythe_kh) { return dal.CapnhatQuyLuong(thang, nam, donviId, quygt, quytt, quythe, chatluongthang, htkh, htcntt, tylethe, tylecuoc, cstl, stt, quygt_kh, quythe_kh); } public bool ThemMoiQuyLuong(decimal thang, decimal nam, string donviId, decimal quygt, decimal quytt, decimal quythe, decimal chatluongthang, decimal htkh, decimal htcntt, decimal tylethe, decimal tylecuoc, decimal cstl, decimal stt, decimal quygt_kh, decimal quythe_kh) { return dal.ThemMoiQuyLuong(thang, nam, donviId, quygt, quytt, quythe, chatluongthang, htkh, htcntt, tylethe, tylecuoc, cstl, stt, quygt_kh, quythe_kh); } } }
using UnityEngine; using UnityEngine.Events; namespace Script { public class GameEventListener : MonoBehaviour { public GameEvent gameEvent; public UnityEvent responseOfGameEvent; private void OnEnable() { gameEvent.Register(this); } private void OnDisable() { gameEvent.UnRegister(this); } public void FireEvent() { responseOfGameEvent.Invoke(); } } }
using log4net; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading; namespace Core.AsyncDecoderImpl { class DecodingQueueManager { private ConcurrentDictionary<string, AutoResetEvent> idToFinishEvent; private ConcurrentDictionary<string, DecodeResult> idToResult; private readonly ILog _logger; public DecodingQueueManager() { idToFinishEvent = new ConcurrentDictionary<string, AutoResetEvent>(); idToResult = new ConcurrentDictionary<string, DecodeResult>(); _logger = LogManager.GetLogger(typeof(DecodingQueueManager)); } public AutoResetEvent RegisterEvent(string id) { AutoResetEvent finishEvent = new AutoResetEvent(false); idToFinishEvent.AddOrUpdate(id, finishEvent, (idx, val) => finishEvent); return finishEvent; } public DecodeResult PopResult(string id) { DecodeResult result = null; bool success = idToResult.TryRemove(id, out result); if (!success) { _logger.Error($"Strange to find ${id} not found in idToResult."); return new DecodeResult { Id = id, Message = "DecodingQueueIdNotFound" }; } return result; } public Action<DecodeResult> DecodeResultSuccessHandler { get { return (result) => { if (result == null) { _logger.Error("null result"); return; } if (!idToFinishEvent.ContainsKey(result.Id)) { _logger.Error($"{result.Id} not in `idToFinishEvent`"); return; } var finishEvent = idToFinishEvent[result.Id]; idToResult.AddOrUpdate(result.Id, result, (idx, val) => result); finishEvent.Set(); }; } } public Action<StackExchange.Redis.RedisException> DecodeResultFailureHandler { get { return (e) => { _logger.Error(e.Message); }; } } } }
using System; using System.Collections.Generic; using System.Text; namespace Library_Task { public static class Variables { public static double SolveEquation(int firstNumber, int secondNumber) { if (firstNumber == secondNumber) { throw new ArgumentException("Число А не может быть равно B"); } else { double result = (5 * firstNumber + Math.Pow(secondNumber, 2)) / (secondNumber - firstNumber); return result; } } //// Другой вариант второй задачи - решение через передачи значения по ссылки. //public static (string firstOut, string secondOut) ChangeVariables(string firstInput, string secondInput) //{ // var changer = (firtsOut: "", secondOut: ""); // changer.firtsOut = secondInput; // changer.secondOut = firstInput; // return changer; //} public static void ChangeVariables(ref string firstInput, ref string secondInput) { string temp = firstInput; firstInput = secondInput; secondInput = temp; } public static int[] SolveDivisionAndShowRemainder(int firstNumber, int secondNumber) { if (secondNumber == 0) { throw new ArgumentException("Второе число не может быть нулем."); } int[] result = new int[2]; result[0] = firstNumber / secondNumber; result[1] = firstNumber % secondNumber; return result; } public static double GetLinearEquation(double firstNumber, double secondNumber, double thirdNumber) { if (firstNumber == 0) { throw new ArgumentException("Первый коэфициент (А) линейного уравнения не должно быть 0."); } double result = (thirdNumber - secondNumber) / firstNumber; return result; } public static string ShowLinearEquation(double a, double b, double c, double d) { if (a == c) { throw new ArgumentException("Числа a и c не должны быть равны."); } var k = (b - d) / (a - c); var s = d - k * c; return $"Y={k}x + ({s})"; } } }
namespace com.Sconit.Utility.Report.Operator { using System; using System.Collections.Generic; using System.Linq; using System.Text; using com.Sconit.Entity.ORD; using com.Sconit.Entity; using com.Sconit.PrintModel.ORD; public class RepORDProductFIOrderOperator : RepTemplate1 { public RepORDProductFIOrderOperator() { //明细部分的行数 this.pageDetailRowCount = 25; //列数 1起始 this.columnCount = 7; //报表头的行数 1起始 this.headRowCount = 8; //报表尾的行数 1起始 this.bottomRowCount = 1; } /** * 填充报表 * * Param list [0]OrderHead * Param list [0]IList<OrderDetail> */ protected override bool FillValuesImpl(String templateFileName, IList<object> list) { try { if (list == null || list.Count < 2) return false; PrintOrderMaster orderHead = (PrintOrderMaster)(list[0]); IList<PrintOrderDetail> orderDetails = (IList<PrintOrderDetail>)(list[1]); orderDetails = orderDetails.OrderBy(o => o.Sequence).ThenBy(o => o.Item).ToList(); if (orderHead == null || orderDetails == null || orderDetails.Count == 0) { return false; } this.barCodeFontName = this.GetBarcodeFontName(0, 4); this.CopyPage(orderDetails.Count); //Get Remark for head area orderHead.remark = orderDetails.ToList().First().Remark; this.FillHead(orderHead); int pageIndex = 1; int rowIndex = 0; int rowTotal = 0; foreach (PrintOrderDetail orderDetail in orderDetails) { //"成品物料号 FG Item Code" this.SetRowCell(pageIndex, rowIndex, 0, orderDetail.Item); //"描述Description" this.SetRowCell(pageIndex, rowIndex, 1, orderDetail.ItemDescription); //"单位Unit" this.SetRowCell(pageIndex, rowIndex, 2, orderDetail.Uom); //"包装UC" this.SetRowCell(pageIndex, rowIndex, 3, orderDetail.UnitCount.ToString("0.########")); //"计划数Dmd Qty" this.SetRowCell(pageIndex, rowIndex, 4, orderDetail.OrderedQty.ToString("0.########")); //收货数---Close,Complete,Cancel显示 if (orderHead.Status == 3 || orderHead.Status == 4 || orderHead.Status == 5) { this.SetRowCell(pageIndex, rowIndex, 5, orderDetail.ReceivedQty.ToString("0.##")); } //备注 this.SetRowCell(pageIndex, rowIndex, 6, orderDetail.Remark); //"合格数Conf Qty" //this.SetRowCell(pageIndex, rowIndex, 5, string.Empty); //"不合格数NC Qty" //this.SetRowCell(pageIndex, rowIndex, 6, string.Empty); //"废品数Scrap Qty" //this.SetRowCell(pageIndex, rowIndex, 7, string.Empty); //"收货人Receiver" //this.SetRowCell(pageIndex, rowIndex, 8, string.Empty); // "收货日期Rct Date" //this.SetRowCell(pageIndex, rowIndex, 9, string.Empty); if (this.isPageBottom(rowIndex, rowTotal))//页的最后一行 { pageIndex++; rowIndex = 0; } else { rowIndex++; } rowTotal++; } this.sheet.DisplayGridlines = false; this.sheet.IsPrintGridlines = false; } catch (Exception) { return false; } return true; } /* * 填充报表头 * * Param repack */ private void FillHead(PrintOrderMaster orderHead) { #region 报表头 if (orderHead.SubType == 1) { this.SetRowCell(1, 3, "退货"); } //this.SetRowCell(pageIndex, 0, 4, orderHead.Sequence.ToString()); //工单号码Order code string orderCode = Utility.BarcodeHelper.GetBarcodeStr(orderHead.OrderNo, this.barCodeFontName); this.SetRowCell(0, 4, orderCode); this.SetRowCell(1, 4, orderHead.OrderNo); // "生产线:Prodline:" //Flow flow = this.flowMgr.LoadFlow(orderHead.Flow); this.SetRowCell(2, 1, orderHead.FlowDescription + "(" + orderHead.Flow + ")"); //"生产班组:Shift:" this.SetRowCell(2, 4, orderHead.Shift == null ? string.Empty : orderHead.Shift); //"发单人:Issuer:" this.SetRowCell(3, 1, orderHead.CreateUserName); //"交货地点:Shipto:" this.SetRowCell(3, 4, orderHead.PartyToName); //开始时间 this.SetRowCell(4, 1, orderHead.StartTime.ToString("yyyy-MM-dd HH:mm")); //结束时间 this.SetRowCell(4, 4, orderHead.WindowTime.ToString("yyyy-MM-dd HH:mm")); //"注意事项:Remarks:" this.SetRowCell(5, 1, orderHead.Dock); //"联系电话:Tel:" //this.SetRowCell(pageIndex, 6, 1, string.Empty); // "生产单号:No. PO:" //this.SetRowCell(pageIndex, 3, 7, orderHead.OrderNo); //"交货日期:Deli. Date:" //this.SetRowCell(pageIndex, 4, 7, orderHead.WindowTime.ToString("yyyy-MM-dd")); //"发出日期:Release Date:" //this.SetRowCell(pageIndex, 4, 1, orderHead.CreateDate.ToString("yyyy-MM-dd hh:mm")); //"窗口时间:Win Time:" //this.SetRowCell(pageIndex, 5, 7, orderHead.WindowTime.ToString("HH:mm")); //正常 紧急 返工 //if ((CodeMaster.OrderPriority)orderHead.Priority == CodeMaster.OrderPriority.Urgent) //{ // this.SetRowCell(pageIndex, 4, 2, "■"); //} //else //{ // this.SetRowCell(pageIndex, 3, 2, "■"); //} ////返工 //if ((CodeMaster.OrderSubType)orderHead.SubType == CodeMaster.OrderSubType.Return) //{ // this.SetRowCell(pageIndex, 5, 2, "■"); //} #endregion } /** * 需要拷贝的数据与合并单元格操作 * * Param pageIndex 页号 */ public override void CopyPageValues(int pageIndex) { //this.SetMergedRegionColumn(pageIndex, 0, 2, 0, 3); //this.SetMergedRegionColumn(pageIndex, 1, 2, 1, 3); ////合并整页的明细 //int i; //for (i = 0; i < this.pageDetailRowCount; i++) //{ // this.SetMergedRegionColumn(pageIndex, i, 2, i, 3); //} this.CopyCell(pageIndex, 33, 0, "A34"); this.CopyCell(pageIndex, 33, 2, "C34"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace EurogamerCommentsApi { [DataContract] public class Comment { #region Private members private string _dateTimeString; #endregion Private members #region Public properties [DataMember(IsRequired = true, Name = "id")] public uint Id { get; set; } [DataMember(IsRequired = true, Name = "u")] public string Username { get; set; } [DataMember(IsRequired = true, Name = "uid")] public uint UserId { get; set; } [DataMember(IsRequired = true, Name = "p")] public string Text { get; set; } [DataMember(IsRequired = true, Name = "t")] public string DateTimeString { get { return _dateTimeString; } set { if (_dateTimeString == value) return; _dateTimeString = value; DateTime = DateTimeFromDateTimeString(_dateTimeString); } } [IgnoreDataMember] public DateTime DateTime { get; set; } #endregion Public properties private static readonly Regex _dateTimeStringRegex = new Regex(@"^(\d+) (second|minute|hour|day|week|month)[s]? ago$", RegexOptions.Compiled); internal static DateTime DateTimeFromDateTimeString(string dateTimeString) { var now = DateTime.Now; var match = _dateTimeStringRegex.Match(dateTimeString); var delta = ushort.Parse(match.Groups[1].Value); var unit = match.Groups[2].Value; switch (unit) { case "second": return now.AddSeconds(delta * -1); case "minute": return now.AddSeconds(delta * 60 * -1); case "hour": return now.AddSeconds(delta * 60 * 60 * -1); case "day": return now.AddSeconds(delta * 60 * 60 * 24 * -1); case "week": return now.AddSeconds(delta * 60 * 60 * 24 * 7 * -1); case "month": return now.AddSeconds(delta * 60 * 60 * 24 * 7 * 30 * -1); default: throw new Exception($"Cannot parse datetimestring: {dateTimeString}"); } } public override string ToString() { return $@"{Id} {Username} ""{Text}"""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _36_Lesson { class Program { static void Main(string[] args) { Console.WriteLine("Enter your weight:"); double weight = double.Parse(Console.ReadLine()); Console.WriteLine("Enter your height:"); double height = double.Parse(Console.ReadLine()); Console.Clear(); double bodyMassIndex = weight / weight * height; bool isTooLow = bodyMassIndex <= 18.5; bool isNormal = bodyMassIndex >18.5 && bodyMassIndex < 25; bool isAboveNormal = bodyMassIndex >= 25 && bodyMassIndex <= 30; bool isTooFat = bodyMassIndex > 30; bool isFat = isAboveNormal || isTooFat; Console.WriteLine(bodyMassIndex); if (isFat) { Console.WriteLine("You'd better lose some weight"); } else { Console.WriteLine("You're in a good shape"); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; namespace IL.Core.BL.Managers { public static class ImageManager { static ImageManager () { } public static IList<Image> GetImages () { return new List<Image>(IL.Core.DAL.ImageManager.GetImages()); } } }
using System.Collections; using System.Collections.Generic; using System.Net.Mime; using System.Reflection; using UnityEngine; using UnityEngine.UI; public class ShowEndStats : MonoBehaviour { private GameObject _gameManager; private GameObject _scoreCanvas; private GameObject _EndscreenCanvas; private Score _score; private AdvisersManager _advisersManager; private Text _scoreText; private Text _adviserText; void Awake () { _gameManager = GameObject.Find("Game_Manager"); _score = _gameManager.GetComponent<Score>(); _advisersManager = _gameManager.GetComponent<AdvisersManager>(); _adviserText = GameObject.FindGameObjectWithTag("Advisetext").GetComponent<Text>(); _scoreText = GameObject.FindGameObjectWithTag("Endscore").GetComponent<Text>(); _scoreCanvas = GameObject.FindGameObjectWithTag("ScoreCanvas"); _EndscreenCanvas = GameObject.FindGameObjectWithTag("Endscreen"); _EndscreenCanvas.SetActive(false); } public void ActiveStats() { _scoreText.text = _score._Score.ToString(); _adviserText.text = _advisersManager._adviserLeft.ToString(); _EndscreenCanvas.SetActive(true); _scoreCanvas.SetActive(false); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static FactoryDesignPattern.Constant; namespace FactoryDesignPattern { public class DatabaseFactory { public IDatabase GetDatabase(eDbType edbType) { IDatabase idb = null; switch (edbType) { case eDbType.Sql: idb = new SqlDatabase(); break; case eDbType.MsAccess: idb = new MsAccessDatabase(); break; case eDbType.Oracle: idb = new OracleDatabase(); break; default: break; } return idb; } } }
using Tomelt.Events; namespace Tomelt.Tokens { public interface ITokenProvider : IEventHandler { void Describe(DescribeContext context); void Evaluate(EvaluateContext context); } }
 using System; using System.Diagnostics; using Jypeli.Assets; using Jypeli.Rendering; using Matrix = System.Numerics.Matrix4x4; using Vector3 = System.Numerics.Vector3; namespace Jypeli { /// <summary> /// Draws simple shapes efficiently. /// Draw() calls should be made only between Begin() and End() calls. /// Other drawing operations can be done between Begin() and /// End(). /// </summary> /// <remarks> /// The shapes are added to a buffer. Only when /// the buffer is full, a draw call is made to the graphics device. /// </remarks> internal class ShapeBatch { VertexPositionColorTexture[] vertexBuffer; /// <summary> /// Buffer for index values to the vertex buffer. /// </summary> /// <remarks> /// Since some low-end graphics cards don't support 32-bit indices, /// 16-bit indices must be used. Which is fine, as it means less traffic /// to the graphics card. We just have to make sure that the buffer size /// isn't larger than 16000. /// </remarks> uint[] indexBuffer; IShader shader; Matrix matrix; //SamplerState samplerState; uint iVertexBuffer = 0; uint iIndexBuffer = 0; bool beginHasBeenCalled = false; public bool LightingEnabled = true; private PrimitiveType primitivetype; private IShader customShader; public void Initialize() { shader = Graphics.BasicColorShader; int vertexBufferSize = Game.GraphicsDevice.BufferSize; vertexBuffer = new VertexPositionColorTexture[vertexBufferSize]; indexBuffer = new uint[vertexBufferSize * 2]; } public void Begin(ref Matrix matrix, PrimitiveType p = PrimitiveType.OpenGlTriangles, IShader shader = null) { Debug.Assert(!beginHasBeenCalled); beginHasBeenCalled = true; primitivetype = p; this.matrix = matrix; iVertexBuffer = 0; iIndexBuffer = 0; customShader = shader; } public void End() { Debug.Assert(beginHasBeenCalled); Flush(); beginHasBeenCalled = false; } private void Flush() { if (iIndexBuffer != 0) { if (customShader is null) { shader.Use(); shader.SetUniform("world", matrix * Graphics.ViewProjectionMatrix); } else { customShader.Use(); customShader.SetUniform("world", matrix * Graphics.ViewProjectionMatrix); } Game.GraphicsDevice.DrawIndexedPrimitives( primitivetype, vertexBuffer, iIndexBuffer, indexBuffer); } iVertexBuffer = 0; iIndexBuffer = 0; } public void Draw(ShapeCache cache, Color color, Vector position, Vector size, float angle) { if ((iVertexBuffer + cache.Vertices.Length) > vertexBuffer.Length || (iIndexBuffer + cache.Triangles.Length * 3) > indexBuffer.Length) { Flush(); } Matrix matrix = Matrix.CreateScale((float)size.X, (float)size.Y, 1f) * Matrix.CreateRotationZ(angle) * Matrix.CreateTranslation((float)position.X, (float)position.Y, 0); uint startIndex = iVertexBuffer; for (int i = 0; i < cache.Vertices.Length; i++) { Vector v = cache.Vertices[i]; vertexBuffer[iVertexBuffer++] = new VertexPositionColorTexture(Vector3.Transform(new Vector3((float)v.X, (float)v.Y, 0), matrix), color, Vector.Zero); } for (int i = 0; i < cache.Triangles.Length; i++) { indexBuffer[iIndexBuffer++] = (uint)cache.Triangles[i].i1 + startIndex; indexBuffer[iIndexBuffer++] = (uint)cache.Triangles[i].i2 + startIndex; indexBuffer[iIndexBuffer++] = (uint)cache.Triangles[i].i3 + startIndex; } } public void DrawOutlines(ShapeCache cache, Color color, Vector position, Vector size, float angle) { if ((iVertexBuffer + cache.Vertices.Length) > vertexBuffer.Length || (iIndexBuffer + cache.Triangles.Length) > indexBuffer.Length) { Flush(); } Matrix matrix = Matrix.CreateScale((float)size.X, (float)size.Y, 1f) * Matrix.CreateRotationZ(angle) * Matrix.CreateTranslation((float)position.X, (float)position.Y, 0); uint startIndex = iVertexBuffer; for (int i = 0; i < cache.Vertices.Length; i++) { Vector v = cache.Vertices[i]; vertexBuffer[iVertexBuffer++] = new VertexPositionColorTexture(Vector3.Transform(new Vector3((float)v.X, (float)v.Y, 0), matrix), color, Vector.Zero); } for (int i = 0; i < cache.OutlineIndices.Length - 1; i++) { indexBuffer[iIndexBuffer++] = (uint)cache.OutlineIndices[i] + startIndex; indexBuffer[iIndexBuffer++] = (uint)cache.OutlineIndices[i + 1] + startIndex; } indexBuffer[iIndexBuffer++] = (uint)cache.OutlineIndices[^1] + startIndex; indexBuffer[iIndexBuffer++] = (uint)cache.OutlineIndices[0] + startIndex; } } }
using System.Collections.Generic; namespace gView.Framework.Data { abstract public class IDSetTemplate<T> { abstract public List<T> IDs { get; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Collections.Generic; public enum PlacementArea { None, Villain, Door, Key } public class GameManager : MonoBehaviour { public DBManager dbManager; List<InventoryItem> inventoryItems; public InventoryItem selectedItem; public SpriteRenderer followSprite; Transform followSpriteTransform; public RectTransform inventoryContents; public MeshTileMap meshTileMap; Map tileMap; Vector3 mouseToWorld; public float inputZ = 15f; public GameObject helpPopup; public GameObject showHelpButton; bool allowSpawn = false; bool anItemIsHovered = false; bool itemMoveIsInProcess = false; public LevelTimer timer; public SelectedItemPopup selectedItemPopup; public SpawnedItemHoverPopup itemPopup; public VictoryMenu victoryMenu; public GameOverMenu gameOverMenu; public bool noSelection = true; public AudioSource minionDie; public AudioSource pickup; public GameObject messageContainer; public Text txtMessage; public GameObject endGameMenu; // Use this for initialization void Start () { //meshTileMap.SetMap(tmxMap); //meshTileMap.GenerateMesh(); meshTileMap.GenerateMesh(dbManager.GetLevel()); if (dbManager.HelpShouldBeShown()) { helpPopup.SetActive(true); } else { showHelpButton.SetActive(true); } } public void MapGenerationCallBack(MapData mapData) { inventoryItems = dbManager.GetInventory(mapData.villains, mapData.gold); for (int i = 0; i < inventoryItems.Count; i += 1) { InventoryItem item = inventoryItems[i]; item.gameManager = this; GameObject newInventoryItem = Instantiate(item).gameObject; newInventoryItem.transform.SetParent(inventoryContents, false); RectTransform rectTransform = newInventoryItem.GetComponent<RectTransform>(); float x = rectTransform.anchoredPosition.x + rectTransform.sizeDelta.x * i + 20f * i; float y = rectTransform.anchoredPosition.y; if (i > 1) { y -= rectTransform.sizeDelta.y * i + 20f * i; } rectTransform.anchoredPosition = new Vector2(x, y); inventoryItems[i] = newInventoryItem.GetComponent<InventoryItem>(); } } public void EndGame() { // endGameMenu.SetActive(true); // Debug.Log("Game end!"); } public void HideHelp(){ dbManager.HideHelp(); } public bool SelectInventoryItem(InventoryItem item) { if (tileMap == null) { tileMap = meshTileMap.mapData.tileMap; } // Debug.Log(item.itemCount); if (selectedItem == null) { selectedItem = item; followSprite.sprite = selectedItem.image.sprite; followSprite.enabled = true; followSpriteTransform = followSprite.GetComponent<Transform>(); if (item.placementArea == PlacementArea.Villain) { meshTileMap.SelectGround(); } if (itemPopup.isActivated) { itemPopup.DeActivate(); } if (!itemMoveIsInProcess) { item.UpdateCount(-1); } selectedItemPopup.Show(selectedItem.itemName, selectedItem.image.sprite); noSelection = false; return true; } else if (selectedItem == item) { CancelItemSelection(); } return false; } public void LevelFinished() { if (timer.enoughTime) { ShowVictoryMenu(); } else { ShowGameOverMenu(); } timer.StopTimer(); } public void ShowVictoryMenu() { victoryMenu.gameObject.SetActive(true); } public void ShowGameOverMenu() { gameOverMenu.gameObject.SetActive(true); } public void NextLevel() { dbManager.NextLevel(); Application.LoadLevel(1); } public void RestartLevel() { Application.LoadLevel(1); } public void OpenMainMenu() { Application.LoadLevel(0); } public void DisplayMessage(string message) { messageContainer.SetActive(true); txtMessage.text = message; } public void HideMessage() { messageContainer.SetActive(false); } public void StartLevel() { bool allowStart = true; foreach(InventoryItem item in inventoryItems){ if (item.itemCount != 0) { allowStart = false; } } if (allowStart) { Hero hero = GameObject.FindGameObjectWithTag("Hero").GetComponent<Hero>(); if (hero == null) { Debug.Log("ERROR: no hero!"); } hero.StartMoving(); timer.StartTimer(); } else { DisplayMessage("Place all the items first!"); } } // if user cancels use (esc key, click same item) public void CancelItemSelection() { itemMoveIsInProcess = false; if (selectedItem != null) { selectedItem.UpdateCount(1); UnselectItem(); } if (itemPopup != null && itemPopup.isActivated) { itemPopup.DeActivate(); } // Debug.Log("Stop item move!"); } // if user places item public void UseItem() { InventoryItem cachedItem = selectedItem; UnselectItem(); if (cachedItem.itemCount > 0 && !itemMoveIsInProcess) { SelectInventoryItem(cachedItem); } else { //Debug.Log("Stop item move!"); itemMoveIsInProcess = false; } } // generic unselection of selected item public void UnselectItem() { if (selectedItem.placementArea == PlacementArea.Villain) { meshTileMap.UnselectGround(); } selectedItem = null; followSprite.enabled = false; selectedItemPopup.Hide(); noSelection = true; } // when player hovers over spawned item public void HoverOverSpawnedItem(SpawnedItemBase spawnedItem) { anItemIsHovered = true; } public void ClickSpawnedItem(SpawnedItemBase spawnedItem) { itemPopup.Activate(spawnedItem.itemName, spawnedItem); } public void HoverOverSpawnedItemEnd() { //Debug.Log("End hover"); anItemIsHovered = false; } public bool RemoveItemThroughHoverPopup(string itemName, SpawnedItemBase itemOnGround) { foreach (InventoryItem item in inventoryItems) { if (item.itemName == itemName) { item.UpdateCount(1); return true; } } return false; } public bool SelectInventoryItemThroughHoverPopup(string itemName, SpawnedItemBase itemOnGround) { foreach (InventoryItem item in inventoryItems) { if (item.itemName == itemName) { // Debug.Log("START item move!"); itemMoveIsInProcess = true; meshTileMap.SelectComeBack(); SelectInventoryItem(item); return true; } } return false; } // Update is called once per frame void Update () { if (selectedItem != null) { mouseToWorld = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, inputZ)); // Debug.Log(Input.mousePosition + " -> " + mouseToWorld); followSpriteTransform.position = new Vector3(mouseToWorld.x, followSpriteTransform.position.y, mouseToWorld.z); if (Input.GetMouseButtonUp(0) && !anItemIsHovered) { if (selectedItem.placementArea == PlacementArea.Villain) { // if mouse is on top of placement area (this time meshTileMap) if (meshTileMap.isHovering) { allowSpawn = true; } } if (allowSpawn) { float x = followSpriteTransform.position.x; float z = followSpriteTransform.position.z; // SNAP TO GRID float newx = Mathf.Round(x); if (x - newx > 0) { newx += 0.5f; } else { newx -= 0.5f; } float newz = Mathf.Round(z); if (z - newz > 0) { newz += 0.5f; } else { newz -= 0.5f; } GameObject spawnedObject = (GameObject)Instantiate(selectedItem.prefab, new Vector3(newx, followSpriteTransform.position.y, newz), followSpriteTransform.rotation); SpawnedItemBase spawnedItem = spawnedObject.GetComponent<SpawnedItemBase>(); MapNode testNode = tileMap.GetNodeNormalized(newx, newz); spawnedItem.Init(this, selectedItem.itemName, testNode); //Debug.Log((int)(newx) + ", " + (int)(newz) + " -> " + testNode.x + ", " + testNode.y); spawnedItem.transform.SetParent(followSpriteTransform.parent, true); UseItem(); allowSpawn = false; } } } if (Input.GetKeyUp(KeyCode.Escape)) { CancelItemSelection(); } if (Input.GetKeyUp(KeyCode.Space)) { StartLevel(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using RabbitMQ.Client; using Spring.Context.Support; using Spring.Messaging.Amqp.Rabbit.Core; using Spring.RabbitQuickStart.Server.Gateways; namespace Spring.RabbitQuickStart.Server { class Program { static void Main(string[] args) { try { // Using Spring's IoC container ContextRegistry.GetContext(); Spring.Messaging.Amqp.Rabbit.Listener.SimpleMessageListenerContainer container = ContextRegistry.GetContext().GetObject("MessageListenerContainer") as Spring.Messaging.Amqp.Rabbit.Listener.SimpleMessageListenerContainer; container.Start(); Console.Out.WriteLine("Server listening..."); IMarketDataService marketDataService = ContextRegistry.GetContext().GetObject("MarketDataGateway") as MarketDataServiceGateway; ThreadStart job = new ThreadStart(marketDataService.SendMarketData); Thread thread = new Thread(job); thread.Start(); Console.Out.WriteLine("--- Press <return> to quit ---"); Console.ReadLine(); } catch (Exception e) { Console.Out.WriteLine(e); Console.Out.WriteLine("--- Press <return> to quit ---"); Console.ReadLine(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Net; using System.Web.Mvc; using Pe.GyM.Security.Web.Session; using Pe.Stracon.Politicas.Aplicacion.Core.ServiceContract; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General; using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General; using Pe.Stracon.SGC.Aplicacion.Core.ServiceContract; using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual; using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual; using Pe.Stracon.SGC.Infraestructura.Core.Context; using Pe.Stracon.SGC.Presentacion.Core.Controllers.Base; using Pe.Stracon.SGC.Presentacion.Core.Helpers; using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Contractual.BandejaContrato; using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual; using Pe.Stracon.SGC.Aplicacion.Core.Base; using Pe.Stracon.SGC.Cross.Core.Base; using Pe.Stracon.SGC.Presentacion.Core.ViewModel.Base; using Pe.Stracon.SGC.Presentacion.Recursos.Base; using Pe.Stracon.SGC.Application.Core.ServiceContract; using Pe.GyM.Security.Web.Filters; using Pe.Stracon.SGC.Cross.Core.Util; using Pe.GyM.Security.Account.Model; using Pe.GyM.Security.Account.SRASecurityService; using System.Configuration; namespace Pe.Stracon.SGC.Presentacion.Core.Controllers.Contractual { /// <summary> /// Controladora de Bandeja Contrato /// </summary> /// <remarks> /// Creación: GMD 20150318 /// Modificación: /// </remarks> public class BandejaContratoController : GenericController { #region Parámetros /// <summary> /// Servicio de manejo de parametro valor /// </summary> public IPoliticaService politicaService { get; set; } /// <summary> /// Servicio de unidad operativa /// </summary> public IUnidadOperativaService unidadOperativaService { get; set; } /// <summary> /// Servicio de Contratos /// </summary> public IContratoService contratoService { get; set; } /// <summary> /// Servicio de trabajadores /// </summary> public ITrabajadorService trabajadorService { get; set; } /// <summary> /// Interfaz de comunicación son los servidores SharePoint. /// </summary> public ISharePointService sharePointService { get; set; } /// <summary> /// Interface para obtener el entorno de la aplicación. /// </summary> public IEntornoActualAplicacion entornoAplicacion { get; set; } /// <summary> /// Servicio de manejo de flujo de aprobación /// </summary> public IFlujoAprobacionService flujoAprobacionService { get; set; } #endregion #region Vistas /// /// <summary> /// Muestra la vista principal /// </summary> /// <returns>Vista principal de la opción</returns> public ActionResult Index() { var UsuarioSesion = HttpGyMSessionContext.CurrentAccount(); var ListaTrabajador = trabajadorService.BuscarTrabajador(new TrabajadorRequest() { CodigoIdentificacion = UsuarioSesion.Alias }); var listaUOResponsable = contratoService.ListarUnidadOperativaResponsable(Guid.Parse(ListaTrabajador.Result[0].CodigoTrabajador)); List<Guid?> lstUOBuscar = new List<Guid?>(); foreach (var item in listaUOResponsable.Result) { lstUOBuscar.Add(item.CodigoUnidadOperativa); } var ListaUOs = unidadOperativaService.ListarUnidadesOperativas(lstUOBuscar); // = unidadOperativaService.ListarUnidadesOperativasPorResponsable(UsuarioSesion.Alias).Result; //var ListaTipoServicio = politicaService.ListarTipoServicio(); var ListaTipoServicio = retornaTipoServicio(); //var ListaTipoRequerimiento = politicaService.ListarTipoRequerimiento(); var ListaTipoRequerimiento = retornaTipoRequerimiento(); BandejaContratoBusqueda modelo = new BandejaContratoBusqueda(ListaUOs.Result, ListaTipoServicio, ListaTipoRequerimiento); modelo.ListaEstadio.Add(new SelectListItem() { Value = string.Empty, Text = GenericoResource.EtiquetaTodos }); modelo.ListaEstadio.AddRange(flujoAprobacionService.BuscarFlujoAprobacionEstadioDescripcion(new FlujoAprobacionEstadioRequest()).Result.Select(x => new SelectListItem() { Text = x.Descripcion, Value = x.Descripcion }).ToList()); if (ListaTrabajador.Result != null && ListaTrabajador.Result.Count > 0) { modelo.CodigoResponsable = Guid.Parse(ListaTrabajador.Result[0].CodigoTrabajador); } else { modelo.CodigoResponsable = Guid.Empty; } modelo.ControlPermisos = Utilitario.ObtenerControlPermisos(HttpGyMSessionContext.CurrentAccount(), "/Contractual/BandejaContrato/"); return View(modelo); } /// <summary> /// Muestra la vista Observaciones /// </summary> /// <returns>La vista Observación</returns> public ActionResult Observaciones(ContratoResponse prm) { ViewBag.CodigoTrabajador = retornaCodigoTrabajadorSession(); ViewBag.CodigoDeContrato = prm.CodigoContrato; ViewBag.NumeroContrado = prm.NumeroContrato; ViewBag.NombreUO = prm.NombreUnidadOperativa; ViewBag.NombreTipoServicio = prm.NombreTipoServicio; ViewBag.NombreTipoRequerimiento = prm.NombreTipoRequerimiento; ViewBag.NombreProveedor = prm.NombreProveedor; ViewBag.FechaCreacion = prm.FechaIngreso; ViewBag.CodigoContratoEstadio = prm.CodigoContratoEstadio; Session.Remove(DatosConstantes.Sesiones.SessionParrafoContrato); if (prm.CodigoContrato != null)//Llenamos el session { obtenerSessionParrafosPorContrato(new Guid(prm.CodigoContrato.ToString())); } ViewBag.ObsPorResponder = RetornaCantidadObservacionesResponder((Guid)prm.CodigoContratoEstadio); ViewBag.ControlPermisos = Utilitario.ObtenerControlPermisos(HttpGyMSessionContext.CurrentAccount(), "/Contractual/BandejaContrato/"); return View(); } /// <summary> /// Muestra la vista Consultas /// </summary> /// <returns>Vista Consulta</returns> public ActionResult Consultas(ContratoResponse prm) { ViewBag.CodigoTrabajador = retornaCodigoTrabajadorSession(); ViewBag.CodigoDeContrato = prm.CodigoContrato; ViewBag.NumeroContrado = prm.NumeroContrato; ViewBag.CodigoFlujoAprobacion = prm.CodigoFlujoAprobacion; ViewBag.NombreUO = prm.NombreUnidadOperativa; ViewBag.NombreTipoServicio = prm.NombreTipoServicio; ViewBag.NombreTipoRequerimiento = prm.NombreTipoRequerimiento; ViewBag.NombreProveedor = prm.NombreProveedor; ViewBag.FechaCreacion = prm.FechaIngreso; ViewBag.CodigoContratoEstadio = prm.CodigoContratoEstadio; ViewBag.ControlPermisos = Utilitario.ObtenerControlPermisos(HttpGyMSessionContext.CurrentAccount(), "/Contractual/BandejaContrato/"); Session.Remove(DatosConstantes.Sesiones.SessionParrafoContrato); if (prm.CodigoContrato != null)//Llenamos el session { obtenerSessionParrafosPorContrato(new Guid(prm.CodigoContrato.ToString())); } return View(); } #endregion #region Vistas Parciales /// <summary> /// Muestra la vista Formulario Observaciones /// </summary> /// <returns>Vista Parcial de Formulario Observacion</returns> public ActionResult FormularioObservaciones(ListadoContratoRequest contratoRequest) { var contrato = contratoService.BuscarListadoContrato(contratoRequest).Result.FirstOrDefault(); var documentoContrato = new ContratoDocumentoResponse(); if (!Convert.ToBoolean(contrato.IndicadorAdhesion)) { documentoContrato = contratoService.DocumentosPorContrato(contrato.CodigoContrato.Value).Result.FirstOrDefault(); } var modelo = new ObservacionesFormulario(contrato, documentoContrato); return PartialView(modelo); } /// <summary> /// Muestra la vista Formulario Responder Observacion /// </summary> /// <returns>Vista Parcial de Formulario Responder Observacion</returns> public ActionResult FormularioResponderObservacion(Guid codigoContratoEstadioObservacion, Guid codigoContrato, string TipoVista) { var contrato = contratoService.BuscarListadoContrato(new ListadoContratoRequest() { CodigoContrato = codigoContrato.ToString() }).Result.FirstOrDefault(); var documentoContrato = new ContratoDocumentoResponse(); if (!Convert.ToBoolean(contrato.IndicadorAdhesion)) { documentoContrato = contratoService.DocumentosPorContrato(contrato.CodigoContrato.Value).Result.FirstOrDefault(); } ObservacionesFormulario model = new ObservacionesFormulario(contrato, documentoContrato); var rptaObservacion = contratoService.ObtieneContratoEstadioObservacionPorID(codigoContratoEstadioObservacion); string lsRespuesta = string.Empty; string lsParrafo = retornaContenidoParrafoContrato(rptaObservacion.CodigoContratoParrafo); if (TipoVista == "C") {//Edicion lsRespuesta = rptaObservacion.Respuesta; } ViewBag.TipoVista = TipoVista; ViewBag.Codigo = rptaObservacion.CodigoContratoEstadioObservacion; ViewBag.CodigoContratoEstadio = rptaObservacion.CodigoContratoEstadio; ViewBag.TextoObservacion = rptaObservacion.Descripcion; ViewBag.FechaRegistro = rptaObservacion.FechaRegistro; ViewBag.CodigoContratoParrafo = rptaObservacion.CodigoContratoParrafo; ViewBag.CodigoEstadioRetorno = rptaObservacion.CodigoEstadioRetorno; ViewBag.Destinatario = rptaObservacion.Destinatario; ViewBag.TextoParrafo = lsParrafo; ViewBag.TextoRespuesta = lsRespuesta; return PartialView(model); } /// <summary> /// Muestra la vista Formulario Consulta /// </summary> /// <returns>Vista Parcial de Formulario de Consulta</returns> public ActionResult FormularioConsulta(Guid codigoFlujoAprobacion, Guid codigoContrato) { var contrato = contratoService.BuscarListadoContrato(new ListadoContratoRequest() { CodigoContrato = codigoContrato.ToString() }).Result.FirstOrDefault(); ConsultasBusqueda model = new ConsultasBusqueda(contrato); model.ResponsableFlujoEstadio = new List<SelectListItem>(); var UsuarioSesion = HttpGyMSessionContext.CurrentAccount(); var ListaTrabajador = trabajadorService.BuscarTrabajador(new TrabajadorRequest() { CodigoIdentificacion = UsuarioSesion.Alias }); if (ListaTrabajador.Result == null) ListaTrabajador.Result = new List<Politicas.Aplicacion.TransferObject.Response.General.TrabajadorResponse>(); var listaResponsable = contratoService.RetornaResponsablesFlujoEstadio(codigoFlujoAprobacion, codigoContrato); foreach (var item in listaResponsable.Result) { if (ListaTrabajador.Result.Count > 0) { if (item.CodigoTrabajador.ToUpper() != ListaTrabajador.Result[0].CodigoTrabajador.ToUpper()) { model.ResponsableFlujoEstadio.Add(new SelectListItem() { Text = item.NombreCompleto, Value = item.CodigoTrabajador }); } } else { model.ResponsableFlujoEstadio.Add(new SelectListItem() { Text = item.NombreCompleto, Value = item.CodigoTrabajador }); } } //model.ResponsableFlujoEstadio = new List<SelectListItem>(); return PartialView(model); } /// <summary> /// Muestra la vista Formula Responder Consulta /// </summary> /// <returns>Vista Parcial de Formulario Responder Consulta</returns> public ActionResult FormularioResponderConsulta(Guid codigoContratoEstadioConsulta, Guid codigoContrato, string TipoVista) { var contrato = contratoService.BuscarListadoContrato(new ListadoContratoRequest() { CodigoContrato = codigoContrato.ToString() }).Result.FirstOrDefault(); var documentoContrato = new ContratoDocumentoResponse(); if (!Convert.ToBoolean(contrato.IndicadorAdhesion)) { documentoContrato = contratoService.DocumentosPorContrato(contrato.CodigoContrato.Value).Result.FirstOrDefault(); } ObservacionesFormulario model = new ObservacionesFormulario(contrato, documentoContrato); var rptaConsulta = contratoService.ObtieneContratoEstadioConsultaPorID(codigoContratoEstadioConsulta); string lsRespuesta = string.Empty; string lsParrafo = retornaContenidoParrafoContrato(rptaConsulta.CodigoContratoParrafo); if (TipoVista == "C") {//Edicion lsRespuesta = rptaConsulta.Respuesta; } ViewBag.TipoVista = TipoVista; ViewBag.Codigo = rptaConsulta.CodigoContratoEstadioConsulta; ViewBag.CodigoContratoEstadio = rptaConsulta.CodigoContratoEstadio; ViewBag.FechaConsulta = rptaConsulta.FechaConsulta; ViewBag.CodigoContratoParrafo = rptaConsulta.CodigoContratoParrafo; ViewBag.Destinatario = rptaConsulta.Destinatario; ViewBag.TextoParrafo = lsParrafo; ViewBag.TextoConsulta = rptaConsulta.Descripcion; ViewBag.TextoRespuesta = lsRespuesta; return PartialView(model); } /// <summary> /// Muestra el formulario de trabajador Suplente /// </summary> /// <returns>Vista FormularioTrabajador</returns> public ActionResult FormularioTrabajadorSuplente() { var usuarioActual = trabajadorService.BuscarTrabajador(new TrabajadorRequest() { CodigoIdentificacion = entornoAplicacion.UsuarioSession }).Result.FirstOrDefault(); var trabajadorSuplente = trabajadorService.BuscarTrabajadorSuplente(new TrabajadorRequest() { CodigoTrabajador = new Guid(usuarioActual.CodigoTrabajador) }).Result.FirstOrDefault(); TrabajadorSuplenteModel modelo = new TrabajadorSuplenteModel(usuarioActual); if (trabajadorSuplente != null) { var trabajadorSuplenteDefinicion = trabajadorService.BuscarTrabajador(new TrabajadorRequest() { CodigoTrabajador = trabajadorSuplente.CodigoSuplente }).Result; trabajadorSuplente.ListaSuplente = trabajadorSuplenteDefinicion.ToDictionary(x => x.CodigoTrabajador, y => y.NombreCompleto); modelo = new TrabajadorSuplenteModel(trabajadorSuplente, usuarioActual); } return PartialView(modelo); } #endregion #region Json /// <summary> /// Busca Bandeja Contrato /// </summary> /// <returns>Lista de Contrato</returns> public JsonResult BuscarBandejaContrato(ContratoRequest request) { var listaTipoServicio = retornaTipoServicio(); var listaTipoRequerimiento = retornaTipoRequerimiento(); var resultado = contratoService.BuscarBandejaProcesosContratoOrdenado(request, listaTipoServicio, listaTipoRequerimiento); var jsonResult = Json(resultado, JsonRequestBehavior.AllowGet); jsonResult.MaxJsonLength = int.MaxValue; return jsonResult; } /// <summary> /// Busca Bandeja Observaciones /// </summary> /// <returns>Lista de Observaciones</returns> public JsonResult BuscarBandejaObservaciones(Guid? CodigoContratoEstadio) { Guid codContratoEsta = Guid.Empty; if (CodigoContratoEstadio != null) { codContratoEsta = (Guid)CodigoContratoEstadio; } var resultado = contratoService.BuscarBandejaContratosObservacion(codContratoEsta); return Json(resultado); } /// <summary> /// Registra Observaciones /// </summary> /// <returns>Objeto request de Contrato Estadio Observacion</returns> ///[AuthorizeEscrituraFilter] public JsonResult RegistrarObservaciones() { var request = new ContratoEstadioObservacionRequest(); if (Request["CodigoContrato"] != null) { request.CodigoContrato = new Guid(Request["CodigoContrato"].ToString()); } if (Request["ConCopiaCorreo"] != null) { request.NotificacionObservadoCC = Request["ConCopiaCorreo"].ToString(); } if (Request["CodigoContratoEstadio"] != null) { request.CodigoContratoEstadio = new Guid(Request["CodigoContratoEstadio"].ToString()); } if (Request["Descripcion"] != null) { request.Descripcion = Request["Descripcion"].ToString(); } if (Request["Destinatario"] != null) { request.Destinatario = new Guid(Request["Destinatario"].ToString()); } if (Request["CodigoEstadioRetorno"] != null) { request.CodigoEstadioRetorno = new Guid(Request["CodigoEstadioRetorno"].ToString()); } if (Request["IndicadorAdhesion"] != null) { request.IndicadorAdhesion = Convert.ToBoolean(Request["IndicadorAdhesion"].ToString()); if (request.IndicadorAdhesion) { HttpPostedFileBase file = Request.Files.Count > 0 ? Request.Files[0] : null; if (file != null) { byte[] documentoContrato = null; using (MemoryStream ms = new MemoryStream()) { file.InputStream.CopyTo(ms); documentoContrato = ms.ToArray(); } request.NombreArchivo = file.FileName; request.DocumentoContrato = documentoContrato; } } } var resultado = contratoService.RegistraContratoEstadioObservacion(request); return Json(resultado); } /// <summary> /// Respuesta a Observaciones de contrato /// </summary> /// <param name="objRqst">objeto request de Contrato Estadio Observacion</param> /// <returns>Indicador con el resultado de la operación</returns> ///[AuthorizeEscrituraFilter] public JsonResult RespondeObservaciones(ContratoEstadioObservacionRequest objRqst) { var resultado = contratoService.RespondeContratoEstadioObservacion(objRqst); return Json(resultado); } /// <summary> /// Busca Bandeja Consulta /// </summary> /// <returns>Lista con el resultado de la operación</returns> public JsonResult BuscarBandejaConsulta(Guid CodigoContratoEstadio) { var resultado = contratoService.BuscarBandejaContratosConsultas(CodigoContratoEstadio); return Json(resultado); } /// <summary> /// Registra la consulta del contrato /// </summary> /// <param name="objRqst">objeto request que contiene la información</param> /// <returns>Indicador con el resultado de la operación</returns> //[AuthorizeEscrituraFilter] public JsonResult RegistrarConsulta(ContratoEstadioConsultaRequest objRqst) { var resultado = contratoService.RegistraContratoEstadioConsulta(objRqst); return Json(resultado); } /// <summary> /// Metodo para Aprobar un Estadío de un Contrato /// </summary> /// <param name="codigoContrato">Código de Contrato</param> /// <param name="codigoContratoEstadio">Código de Contrato de Estadio</param> /// <param name="MotivoAprobacion">Motivo de aprobación no obligatoria</param> /// <returns>Indicador con el resultado de la operación</returns> ///[AuthorizeEscrituraFilter] public JsonResult AprobarContratoEstadio(Guid codigoContrato, Guid codigoContratoEstadio, string MotivoAprobacion) { var resultado = contratoService.ApruebaContratoEstadio(codigoContrato, codigoContratoEstadio, MotivoAprobacion, entornoAplicacion.UsuarioSession); return Json(resultado); } /// <summary> /// Retorna la lista de Párrafos por Contrato. /// </summary> /// <param name="CodigoContrato">Código del Contrato</param> /// <returns>Lista de Parrafos por contrato</returns> public JsonResult ListaParrafosPorContrato(Guid CodigoContrato) { Aplicacion.Core.Base.ProcessResult<List<ContratoParrafoResponse>> lstParrafos = new Aplicacion.Core.Base.ProcessResult<List<ContratoParrafoResponse>>(); obtenerSessionParrafosPorContrato(CodigoContrato); lstParrafos.Result = (List<ContratoParrafoResponse>)Session[DatosConstantes.Sesiones.SessionParrafoContrato]; return Json(lstParrafos); } /// <summary> /// Retorna la lista de estadíos por Contrato /// </summary> /// <param name="CodigoContratoEstadio">Código de Contrato Estadío</param> /// <returns>Lista Estadios por Contrato</returns> public JsonResult ListaEstadiosPorContrato(Guid CodigoContratoEstadio) { var listaEstadio = contratoService.RetornaEstadioContratoObservacion(CodigoContratoEstadio); return Json(listaEstadio); } /// <summary> /// Muestra el contenido del Contrato, dependiendo de su versión. /// </summary> /// <param name="CodigoDeContrato">Código del Contrato</param> /// <param name="codigoContratoEstadio"></param> /// <returns>Contenido del Contrato</returns> public ActionResult MostrarContratoDocumento(Guid CodigoDeContrato, Guid? codigoContratoEstadio) { string NombreFile = string.Empty; string lslinkCss = System.Web.HttpContext.Current.Server.MapPath("~/Theme/app/cssPdf.css"); var FileContrato = contratoService.GenerarContenidoContrato(CodigoDeContrato, codigoContratoEstadio, ref NombreFile, lslinkCss); MemoryStream memorySt = null; if (FileContrato.Result != null && FileContrato.IsSuccess) { memorySt = new MemoryStream((byte[])FileContrato.Result); } if (memorySt != null) { byte[] byteArchivo = memorySt.ToArray(); Response.Clear(); Response.AddHeader("Content-Disposition", string.Format("attachement; filename={0}", NombreFile)); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(byteArchivo); Response.End(); } else { return null; } return RedirectToAction("Reporte"); } /// <summary> /// Muestra el contenido del Contrato, dependiendo su observación. /// </summary> /// <param name="codigoContratoEstadioObservacion">Código de la Observación del Estadio del Contrato</param> /// <returns>Contenido del Contrato</returns> public ActionResult MostrarContratoDocumentoAnteriorObservacion(Guid codigoContratoEstadioObservacion) { string nombreArchivo = string.Empty; var FileContrato = contratoService.ObtenerContratoAnteriorObservacion(codigoContratoEstadioObservacion, ref nombreArchivo); MemoryStream memorySt = null; if (FileContrato.Result != null) { memorySt = new MemoryStream((byte[])FileContrato.Result); } if (memorySt != null) { byte[] byteArchivo = memorySt.ToArray(); Response.Clear(); Response.AddHeader("Content-Disposition", string.Format("attachement; filename={0}", nombreArchivo)); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(byteArchivo); Response.End(); } else { return null; } return RedirectToAction("Reporte"); } /// <summary> /// Muestra el contenido del Contrato, dependiendo su observación. /// </summary> /// <param name="codigoContratoEstadioObservacion">Código de la Observación del Estadio del Contrato</param> /// <returns>Contenido del Contrato</returns> public ActionResult MostrarContratoDocumentoReemplazanteObservacion(Guid codigoContratoEstadioObservacion) { string nombreArchivo = string.Empty; var FileContrato = contratoService.ObtenerContratoReemplazanteObservacion(codigoContratoEstadioObservacion, ref nombreArchivo); MemoryStream memorySt = null; if (FileContrato.Result != null) { memorySt = new MemoryStream((byte[])FileContrato.Result); } if (memorySt != null) { byte[] byteArchivo = memorySt.ToArray(); Response.Clear(); Response.AddHeader("Content-Disposition", string.Format("attachement; filename={0}", nombreArchivo)); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(byteArchivo); Response.End(); } else { return null; } return RedirectToAction("Reporte"); } /// <summary> /// Permite registrar el trabajador /// </summary> /// <param name="filtro">Filtro</param> /// <returns>Resultado de la operación</returns> [AuthorizeEscrituraFilter] public JsonResult RegistrarTrabajadorSuplente(TrabajadorSuplenteRequest filtro) { filtro.UsuarioSession = entornoAplicacion.UsuarioSession; filtro.Terminal = entornoAplicacion.Terminal; var resultado = trabajadorService.RegistrarTrabajadorSuplente(filtro); if (resultado.IsSuccess) { if (filtro.Activo == false) { var result = flujoAprobacionService.ActualizarTrabajadorOriginalFlujo(filtro.CodigoTrabajador); resultado.IsSuccess = result.IsSuccess; trabajadorService.EnviarNotificacionFinReemplazo(filtro.CodigoTrabajador, filtro.CodigoSuplente.Value); } } return Json(resultado); } /// <summary> /// Busca Trabajador /// </summary> /// <param name="filtroReq"></param> /// <returns>Lista con el resultado de la operación</returns> public JsonResult BuscarTrabajadorUO(string filtroReq) { TrabajadorRequest filtro = new TrabajadorRequest(); filtro.NombreCompleto = filtroReq; Pe.Stracon.Politicas.Aplicacion.Core.Base.ProcessResult<List<TrabajadorDatoMinimoResponse>> resultado = trabajadorService.BuscarTrabajadorDatoMinimo(filtro); return Json(resultado.Result, JsonRequestBehavior.AllowGet); } #endregion /// <summary> /// Carga información de un contrato estadio. /// </summary> /// <returns>Indicador con el resultado de la operación</returns> public JsonResult CargaDocumentoContratoEstadio() { Aplicacion.Core.Base.ProcessResult<object> rpta = new Aplicacion.Core.Base.ProcessResult<object>(); string codigoContratoDocumento = string.Empty, NombreUO = string.Empty, hayError = string.Empty; string lsDirectorioDestino, listName, folderName; Guid codigoContrato; HttpPostedFileBase file = Request.Files.Count > 0 ? Request.Files[0] : null; if (file != null && file.ContentLength > 0) { try { codigoContratoDocumento = Guid.NewGuid().ToString(); codigoContrato = Guid.Parse(Request["CodigoDeContrato"].ToString()); NombreUO = Request["NombreUnidadOperativa"].ToString(); #region InformacionRepositorioSharePoint string NombreFile = string.Format("{0}.{1}", codigoContratoDocumento.ToString(), DatosConstantes.ArchivosContrato.ExtensionValidaCarga); Aplicacion.Core.Base.ProcessResult<string> miDirectorio = contratoService.RetornaDirectorioFile(codigoContrato, NombreUO, NombreFile); lsDirectorioDestino = miDirectorio.Result.ToString(); string[] nivelCarpeta = lsDirectorioDestino.Split(new char[] { '/' }); listName = nivelCarpeta[0]; folderName = string.Format("{0}/{1}", nivelCarpeta[1], nivelCarpeta[2]); #endregion //CodigoArchivoSHP = ProcesaArchivoSharePoint(file, lstCodigosParam, ref hayErrorShp, ref lsRutaDestinoArchivo); MemoryStream ms; using (ms = new MemoryStream()) { file.InputStream.CopyTo(ms); } var regSHP = sharePointService.RegistraArchivoSharePoint(ref hayError, listName, folderName, NombreFile, ms); if (Convert.ToInt32(regSHP.Result) > 0 && hayError == string.Empty) { ContratoDocumentoResponse cdr = new ContratoDocumentoResponse(); cdr.CodigoContratoDocumento = Guid.Parse(codigoContratoDocumento); cdr.CodigoContrato = codigoContrato; cdr.CodigoArchivo = Convert.ToInt32(regSHP.Result); cdr.RutaArchivoSharePoint = lsDirectorioDestino; rpta = contratoService.RegistraContratoDocumentoCargaArchivo(cdr); if (Convert.ToInt32(regSHP.Result) == -1) { rpta.IsSuccess = false; rpta.Result = regSHP.Exception; } } else { rpta.IsSuccess = false; rpta.Result = hayError; } } catch (Exception ex) { rpta.IsSuccess = false; rpta.Result = ex.Message; } } return Json(rpta); } #region MetodosInternos /// <summary> /// Metodo para registrar los párrafos en una sessión. /// </summary> /// <param name="codigoContrato">código del contrato que contiene los párrafos.</param> private void obtenerSessionParrafosPorContrato(Guid codigoContrato) { List<ContratoParrafoResponse> lstParrafos = new List<ContratoParrafoResponse>(); if (Session[DatosConstantes.Sesiones.SessionParrafoContrato] == null) { lstParrafos = contratoService.RetornaParrafosPorContrato(codigoContrato).Result; Session[DatosConstantes.Sesiones.SessionParrafoContrato] = lstParrafos; } } /// <summary> /// Retorna el código GUID del Trabajador. /// </summary> /// <returns>Codigo Guid del Trabajador</returns> private string retornaCodigoTrabajadorSession() { var UsuarioSesion = HttpGyMSessionContext.CurrentAccount(); var ListaTrabajador = trabajadorService.BuscarTrabajador(new TrabajadorRequest() { CodigoIdentificacion = UsuarioSesion.Alias }); string ls_codtrb = string.Empty; if (ListaTrabajador.Result != null && ListaTrabajador.Result.Count > 0) { ls_codtrb = ListaTrabajador.Result[0].CodigoTrabajador.ToString(); } else { ls_codtrb = Guid.Empty.ToString(); } return ls_codtrb; } /// <summary> /// Retorna el contenido de cada párrafo por el codigo. /// </summary> /// <param name="codigoContratoParrafo">Código el Párrafo de contrato.</param> /// <returns>Contenido de Parrafo</returns> private string retornaContenidoParrafoContrato(Guid? codigoContratoParrafo) { string lsParrafo = string.Empty; int li_index = -1;//Obtenemos el Párrafo List<ContratoParrafoResponse> lstParrafos = (List<ContratoParrafoResponse>)Session[DatosConstantes.Sesiones.SessionParrafoContrato]; if (lstParrafos != null && lstParrafos.Count > 0) { li_index = lstParrafos.FindIndex(x => x.CodigoContratoParrafo.ToString().ToUpper() == codigoContratoParrafo.ToString().ToUpper()); if (li_index > -1) { lsParrafo = lstParrafos[li_index].Contenido; } } return lsParrafo; } /// <summary> /// Procedimiento que actualiza el Archivo en Repositorio SharePoint y devuelve el ID generado del archivo /// </summary> /// <param name="file">Codigo File</param> /// <param name="lstParametros">Codigo Lista Parametros</param> /// <param name="hayError">Codigo Error</param> /// <param name="RutaDestino">Codigo Ruta Destino</param> /// <returns>Indicador con el resultado de la operación</returns> public int ProcesaArchivoSharePoint(HttpPostedFileBase file, List<string> lstParametros, ref string hayError, ref string RutaDestino) { int resultado = -1; try { string lsUrlServerSHP = string.Empty, lsSite = string.Empty; string userShp = string.Empty, passWord = string.Empty, dominio = string.Empty; RutaDestino = string.Empty; Guid CodContrato = Guid.Parse(lstParametros[0]); string NombreUO = lstParametros[1]; string NombreFile = string.Format("{0}.{1}", lstParametros[2], DatosConstantes.ArchivosContrato.ExtensionValidaCarga); #region GrabarInformacionSH /*Servicio armar el directorio.*/ var lsRuta = contratoService.RetornaDirectorioFile(CodContrato, NombreUO, NombreFile); string lsDirectorioDestino = lsRuta.Result.ToString(); RutaDestino = lsDirectorioDestino; var cfgSharePoint = politicaService.ListarConfiguracionSharePoint(null, "3"); var crdSharePoint = politicaService.ListarCredencialesAccesoDinamico(); lsUrlServerSHP = cfgSharePoint.Result[0].Valor.ToString(); lsSite = cfgSharePoint.Result[1].Valor.ToString(); userShp = crdSharePoint.Result[0].Atributo3; passWord = crdSharePoint.Result[0].Atributo4; dominio = crdSharePoint.Result[0].Atributo5; MemoryStream ms; using (ms = new MemoryStream()) { file.InputStream.CopyTo(ms); } /*Revisamos la estructura de las carpetas SharePoint*/ string[] nivelCarpeta = lsDirectorioDestino.Split(new char[] { '/' }); SharepointEN shEnt = new SharepointEN(); shEnt.siteUrlParam = string.Format("{0}{1}", lsUrlServerSHP, lsSite); shEnt.listName = nivelCarpeta[0]; shEnt.folderName = string.Format("{0}/{1}", nivelCarpeta[1], nivelCarpeta[2]); shEnt.fileName = NombreFile; shEnt.msfile = ms; SharepointHelper shp = new SharepointHelper(userShp, passWord, dominio); int NewFileSharePoint = shp.RegistraFileSharePointSGC(shEnt, ref hayError); return NewFileSharePoint; #endregion } catch (Exception) { resultado = -1; } return resultado; } /// <summary> /// metodo para retorna el contenido html de un parrafo. /// </summary> /// <param name="codigoContratoParrafo">Código del Contrato - Parrafo</param> /// <returns>Contenido HTML de Parrafo</returns> public JsonResult ConsultaContenidoParrafo(Guid codigoContratoParrafo) { Aplicacion.Core.Base.ProcessResult<string> rptaParrafo = new ProcessResult<string>(); rptaParrafo.Result = retornaContenidoParrafoContrato(codigoContratoParrafo); return Json(rptaParrafo); } /// <summary> /// Retorna la cantidad de obesrvaciones pendientes de responder. /// </summary> /// <param name="codigoContratoEstadio">Código de Contrato Estadio.</param> /// <returns>Cantidad de Observaciones pendientes</returns> private int RetornaCantidadObservacionesResponder(Guid codigoContratoEstadio) { int obsPorResponder = 0; var lstObservaciones = contratoService.BuscarBandejaContratosObservacion(codigoContratoEstadio); if (lstObservaciones.Result != null && lstObservaciones.Result.Count > 0) { foreach (var item in lstObservaciones.Result) { if (string.IsNullOrEmpty(item.CodigoTipoRespuesta)) { obsPorResponder++; } } } return obsPorResponder; } /// <summary> /// Método para obetener la cantidad de obesrvaciones pendientes de responder. /// </summary> /// <param name="codigoContratoEstadio"></param> /// <returns>Obeservaciones pendientes por responder</returns> public JsonResult ObservacionesPorResponder(Guid codigoContratoEstadio) { Aplicacion.Core.Base.ProcessResult<object> rpta = new ProcessResult<object>(); rpta.Result = RetornaCantidadObservacionesResponder(codigoContratoEstadio); return Json(rpta); } /// <summary> /// Retorna la lista de Tipo de Servicio del Contrato /// </summary> /// <returns>Lista de Tipo de Servicio del Contrato</returns> public List<CodigoValorResponse> retornaTipoServicio() { List<CodigoValorResponse> listaTipoServicio = new List<CodigoValorResponse>(); if (Session[DatosConstantes.Sesiones.SessionTipoServicio] == null) { listaTipoServicio = politicaService.ListarTipoContrato().Result; Session[DatosConstantes.Sesiones.SessionTipoServicio] = listaTipoServicio; } else { listaTipoServicio = (List<CodigoValorResponse>)Session[DatosConstantes.Sesiones.SessionTipoServicio]; } return listaTipoServicio; } /// <summary> /// Retorna la lista de Tipo de Requerimiento del Contrato /// </summary> /// <returns>Lista de Tipo de Requerimiento del Contrato</returns> public List<CodigoValorResponse> retornaTipoRequerimiento() { List<CodigoValorResponse> listaTipoRequerimiento = new List<CodigoValorResponse>(); if (Session[DatosConstantes.Sesiones.SessionTipoRequerimiento] == null) { listaTipoRequerimiento = politicaService.ListarTipoServicio().Result; Session[DatosConstantes.Sesiones.SessionTipoRequerimiento] = listaTipoRequerimiento; } else { listaTipoRequerimiento = (List<CodigoValorResponse>)Session[DatosConstantes.Sesiones.SessionTipoRequerimiento]; } return listaTipoRequerimiento; } #endregion } }
using System.Collections.Generic; using System.Dynamic; using NHibernate.Envers.Configuration.Attributes; using Profiling2.Domain.Extensions; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Persons { public class PersonRelationship : Entity, IIncompleteDate { [Audited] public virtual Person SubjectPerson { get; set; } [Audited] public virtual Person ObjectPerson { get; set; } [Audited] public virtual PersonRelationshipType PersonRelationshipType { get; set; } [Audited] public virtual int DayOfStart { get; set; } [Audited] public virtual int MonthOfStart { get; set; } [Audited] public virtual int YearOfStart { get; set; } [Audited] public virtual int DayOfEnd { get; set; } [Audited] public virtual int MonthOfEnd { get; set; } [Audited] public virtual int YearOfEnd { get; set; } [Audited] public virtual bool Archive { get; set; } [Audited] public virtual string Notes { get; set; } public virtual string RelationshipSummary() { return this.RelationshipSummary(null); } public virtual string RelationshipSummary(Person p) { return string.Join(" ", new string[] { this.SubjectPerson == p ? "(Profiled) " + this.SubjectPerson.Name : this.SubjectPerson.Name, this.PersonRelationshipType.PersonRelationshipTypeName, this.ObjectPerson == p ? "(profiled) " + this.ObjectPerson.Name : this.ObjectPerson.Name }); } protected virtual string GetTimelineHeadlineText(Person p) { IList<string> parts = new List<string>(); if (this.SubjectPerson != p) parts.Add(this.SubjectPerson.Name); parts.Add(this.PersonRelationshipType != null ? this.PersonRelationshipType.PersonRelationshipTypeName : "(no relationship type)"); if (this.ObjectPerson != p) parts.Add(this.ObjectPerson.Name); return string.Join(" ", parts); } /// <summary> /// Returns TimelineJS date object. /// </summary> /// <param name="p">Subject of the timeline, in order not to duplicate text.</param> /// <returns></returns> public virtual object GetTimelineSlideObject(Person p) { dynamic o = new ExpandoObject(); if (this.GetTimelineStartDateObject() != null) o.start_date = this.GetTimelineStartDateObject(); if (this.GetTimelineEndDateObject() != null) o.end_date = this.GetTimelineEndDateObject(); o.text = new { headline = this.GetTimelineHeadlineText(p), text = this.RelationshipSummary() + (!string.IsNullOrEmpty(this.Notes) ? "<p>" + this.Notes + "</p>" : string.Empty) }; o.group = "Relationship"; return o; } public override string ToString() { //return (this.SubjectPerson != null ? "Person(ID=" + this.SubjectPerson.Id.ToString() + ")" : string.Empty) // + " " + this.PersonRelationshipType.ToString() + " " // + (this.ObjectPerson != null ? "Person(ID=" + this.ObjectPerson.Id.ToString() + ")" : string.Empty); return "PersonRelationship(ID=" + this.Id.ToString() + ")"; } } }
using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using Autofac; using Autofac.Core; namespace Tomelt.Wcf { public class TomeltInstanceProvider : IInstanceProvider { private readonly IWorkContextAccessor _workContextAccessor; private readonly IComponentRegistration _componentRegistration; public TomeltInstanceProvider(IWorkContextAccessor workContextAccessor, IComponentRegistration componentRegistration) { _workContextAccessor = workContextAccessor; _componentRegistration = componentRegistration; } public object GetInstance(InstanceContext instanceContext, Message message) { TomeltInstanceContext item = new TomeltInstanceContext(_workContextAccessor); instanceContext.Extensions.Add(item); return item.Resolve(_componentRegistration); } public object GetInstance(InstanceContext instanceContext) { return GetInstance(instanceContext, null); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { TomeltInstanceContext context = instanceContext.Extensions.Find<TomeltInstanceContext>(); if (context != null) { context.Dispose(); } } } }
using Sentry.Extensibility; using Sentry.Internal; using Sentry.Protocol; namespace Sentry.Integrations; internal class AppDomainUnhandledExceptionIntegration : ISdkIntegration { private readonly IAppDomain _appDomain; private IHub? _hub; private SentryOptions? _options; internal AppDomainUnhandledExceptionIntegration(IAppDomain? appDomain = null) => _appDomain = appDomain ?? AppDomainAdapter.Instance; public void Register(IHub hub, SentryOptions options) { _hub = hub; _options = options; _appDomain.UnhandledException += Handle; } // Internal for testability #if !NET6_0_OR_GREATER [HandleProcessCorruptedStateExceptions] #endif [SecurityCritical] internal void Handle(object sender, UnhandledExceptionEventArgs e) { _options?.LogDebug("AppDomain Unhandled Exception"); if (e.ExceptionObject is Exception ex) { ex.SetSentryMechanism( "AppDomain.UnhandledException", "This exception was caught by the .NET Application Domain global error handler. " + "The application likely crashed as a result of this exception.", handled: false); // Call the internal implementation, so that we still capture even if the hub has been disabled. _hub?.CaptureExceptionInternal(ex); } if (e.IsTerminating) { _hub?.Flush(_options!.ShutdownTimeout); } } }
public class Solution { public bool IsValid(string s) { Stack<char> st = new Stack<char>(); for (int i = 0; i < s.Length; i ++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { st.Push(s[i]); } else { if (st.Count == 0) return false; char top = st.Pop(); if (!((s[i] == ')' && top == '(') || (s[i] == ']' && top == '[') || (s[i] == '}' && top == '{') )) { return false; } } } if (st.Count == 0) { return true; } else { return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Backend_WebProject_API.Models; using Microsoft.AspNetCore.Mvc; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Backend_WebProject_API.Controllers { public class TodoListController : Controller { // GET: /<controller>/ public IActionResult Index() { return View(); } [HttpPost] [Route("AddTodoTask")] public ActionResult AddTodoTask([FromBody] TodoItemModel todoItemModel) { if (Helper.isUserLoggedIn(HttpContext.Request.Cookies["session-id"])){ todoItemModel.UUID = HttpContext.Request.Cookies["session-id"]; Helper.addToDoTaskInList(todoItemModel); return Ok(); } else { return Unauthorized("User is not loggged"); } } [HttpGet] [Route("getAllTodoTasks")] public ActionResult Get() { if (Helper.isUserLoggedIn(HttpContext.Request.Cookies["session-id"])) { return Ok(Helper.getAllToDoTaskInList(HttpContext.Request.Cookies["session-id"]).ToArray()); } else { return Unauthorized("User is not loggged"); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; namespace NStandard.Security { internal class RsaConverter { public static byte[] ParamsToPem(RSAParameters parameters, bool includePrivateParameters) { if (includePrivateParameters) { return new PemNode(PemNode.DataType.Sequence, new[] { new PemNode(PemNode.DataType.Integer, new byte[] { 0x00 }), new PemNode(PemNode.DataType.Sequence, PemNode.RSA_OID), new PemNode(PemNode.DataType.OctetString, new[] { new PemNode(PemNode.DataType.Sequence, new[] { new PemNode(PemNode.DataType.Integer, new byte[] { 0x00 } ), new PemNode(PemNode.DataType.Integer, parameters.Modulus ), new PemNode(PemNode.DataType.Integer, parameters.Exponent ), new PemNode(PemNode.DataType.Integer, parameters.D ), new PemNode(PemNode.DataType.Integer, parameters.P ), new PemNode(PemNode.DataType.Integer, parameters.Q ), new PemNode(PemNode.DataType.Integer, parameters.DP ), new PemNode(PemNode.DataType.Integer, parameters.DQ ), new PemNode(PemNode.DataType.Integer, parameters.InverseQ ), }) }), }).Fragment; } else { return new PemNode(PemNode.DataType.Sequence, new[] { new PemNode(PemNode.DataType.Sequence, PemNode.RSA_OID), new PemNode(PemNode.DataType.BitString, new[] { new PemNode(PemNode.DataType.Sequence, new[] { new PemNode(PemNode.DataType.Integer, parameters.Modulus ), new PemNode(PemNode.DataType.Integer, parameters.Exponent ), }) }), }).Fragment; } } public static RSAParameters ParamsFromPem(byte[] pem, bool includePrivateParameters) { byte[][] resolved; if (includePrivateParameters) { resolved = Resolve(Resolve(Resolve(Resolve(pem, new[] { PemNode.DataType.Sequence, })[0], new[] { PemNode.DataType.Integer, PemNode.DataType.Sequence, PemNode.DataType.OctetString, })[2], new[] { PemNode.DataType.Sequence, })[0], new[] { PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, PemNode.DataType.Integer, }); return new RSAParameters { Modulus = resolved[1], Exponent = resolved[2], D = resolved[3], P = resolved[4], Q = resolved[5], DP = resolved[6], DQ = resolved[7], InverseQ = resolved[8], }; } else { resolved = Resolve(Resolve(Resolve(Resolve(pem, new[] { PemNode.DataType.Sequence, })[0], new[] { PemNode.DataType.Sequence, PemNode.DataType.BitString, })[1], new[] { PemNode.DataType.Sequence, })[0], new[] { PemNode.DataType.Integer, PemNode.DataType.Integer, }); return new RSAParameters { Modulus = resolved[0], Exponent = resolved[1], }; } } private static byte[][] Resolve(byte[] fragment, PemNode.DataType[] dataTypes) { var bytesList = new List<byte[]>(); using (var memory = new MemoryStream(fragment)) { foreach (var dataType in dataTypes) { var type = (PemNode.DataType)memory.ReadByte(); if (type != dataType) throw new ArgumentException($"Argument[{bytesList.Count}] is not a '{dataType}'."); var lengthBytes = new byte[5]; lengthBytes[0] = (byte)memory.ReadByte(); switch (lengthBytes[0]) { case byte sign when sign == 0x81: memory.Read(lengthBytes, 1, 1); break; case byte sign when sign == 0x82: memory.Read(lengthBytes, 1, 2); break; case byte sign when sign == 0x83: memory.Read(lengthBytes, 1, 3); break; case byte sign when sign == 0x84: memory.Read(lengthBytes, 1, 4); break; } var length = PemNode.GetLength(lengthBytes); byte[] data; var first = (byte)memory.ReadByte(); if (first == 0) { data = new byte[length - 1]; memory.Read(data, 0, data.Length); } else { data = new byte[length]; data[0] = first; memory.Read(data, 1, data.Length - 1); } bytesList.Add(data); } } return bytesList.ToArray(); } } }
using System.Collections.Generic; namespace Tests.Data.Van.Input { public class ScriptSortOptionsOrder { public Dictionary<string, bool> OrderRadioButtonDictionary = new Dictionary<string, bool> { { "Ascending", false }, { "Descending", false } }; public bool ShowGroupHeader = false; public bool PageBreaks = false; } }
using System.Threading.Tasks; namespace CustomServiceRegistration.Domain.Infrastructure.Configuration { public interface IDatabaseInitializer { Task Seed(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HTB.v2.intranetx { public class XGlobals { public static string KT_db_date_format = "yyyy-mm-dd"; public static string KT_db_time_format = "HH:mm:ss"; public static string KT_screen_date_format = "dd.mm.yyyy"; public static string KT_screen_time_format = "hh:mm tt"; } }
// // FakeConsole.cs: A fake .NET Windows Console API implementation for unit tests. // using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Terminal.Gui { #pragma warning disable RCS1138 // Add summary to documentation comment. /// <summary> /// /// </summary> public static class FakeConsole { #pragma warning restore RCS1138 // Add summary to documentation comment. // // Summary: // Gets or sets the width of the console window. // // Returns: // The width of the console window measured in columns. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value of the System.Console.WindowWidth property or the value of the System.Console.WindowHeight // property is less than or equal to 0.-or-The value of the System.Console.WindowHeight // property plus the value of the System.Console.WindowTop property is greater than // or equal to System.Int16.MaxValue.-or-The value of the System.Console.WindowWidth // property or the value of the System.Console.WindowHeight property is greater // than the largest possible window width or height for the current screen resolution // and console font. // // T:System.IO.IOException: // Error reading or writing information. #pragma warning disable RCS1138 // Add summary to documentation comment. /// <summary> /// Specifies the initial console width. /// </summary> public const int WIDTH = 80; /// <summary> /// Specifies the initial console height. /// </summary> public const int HEIGHT = 25; /// <summary> /// /// </summary> public static int WindowWidth { get; set; } = WIDTH; // // Summary: // Gets a value that indicates whether output has been redirected from the standard // output stream. // // Returns: // true if output is redirected; otherwise, false. /// <summary> /// /// </summary> public static bool IsOutputRedirected { get; } // // Summary: // Gets a value that indicates whether the error output stream has been redirected // from the standard error stream. // // Returns: // true if error output is redirected; otherwise, false. /// <summary> /// /// </summary> public static bool IsErrorRedirected { get; } // // Summary: // Gets the standard input stream. // // Returns: // A System.IO.TextReader that represents the standard input stream. /// <summary> /// /// </summary> public static TextReader In { get; } // // Summary: // Gets the standard output stream. // // Returns: // A System.IO.TextWriter that represents the standard output stream. /// <summary> /// /// </summary> public static TextWriter Out { get; } // // Summary: // Gets the standard error output stream. // // Returns: // A System.IO.TextWriter that represents the standard error output stream. /// <summary> /// /// </summary> public static TextWriter Error { get; } // // Summary: // Gets or sets the encoding the console uses to read input. // // Returns: // The encoding used to read console input. // // Exceptions: // T:System.ArgumentNullException: // The property value in a set operation is null. // // T:System.IO.IOException: // An error occurred during the execution of this operation. // // T:System.Security.SecurityException: // Your application does not have permission to perform this operation. /// <summary> /// /// </summary> public static Encoding InputEncoding { get; set; } // // Summary: // Gets or sets the encoding the console uses to write output. // // Returns: // The encoding used to write console output. // // Exceptions: // T:System.ArgumentNullException: // The property value in a set operation is null. // // T:System.IO.IOException: // An error occurred during the execution of this operation. // // T:System.Security.SecurityException: // Your application does not have permission to perform this operation. /// <summary> /// /// </summary> public static Encoding OutputEncoding { get; set; } // // Summary: // Gets or sets the background color of the console. // // Returns: // A value that specifies the background color of the console; that is, the color // that appears behind each character. The default is black. // // Exceptions: // T:System.ArgumentException: // The color specified in a set operation is not a valid member of System.ConsoleColor. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. static ConsoleColor _defaultBackgroundColor = ConsoleColor.Black; /// <summary> /// /// </summary> public static ConsoleColor BackgroundColor { get; set; } = _defaultBackgroundColor; // // Summary: // Gets or sets the foreground color of the console. // // Returns: // A System.ConsoleColor that specifies the foreground color of the console; that // is, the color of each character that is displayed. The default is gray. // // Exceptions: // T:System.ArgumentException: // The color specified in a set operation is not a valid member of System.ConsoleColor. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. static ConsoleColor _defaultForegroundColor = ConsoleColor.Gray; /// <summary> /// /// </summary> public static ConsoleColor ForegroundColor { get; set; } = _defaultForegroundColor; // // Summary: // Gets or sets the height of the buffer area. // // Returns: // The current height, in rows, of the buffer area. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value in a set operation is less than or equal to zero.-or- The value in // a set operation is greater than or equal to System.Int16.MaxValue.-or- The value // in a set operation is less than System.Console.WindowTop + System.Console.WindowHeight. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static int BufferHeight { get; set; } = HEIGHT; // // Summary: // Gets or sets the width of the buffer area. // // Returns: // The current width, in columns, of the buffer area. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value in a set operation is less than or equal to zero.-or- The value in // a set operation is greater than or equal to System.Int16.MaxValue.-or- The value // in a set operation is less than System.Console.WindowLeft + System.Console.WindowWidth. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static int BufferWidth { get; set; } = WIDTH; // // Summary: // Gets or sets the height of the console window area. // // Returns: // The height of the console window measured in rows. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value of the System.Console.WindowWidth property or the value of the System.Console.WindowHeight // property is less than or equal to 0.-or-The value of the System.Console.WindowHeight // property plus the value of the System.Console.WindowTop property is greater than // or equal to System.Int16.MaxValue.-or-The value of the System.Console.WindowWidth // property or the value of the System.Console.WindowHeight property is greater // than the largest possible window width or height for the current screen resolution // and console font. // // T:System.IO.IOException: // Error reading or writing information. /// <summary> /// /// </summary> public static int WindowHeight { get; set; } = HEIGHT; // // Summary: // Gets or sets a value indicating whether the combination of the System.ConsoleModifiers.Control // modifier key and System.ConsoleKey.C console key (Ctrl+C) is treated as ordinary // input or as an interruption that is handled by the operating system. // // Returns: // true if Ctrl+C is treated as ordinary input; otherwise, false. // // Exceptions: // T:System.IO.IOException: // Unable to get or set the input mode of the console input buffer. /// <summary> /// /// </summary> public static bool TreatControlCAsInput { get; set; } // // Summary: // Gets the largest possible number of console window columns, based on the current // font and screen resolution. // // Returns: // The width of the largest possible console window measured in columns. /// <summary> /// /// </summary> public static int LargestWindowWidth { get; } // // Summary: // Gets the largest possible number of console window rows, based on the current // font and screen resolution. // // Returns: // The height of the largest possible console window measured in rows. /// <summary> /// /// </summary> public static int LargestWindowHeight { get; } // // Summary: // Gets or sets the leftmost position of the console window area relative to the // screen buffer. // // Returns: // The leftmost console window position measured in columns. // // Exceptions: // T:System.ArgumentOutOfRangeException: // In a set operation, the value to be assigned is less than zero.-or-As a result // of the assignment, System.Console.WindowLeft plus System.Console.WindowWidth // would exceed System.Console.BufferWidth. // // T:System.IO.IOException: // Error reading or writing information. /// <summary> /// /// </summary> public static int WindowLeft { get; set; } // // Summary: // Gets or sets the top position of the console window area relative to the screen // buffer. // // Returns: // The uppermost console window position measured in rows. // // Exceptions: // T:System.ArgumentOutOfRangeException: // In a set operation, the value to be assigned is less than zero.-or-As a result // of the assignment, System.Console.WindowTop plus System.Console.WindowHeight // would exceed System.Console.BufferHeight. // // T:System.IO.IOException: // Error reading or writing information. /// <summary> /// /// </summary> public static int WindowTop { get; set; } // // Summary: // Gets or sets the column position of the cursor within the buffer area. // // Returns: // The current position, in columns, of the cursor. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value in a set operation is less than zero.-or- The value in a set operation // is greater than or equal to System.Console.BufferWidth. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static int CursorLeft { get; set; } // // Summary: // Gets or sets the row position of the cursor within the buffer area. // // Returns: // The current position, in rows, of the cursor. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value in a set operation is less than zero.-or- The value in a set operation // is greater than or equal to System.Console.BufferHeight. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static int CursorTop { get; set; } // // Summary: // Gets or sets the height of the cursor within a character cell. // // Returns: // The size of the cursor expressed as a percentage of the height of a character // cell. The property value ranges from 1 to 100. // // Exceptions: // T:System.ArgumentOutOfRangeException: // The value specified in a set operation is less than 1 or greater than 100. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static int CursorSize { get; set; } // // Summary: // Gets or sets a value indicating whether the cursor is visible. // // Returns: // true if the cursor is visible; otherwise, false. // // Exceptions: // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static bool CursorVisible { get; set; } // // Summary: // Gets or sets the title to display in the console title bar. // // Returns: // The string to be displayed in the title bar of the console. The maximum length // of the title string is 24500 characters. // // Exceptions: // T:System.InvalidOperationException: // In a get operation, the retrieved title is longer than 24500 characters. // // T:System.ArgumentOutOfRangeException: // In a set operation, the specified title is longer than 24500 characters. // // T:System.ArgumentNullException: // In a set operation, the specified title is null. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static string Title { get; set; } // // Summary: // Gets a value indicating whether a key press is available in the input stream. // // Returns: // true if a key press is available; otherwise, false. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.InvalidOperationException: // Standard input is redirected to a file instead of the keyboard. /// <summary> /// /// </summary> public static bool KeyAvailable { get; } // // Summary: // Gets a value indicating whether the NUM LOCK keyboard toggle is turned on or // turned off. // // Returns: // true if NUM LOCK is turned on; false if NUM LOCK is turned off. /// <summary> /// /// </summary> public static bool NumberLock { get; } // // Summary: // Gets a value indicating whether the CAPS LOCK keyboard toggle is turned on or // turned off. // // Returns: // true if CAPS LOCK is turned on; false if CAPS LOCK is turned off. /// <summary> /// /// </summary> public static bool CapsLock { get; } // // Summary: // Gets a value that indicates whether input has been redirected from the standard // input stream. // // Returns: // true if input is redirected; otherwise, false. /// <summary> /// /// </summary> public static bool IsInputRedirected { get; } // // Summary: // Plays the sound of a beep through the console speaker. // // Exceptions: // T:System.Security.HostProtectionException: // This method was executed on a server, such as SQL Server, that does not permit // access to a user interface. /// <summary> /// /// </summary> public static void Beep () { throw new NotImplementedException (); } // // Summary: // Plays the sound of a beep of a specified frequency and duration through the console // speaker. // // Parameters: // frequency: // The frequency of the beep, ranging from 37 to 32767 hertz. // // duration: // The duration of the beep measured in milliseconds. // // Exceptions: // T:System.ArgumentOutOfRangeException: // frequency is less than 37 or more than 32767 hertz.-or- duration is less than // or equal to zero. // // T:System.Security.HostProtectionException: // This method was executed on a server, such as SQL Server, that does not permit // access to the console. /// <summary> /// /// </summary> public static void Beep (int frequency, int duration) { throw new NotImplementedException (); } // // Summary: // Clears the console buffer and corresponding console window of display information. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. static char [,] _buffer = new char [WindowWidth, WindowHeight]; /// <summary> /// /// </summary> public static void Clear () { _buffer = new char [BufferWidth, BufferHeight]; SetCursorPosition (0, 0); } // // Summary: // Copies a specified source area of the screen buffer to a specified destination // area. // // Parameters: // sourceLeft: // The leftmost column of the source area. // // sourceTop: // The topmost row of the source area. // // sourceWidth: // The number of columns in the source area. // // sourceHeight: // The number of rows in the source area. // // targetLeft: // The leftmost column of the destination area. // // targetTop: // The topmost row of the destination area. // // Exceptions: // T:System.ArgumentOutOfRangeException: // One or more of the parameters is less than zero.-or- sourceLeft or targetLeft // is greater than or equal to System.Console.BufferWidth.-or- sourceTop or targetTop // is greater than or equal to System.Console.BufferHeight.-or- sourceTop + sourceHeight // is greater than or equal to System.Console.BufferHeight.-or- sourceLeft + sourceWidth // is greater than or equal to System.Console.BufferWidth. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static void MoveBufferArea (int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) { throw new NotImplementedException (); } // // Summary: // Copies a specified source area of the screen buffer to a specified destination // area. // // Parameters: // sourceLeft: // The leftmost column of the source area. // // sourceTop: // The topmost row of the source area. // // sourceWidth: // The number of columns in the source area. // // sourceHeight: // The number of rows in the source area. // // targetLeft: // The leftmost column of the destination area. // // targetTop: // The topmost row of the destination area. // // sourceChar: // The character used to fill the source area. // // sourceForeColor: // The foreground color used to fill the source area. // // sourceBackColor: // The background color used to fill the source area. // // Exceptions: // T:System.ArgumentOutOfRangeException: // One or more of the parameters is less than zero.-or- sourceLeft or targetLeft // is greater than or equal to System.Console.BufferWidth.-or- sourceTop or targetTop // is greater than or equal to System.Console.BufferHeight.-or- sourceTop + sourceHeight // is greater than or equal to System.Console.BufferHeight.-or- sourceLeft + sourceWidth // is greater than or equal to System.Console.BufferWidth. // // T:System.ArgumentException: // One or both of the color parameters is not a member of the System.ConsoleColor // enumeration. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static void MoveBufferArea (int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { throw new NotImplementedException (); } // // Summary: // Acquires the standard error stream. // // Returns: // The standard error stream. /// <summary> /// /// </summary> public static Stream OpenStandardError () { throw new NotImplementedException (); } // // Summary: // Acquires the standard error stream, which is set to a specified buffer size. // // Parameters: // bufferSize: // The internal stream buffer size. // // Returns: // The standard error stream. // // Exceptions: // T:System.ArgumentOutOfRangeException: // bufferSize is less than or equal to zero. /// <summary> /// /// </summary> public static Stream OpenStandardError (int bufferSize) { throw new NotImplementedException (); } // // Summary: // Acquires the standard input stream, which is set to a specified buffer size. // // Parameters: // bufferSize: // The internal stream buffer size. // // Returns: // The standard input stream. // // Exceptions: // T:System.ArgumentOutOfRangeException: // bufferSize is less than or equal to zero. /// <summary> /// /// </summary> public static Stream OpenStandardInput (int bufferSize) { throw new NotImplementedException (); } // // Summary: // Acquires the standard input stream. // // Returns: // The standard input stream. /// <summary> /// /// </summary> public static Stream OpenStandardInput () { throw new NotImplementedException (); } // // Summary: // Acquires the standard output stream, which is set to a specified buffer size. // // Parameters: // bufferSize: // The internal stream buffer size. // // Returns: // The standard output stream. // // Exceptions: // T:System.ArgumentOutOfRangeException: // bufferSize is less than or equal to zero. /// <summary> /// /// </summary> public static Stream OpenStandardOutput (int bufferSize) { throw new NotImplementedException (); } // // Summary: // Acquires the standard output stream. // // Returns: // The standard output stream. /// <summary> /// /// </summary> public static Stream OpenStandardOutput () { throw new NotImplementedException (); } // // Summary: // Reads the next character from the standard input stream. // // Returns: // The next character from the input stream, or negative one (-1) if there are currently // no more characters to be read. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static int Read () { throw new NotImplementedException (); } // // Summary: // Obtains the next character or function key pressed by the user. The pressed key // is optionally displayed in the console window. // // Parameters: // intercept: // Determines whether to display the pressed key in the console window. true to // not display the pressed key; otherwise, false. // // Returns: // An object that describes the System.ConsoleKey constant and Unicode character, // if any, that correspond to the pressed console key. The System.ConsoleKeyInfo // object also describes, in a bitwise combination of System.ConsoleModifiers values, // whether one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously // with the console key. // // Exceptions: // T:System.InvalidOperationException: // The System.Console.In property is redirected from some stream other than the // console. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static ConsoleKeyInfo ReadKey (bool intercept) { if (MockKeyPresses.Count > 0) { return MockKeyPresses.Pop (); } else { return new ConsoleKeyInfo ('\0', (ConsoleKey)'\0', false, false, false); } } /// <summary> /// /// </summary> public static Stack<ConsoleKeyInfo> MockKeyPresses = new Stack<ConsoleKeyInfo> (); // // Summary: // Obtains the next character or function key pressed by the user. The pressed key // is displayed in the console window. // // Returns: // An object that describes the System.ConsoleKey constant and Unicode character, // if any, that correspond to the pressed console key. The System.ConsoleKeyInfo // object also describes, in a bitwise combination of System.ConsoleModifiers values, // whether one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously // with the console key. // // Exceptions: // T:System.InvalidOperationException: // The System.Console.In property is redirected from some stream other than the // console. /// <summary> /// /// </summary> public static ConsoleKeyInfo ReadKey () { throw new NotImplementedException (); } // // Summary: // Reads the next line of characters from the standard input stream. // // Returns: // The next line of characters from the input stream, or null if no more lines are // available. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.OutOfMemoryException: // There is insufficient memory to allocate a buffer for the returned string. // // T:System.ArgumentOutOfRangeException: // The number of characters in the next line of characters is greater than System.Int32.MaxValue. /// <summary> /// /// </summary> public static string ReadLine () { throw new NotImplementedException (); } // // Summary: // Sets the foreground and background console colors to their defaults. // // Exceptions: // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static void ResetColor () { BackgroundColor = _defaultBackgroundColor; ForegroundColor = _defaultForegroundColor; } // // Summary: // Sets the height and width of the screen buffer area to the specified values. // // Parameters: // width: // The width of the buffer area measured in columns. // // height: // The height of the buffer area measured in rows. // // Exceptions: // T:System.ArgumentOutOfRangeException: // height or width is less than or equal to zero.-or- height or width is greater // than or equal to System.Int16.MaxValue.-or- width is less than System.Console.WindowLeft // + System.Console.WindowWidth.-or- height is less than System.Console.WindowTop // + System.Console.WindowHeight. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static void SetBufferSize (int width, int height) { BufferWidth = width; BufferHeight = height; _buffer = new char [BufferWidth, BufferHeight]; } // // Summary: // Sets the position of the cursor. // // Parameters: // left: // The column position of the cursor. Columns are numbered from left to right starting // at 0. // // top: // The row position of the cursor. Rows are numbered from top to bottom starting // at 0. // // Exceptions: // T:System.ArgumentOutOfRangeException: // left or top is less than zero.-or- left is greater than or equal to System.Console.BufferWidth.-or- // top is greater than or equal to System.Console.BufferHeight. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static void SetCursorPosition (int left, int top) { CursorLeft = left; CursorTop = top; WindowLeft = Math.Max (Math.Min (left, BufferWidth - WindowWidth), 0); WindowTop = Math.Max (Math.Min (top, BufferHeight - WindowHeight), 0); } // // Summary: // Sets the System.Console.Error property to the specified System.IO.TextWriter // object. // // Parameters: // newError: // A stream that is the new standard error output. // // Exceptions: // T:System.ArgumentNullException: // newError is null. // // T:System.Security.SecurityException: // The caller does not have the required permission. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static void SetError (TextWriter newError) { throw new NotImplementedException (); } // // Summary: // Sets the System.Console.In property to the specified System.IO.TextReader object. // // Parameters: // newIn: // A stream that is the new standard input. // // Exceptions: // T:System.ArgumentNullException: // newIn is null. // // T:System.Security.SecurityException: // The caller does not have the required permission. //[SecuritySafeCritical] /// <summary> /// /// </summary> public static void SetIn (TextReader newIn) { throw new NotImplementedException (); } // // Summary: // Sets the System.Console.Out property to the specified System.IO.TextWriter object. // // Parameters: // newOut: // A stream that is the new standard output. // // Exceptions: // T:System.ArgumentNullException: // newOut is null. // // T:System.Security.SecurityException: // The caller does not have the required permission. //[SecuritySafeCritical] /// <summary> /// /// </summary> /// <param name="newOut"></param> public static void SetOut (TextWriter newOut) { throw new NotImplementedException (); } // // Summary: // Sets the position of the console window relative to the screen buffer. // // Parameters: // left: // The column position of the upper left corner of the console window. // // top: // The row position of the upper left corner of the console window. // // Exceptions: // T:System.ArgumentOutOfRangeException: // left or top is less than zero.-or- left + System.Console.WindowWidth is greater // than System.Console.BufferWidth.-or- top + System.Console.WindowHeight is greater // than System.Console.BufferHeight. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. //[SecuritySafeCritical] /// <summary> /// /// </summary> /// <param name="left"></param> /// <param name="top"></param> public static void SetWindowPosition (int left, int top) { WindowLeft = left; WindowTop = top; } // // Summary: // Sets the height and width of the console window to the specified values. // // Parameters: // width: // The width of the console window measured in columns. // // height: // The height of the console window measured in rows. // // Exceptions: // T:System.ArgumentOutOfRangeException: // width or height is less than or equal to zero.-or- width plus System.Console.WindowLeft // or height plus System.Console.WindowTop is greater than or equal to System.Int16.MaxValue. // -or- width or height is greater than the largest possible window width or height // for the current screen resolution and console font. // // T:System.Security.SecurityException: // The user does not have permission to perform this action. // // T:System.IO.IOException: // An I/O error occurred. //[SecuritySafeCritical] /// <summary> /// /// </summary> /// <param name="width"></param> /// <param name="height"></param> public static void SetWindowSize (int width, int height) { WindowWidth = width; WindowHeight = height; } // // Summary: // Writes the specified string value to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (string value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified object to the standard output // stream. // // Parameters: // value: // The value to write, or null. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (object value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 64-bit unsigned integer value // to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. //[CLSCompliant (false)] /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (ulong value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 64-bit signed integer value to // the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (long value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified objects to the standard output // stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg0: // The first object to write using format. // // arg1: // The second object to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> /// <param name="arg1"></param> public static void Write (string format, object arg0, object arg1) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 32-bit signed integer value to // the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (int value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified object to the standard output // stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg0: // An object to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> public static void Write (string format, object arg0) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 32-bit unsigned integer value // to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. //[CLSCompliant (false)] /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (uint value) { throw new NotImplementedException (); } //[CLSCompliant (false)] /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> public static void Write (string format, object arg0, object arg1, object arg2, object arg3) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified array of objects to the standard // output stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg: // An array of objects to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format or arg is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg"></param> public static void Write (string format, params object [] arg) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified Boolean value to the standard // output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (bool value) { throw new NotImplementedException (); } // // Summary: // Writes the specified Unicode character value to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (char value) { _buffer [CursorLeft, CursorTop] = value; } // // Summary: // Writes the specified array of Unicode characters to the standard output stream. // // Parameters: // buffer: // A Unicode character array. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="buffer"></param> public static void Write (char [] buffer) { _buffer [CursorLeft, CursorTop] = (char)0; foreach (var ch in buffer) { _buffer [CursorLeft, CursorTop] += ch; } } // // Summary: // Writes the specified subarray of Unicode characters to the standard output stream. // // Parameters: // buffer: // An array of Unicode characters. // // index: // The starting position in buffer. // // count: // The number of characters to write. // // Exceptions: // T:System.ArgumentNullException: // buffer is null. // // T:System.ArgumentOutOfRangeException: // index or count is less than zero. // // T:System.ArgumentException: // index plus count specify a position that is not within buffer. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> public static void Write (char [] buffer, int index, int count) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified objects to the standard output // stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg0: // The first object to write using format. // // arg1: // The second object to write using format. // // arg2: // The third object to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> /// <param name="arg1"></param> /// <param name="arg2"></param> public static void Write (string format, object arg0, object arg1, object arg2) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified System.Decimal value to the standard // output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (decimal value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified single-precision floating-point // value to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (float value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified double-precision floating-point // value to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void Write (double value) { throw new NotImplementedException (); } // // Summary: // Writes the current line terminator to the standard output stream. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> public static void WriteLine () { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified single-precision floating-point // value, followed by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (float value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 32-bit signed integer value, // followed by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (int value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 32-bit unsigned integer value, // followed by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. //[CLSCompliant (false)] /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (uint value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 64-bit signed integer value, // followed by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (long value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified 64-bit unsigned integer value, // followed by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. //[CLSCompliant (false)] /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (ulong value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified object, followed by the current // line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (object value) { throw new NotImplementedException (); } // // Summary: // Writes the specified string value, followed by the current line terminator, to // the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (string value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified object, followed by the current // line terminator, to the standard output stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg0: // An object to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> public static void WriteLine (string format, object arg0) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified objects, followed by the current // line terminator, to the standard output stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg0: // The first object to write using format. // // arg1: // The second object to write using format. // // arg2: // The third object to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> /// <param name="arg1"></param> /// <param name="arg2"></param> public static void WriteLine (string format, object arg0, object arg1, object arg2) { throw new NotImplementedException (); } //[CLSCompliant (false)] /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> public static void WriteLine (string format, object arg0, object arg1, object arg2, object arg3) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified array of objects, followed by // the current line terminator, to the standard output stream using the specified // format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg: // An array of objects to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format or arg is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg"></param> public static void WriteLine (string format, params object [] arg) { throw new NotImplementedException (); } // // Summary: // Writes the specified subarray of Unicode characters, followed by the current // line terminator, to the standard output stream. // // Parameters: // buffer: // An array of Unicode characters. // // index: // The starting position in buffer. // // count: // The number of characters to write. // // Exceptions: // T:System.ArgumentNullException: // buffer is null. // // T:System.ArgumentOutOfRangeException: // index or count is less than zero. // // T:System.ArgumentException: // index plus count specify a position that is not within buffer. // // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="index"></param> /// <param name="count"></param> public static void WriteLine (char [] buffer, int index, int count) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified System.Decimal value, followed // by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (decimal value) { throw new NotImplementedException (); } // // Summary: // Writes the specified array of Unicode characters, followed by the current line // terminator, to the standard output stream. // // Parameters: // buffer: // A Unicode character array. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="buffer"></param> public static void WriteLine (char [] buffer) { throw new NotImplementedException (); } // // Summary: // Writes the specified Unicode character, followed by the current line terminator, // value to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (char value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified Boolean value, followed by the // current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (bool value) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified objects, followed by the current // line terminator, to the standard output stream using the specified format information. // // Parameters: // format: // A composite format string (see Remarks). // // arg0: // The first object to write using format. // // arg1: // The second object to write using format. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. // // T:System.ArgumentNullException: // format is null. // // T:System.FormatException: // The format specification in format is invalid. /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="arg0"></param> /// <param name="arg1"></param> public static void WriteLine (string format, object arg0, object arg1) { throw new NotImplementedException (); } // // Summary: // Writes the text representation of the specified double-precision floating-point // value, followed by the current line terminator, to the standard output stream. // // Parameters: // value: // The value to write. // // Exceptions: // T:System.IO.IOException: // An I/O error occurred. /// <summary> /// /// </summary> /// <param name="value"></param> public static void WriteLine (double value) { throw new NotImplementedException (); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace TheZhazha.WinForms { public partial class SetMasterHandleForm : Form { public string MasterHandle { get; set; } public SetMasterHandleForm() { InitializeComponent(); } protected override void OnActivated(EventArgs e) { base.OnActivated(e); textBoxHandle.Text = MasterHandle; textBoxHandle.Focus(); textBoxHandle.SelectAll(); } private void buttonOk_Click(object sender, EventArgs e) { MasterHandle = textBoxHandle.Text; DialogResult = DialogResult.OK; Close(); } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
using System; using System.Linq; using System.Net; using System.Reflection; using System.Threading.Tasks; using Humanizer; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Microsoft.Extensions.Options; using MeeToo.Domain.Attributes; using MeeToo.Domain.Contracts; namespace MeeToo.DataAccess.DocumentDb { public sealed class DocumentDbStorage : IStorage, IStorageDb { #region Fields private readonly IOptions<DocumentDbOptions> dbOptions; private readonly Task<Database> databaseFuture; private readonly DocumentClient documentClient; #endregion Fields public DocumentDbStorage(DocumentClient documentClient, IOptions<DocumentDbOptions> dbOptions) { this.dbOptions = dbOptions; this.documentClient = documentClient; } private DocumentDbStorage(DocumentClient documentClient, IOptions<DocumentDbOptions> dbOptions, Task<Database> databaseFuture) { this.dbOptions = dbOptions; this.databaseFuture = databaseFuture; this.documentClient = documentClient; } public IStorageDb Db(string id) { id = id ?? dbOptions.Value.DefaultDbId; if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException(nameof(id)); } return new DocumentDbStorage(documentClient, dbOptions, GetOrCreateDatabaseAsync(id)); } public async Task CreateIfNotExists(string id) { try { await documentClient.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(id)) .ConfigureAwait(false); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.NotFound) { await documentClient.CreateDatabaseAsync(new Database { Id = id }) .ConfigureAwait(false); } else { throw; } } } public async Task<IStorageCollection<T>> CollectionAsync<T>(string id = null) where T : IDocument { var db = await databaseFuture.ConfigureAwait(false); var collectionId = id ?? GetCollectionId(typeof(T)); var response = await documentClient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(db.Id, collectionId)); return new DocumentDbStorageCollection<T>(documentClient, db, response.Resource); } #region Private Stuff private async Task<Database> GetOrCreateDatabaseAsync(string id) { return documentClient.CreateDatabaseQuery() .Where(db => db.Id == id) .ToArray() .FirstOrDefault() ?? await documentClient.CreateDatabaseAsync(new Database {Id = id}) .ConfigureAwait(false); } private static string GetCollectionId(MemberInfo resourceType) { var dbCollectionAttribute = resourceType.GetCustomAttribute<DbCollectionAttribute>(); return dbCollectionAttribute != null ? dbCollectionAttribute.Id : resourceType.Name.Camelize().Pluralize(); } #endregion Private Stuff #region IDisposable public void Dispose() { try { documentClient.Dispose(); } catch { //ignore } } #endregion } }
using System; namespace gronsfeld { class Program { static void Main(string[] args) { string ABC = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; Console.WriteLine("Шифр Гронсфельда"); Console.WriteLine("Введите текст"); string startText = Console.ReadLine(); bool enterKey = true; string startkey = ""; do { Console.WriteLine("Введите ключ(из цифр)"); startkey = Console.ReadLine(); if (int.Parse(startkey) == 0) { Console.WriteLine("Ключ не должен быть равен нулю"); } if (startkey.Length > startText.Length) { startkey = startkey.Substring(0, startText.Length); } if (int.Parse(startkey) > 0) { enterKey = false; } } while (enterKey == true); string finKey = ""; for (int i = 0, j = 0; i < startText.Length; i++, j++) { if (j == startkey.Length) { j = 0; } finKey += startkey[j]; } string finText = ""; int startIndex = 0; int shift = 0; for (int i = 0; i < startText.Length; i++) { startIndex = ABC.IndexOf(startText[i]); shift = int.Parse(finKey[i].ToString()); if (startIndex + shift < ABC.Length) { finText += ABC[startIndex + shift]; } else { finText += ABC[startIndex + shift - ABC.Length]; } } Console.WriteLine("Ваш текст:{0} \nВаш ключ:{1}", finText, finKey); Console.WriteLine("Введите зашифрованный текст"); string text = Console.ReadLine(); Console.WriteLine("Ввелите ключ(из цифр)"); string key = Console.ReadLine(); string firstText = ""; int finIndex = 0; int shift1 = 0; for (int i = 0; i < text.Length; i++) { finIndex = ABC.IndexOf(text[i]); shift1 = int.Parse(key[i].ToString()); if (finIndex - shift1 >= 0) { firstText += ABC[finIndex - shift1]; } else { firstText += ABC[finIndex - shift1 + ABC.Length]; } } Console.WriteLine("Расшифрованный текст:{0}", firstText); Console.WriteLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; // ADD START using WebClickOnce.ViewModels; using WCF_Northwind.Contract; // ADD END namespace WebClickOnce.Controllers { public class OrderController : Controller { private NorthwindServiceReference.NorthwindServiceClient db = new NorthwindServiceReference.NorthwindServiceClient(); // GET: Order public ActionResult Index(int? CategoryID) { CategoryIndexData viewModel = new CategoryIndexData(); viewModel.Categories = db.GetAllCategories().ToList(); if (CategoryID != null) { ViewBag.CategoryID = CategoryID.Value; viewModel.Products = db.GetProductByCategoryID(CategoryID.Value).ToList(); } return View(viewModel); } } }
using System.Xml.Serialization; namespace Witsml.Data { public class WitsmlRefWellboreTrajectoryStation { [XmlElement("stationReference")] public string StationReference { get; set; } [XmlElement("trajectoryParent")] public string TrajectoryParent { get; set; } [XmlElement("wellboreParent")] public string WellboreParent { get; set; } } }
using System; //sistem kullanılır using System.Collections.Generic; //sistemin genel koleksiyonlarını tanımlayan sınıflarını içerir. using System.ComponentModel;//bileşenlerin ve tasarım zamanı davranışını uygulamak için kullanılan sınıfları sağlar. using System.Data;//birden çok veri kaynağındanbileşenleri oluşturmanızı sağlar. using System.Drawing;//grafiklere erişim sağlar using System.Linq;//birden çok veri kümesine işlem yapılmasını sağlar using System.Text;// bir ad alanında türlerin kullanımını sağlar using System.Threading.Tasks;//zaman uyumsuz kod yazma işlemini kolay hale getirir. using System.Windows.Forms;//form oluşturma namespace belirtiKaydiProg //özelliklerin, sınıfların ve fonksiyonların bir yerde toplandığı yer { public partial class Form1 : Form//formun yapısı { public Form1() { InitializeComponent(); } private void SonucButton_Click(object sender, EventArgs e)//sonuçları göster butonunun içine giriyoruz. { sncIsımLabel.Text = "İsim"; //sncIsımLabel'a isim yazısını tanımlıyoruz sncSonucLabel.Text = "Sonuç"; //sncSonucLabel'a sonuç yazısını tanımlıyoruz sncSoyIsimLabel.Text = "Soy İsim"; //sncSoyIsimLabel'a soy isim yazısını tanımlıyoruz sncTcLabel.Text = "T.C. Numarası";//sncTcLabel'a tc numarası yazısını tanımlıyoruz sncTelefonLabel.Text = "Telefon";//sncTelefonLabel'a telefon yazısını tanımlıyoruz sncYasAraligiLabel.Text = "Yaş";//sncYaşAraligiLabel'a yaş yazısını tanımlıyoruz sncAdresLabel.Text = "Adres";//sncAdresLabel'a adres yazısını tanımlıyoruz sncikiNoktalabel1.Text = ":";//sncikiNoktalabel1'e : yazısını tanımlıyoruz sncikiNoktalabel2.Text = ":";//sncikiNoktalabel2'ye : yazısını tanımlıyoruz sncikiNoktalabel3.Text = ":";//sncikiNoktalabel3'e : yazısını tanımlıyoruz sncikiNoktalabel4.Text = ":";//sncikiNoktalabel4'e : yazısını tanımlıyoruz sncikiNoktalabel5.Text = ":";//sncikiNoktalabel5'e : yazısını tanımlıyoruz sncikiNoktalabel6.Text = ":";//sncikiNoktalabel6'ya : yazısını tanımlıyoruz sonAdresLabel.Text = AdresTextBox.Text;// adres değerinin AdresTextBoxdan alınacağı tanımlanır sonIsimLabel.Text = isimTextBox.Text;// isim değerinin İsimTextBoxdan alınacağı tanımlanır sonSoyIsimLabel.Text = SoyIsimTextBox.Text;//soyisim değerinin SoyIsimTextBoxdan alınacağı tanımlanır sonTcLabel.Text = TcTextBox.Text;// tc numarasının değerinin TcTextBoxdan alınacağı tanımlanır sonTelefonLabel.Text = TelefonTextBox.Text;// telefon numarasının değerinin TelefonTextBoxdan alınacağı tanımlanır sonYasAraligiLabel.Text = yasAraligiTextBox.Text;// yaşın değerinin yasAraligiTextBoxdan alınacağı tanımlanır if (semptomCheckedListBox.CheckedItems.Count >= 2)//semptom ListBoxunda seçili itemler 2 ya da 2den fazlaysa bu yapıyı kullanırız. { if (semptomCheckedListBox.CheckedItems.Count >= 2 & arasiRadioButton2.Checked || uzeriRadioButton.Checked) //semptom ListBoxunda seçili itemler 2 ya da 2den fazlaysa ve yüksek ateş itemleri seçiliyse bu yapıyı kullanırız. { sonAnalizLabel.Text = "Belirtilerinizden Dolayı ve\nYüksek Ateşiniz Sebebiyle\nDoktora Görünmelisiniz.";//ateş ve semptom durumlarının ikisi de sağlanırsa sonuç kısmında bu metini yazdırıyoruz. } else if (semptomCheckedListBox.CheckedItems.Count >= 2 & altiRadioButton.Checked)//semptom ListBoxunda seçili itemler 2 ya da 2den fazlaysa ve düşük ateş itemi seçiliyse bu yapıyı kullanırız. { sonAnalizLabel.Text = "Ateşinizin Yükselmesi\nDurumunda\nDoktora Görününüz"; //sadece semptom durumu sağlanırsa sonuç kısmında bu metini yazdırıyoruz. } } if (semptomCheckedListBox.CheckedItems.Count <= 1)//semptom ListBoxunda seçili itemler 1 ya da 1den az ise bu yapıyı kullanırız. { if (semptomCheckedListBox.CheckedItems.Count <= 1 & arasiRadioButton2.Checked || uzeriRadioButton.Checked)//semptom ListBoxunda seçili itemler 1 ya da 1den az ise ve yüksek ateş itemleri seçiliyse bu yapıyı kullanırız. { sonAnalizLabel.Text = "Semptomların Görülmesi\nDurumunda\nDoktora Görününüz";//sadece ateş durumu sağlanırsa sonuç kısmında bu metini yazdırıyoruz. } else if (semptomCheckedListBox.CheckedItems.Count <= 1 & altiRadioButton.Checked)//semptom ListBoxunda seçili itemler 1 ya da 1den az ise ve düşük ateş itemi seçiliyse bu yapıyı kullanırız. { sonAnalizLabel.Text = "Virüs Taşıma Olasılığınız\nDüşüktür.";//ateş ve semptom durumlarının ikisi de sağlanmazsa sonuç kısmında bu metini yazdırıyoruz. } } } private void bagisiklikButton_Click(object sender, EventArgs e) //maddeleri göstermek için oluşturulan buton { bagisiklikListBox.Items.Add("Güçlü Bağışıklık Sistemi için Yeterli ve Dengeli Beslenin, Kaliteli Uyku Uyuyun ve Egzersiz Yapın.");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("Çeşitli ve Rengarenk Beslenin");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("D Vitaminin En Önemli Kaynağı Güneş.");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("Günde Bir Avuç Ceviz, Fındık, Badem gibi Yağlı Tohumlar Bağışıklık Sisteminin Güçlenmesine Katkı Sağlıyor");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("Yeterli ve Dengeli Beslenme, Tüm Besin Gruplarına Günlük Beslenmede Yer Vermekle Mümkün.");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("Bir Küçük Boy Patates Günlük A Vitamini İhtiyacını Karşılıyor.");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("Vücutta Gerçekleşen Çoğu Reaksiyon İçin Su Gereklidir.");//listboxa yazılacak maddeleri ekliyoruz bagisiklikListBox.Items.Add("Balık Tüketimi Arttırılmalıdır."); bagisiklikListBox.BackColor = Color.LimeGreen;//listboxun arka planı lime green olarak ayarlanır. } private void temizleButton_Click(object sender, EventArgs e)//kayıtları temizlemek için oluşturulan buton { { foreach (Control item in this.Controls)//kayıt temizlemek için bu yapıyı kullanacağız { if (item is TextBox) { TextBox tbox = (TextBox)item; tbox.Clear();//textlerdeki kaydın foreach kullanılarak silinmesi } } { while (semptomCheckedListBox.CheckedIndices.Count > 0) semptomCheckedListBox.SetItemChecked(semptomCheckedListBox.CheckedIndices[0], false);// semptom listboxunda 1 ve 1 den fazla item işaretliyse temizlenmesini sağlıyoruz } altiRadioButton.Checked = false; //RadioButtondaki kaydın false kullanılarak temizlenmesi uzeriRadioButton.Checked = false; //RadioButtondaki kaydın false kullanılarak temizlenmesi arasiRadioButton2.Checked = false; //RadioButtondaki kaydın fale kullanılarak temizlenmesi sonAnalizLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi sonAdresLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi sonIsimLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi sonSoyIsimLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi sonTcLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi sonTelefonLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi sonYasAraligiLabel.Text = ""; // labeldaki kaydın “ ” kullanılarak silinmesi bagisiklikListBox.Items.Clear(); //listboxdaki kaydın silinmesi bagisiklikListBox.BackColor = Color.White; //listboxun arkaplan renginin belirlenmesi } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class SubInteraction : IConditionable { public string interactionType; public List<string> textList; public List<Condition> conditionList; public Direction direction; public string destinationRoomName; public Vector2 entrancePoint; public string ItemToUseName; public bool ItemToUseRemoveBool; //public List<InventoryItem> inventoryItems; public InventoryItem inventoryItem; public string itemToRemove; public string conversationName; public string dialogueOptionTitle; public string dialogueTreeName; public string animationToPlay; public string animationToPlayOn; public string targetFurniture; public string soundToPlay; public int numberOfPlays; public string soundToStop; public string eventToAdd; public string eventToRemove; public string cutsceneToPlay; public string PItoHide; public string PItoShow; public string specialSubInt; public string roomToReset; public string newPlayer; public bool isImportant; public string rawText; public string RawText { get { return rawText; } set { rawText = value; textList = Utilities.SeparateText (rawText); } } public List<Condition> ConditionList { get { return conditionList; } set { conditionList = value; } } // move to room interaction public SubInteraction (string interactionType) { this.interactionType = interactionType; conditionList = new List<Condition>(); } public void RemoveConditionFromList(Condition condition) { if (condition == null) { Debug.LogError ("condition is null"); return; } if (conditionList.Contains (condition) == false) { Debug.LogError ("condition is not in list"); return; } conditionList.Remove (condition); } // ----- SUBINTERACT ----- // public void SubInteract () { //Debug.Log ("subinteract"); switch (interactionType) { case "showMonologue": InteractionManager.instance.DisplayText (Utilities.CreateSentenceList(PlayerManager.myPlayer, textList), isImportant); break; case "showDialogue": InteractionManager.instance.DisplayDialogueOption (this.dialogueOptionTitle); break; case "showDialogueTree": DialogueTree dialogueTree = GameManager.gameData.nameDialogueTreeMap [this.dialogueTreeName]; if (dialogueTree.currentConversation == null) { if (dialogueTree.conversationList.Count == 0) { Debug.LogError ("There are no conversations"); } dialogueTree.currentConversation = dialogueTree.conversationList [0]; } DialogueManager.instance.ActivateDialogueTree (dialogueTree); break; case "PlayAnimation": PI_Handler.instance.SetPIAnimationState (targetFurniture, animationToPlay); EventsHandler.Invoke_cb_inputStateChanged (); break; case "PlayAnimationOn": PI_Handler.instance.SetPIAnimationState (targetFurniture, animationToPlayOn); EventsHandler.Invoke_cb_inputStateChanged (); break; case "PlaySound": SoundManager.Invoke_cb_playSound (soundToPlay, numberOfPlays); EventsHandler.Invoke_cb_inputStateChanged (); break; case "StopSound": SoundManager.Invoke_cb_stopSound (soundToStop); EventsHandler.Invoke_cb_inputStateChanged (); break; case "PlayCutscene": Debug.Log ("subinteract" + "play cut scene"); CutsceneManager.instance.PlayCutscene(cutsceneToPlay); break; case "moveToRoom": InteractionManager.instance.MoveToRoom (destinationRoomName, entrancePoint); break; case "intoShadows": Debug.Log ("into shadows"); InteractionManager.instance.ChangeShadowState (true); break; case "outOfShadows": Debug.Log ("out of shadows"); InteractionManager.instance.ChangeShadowState (false); InteractionManager.instance.ResetRoom (RoomManager.instance.myRoom.myName); break; case "pickUpItem": InteractionManager.instance.PickUpItem (inventoryItem); ActionBoxManager.instance.CloseFurnitureFrame (); EventsHandler.Invoke_cb_inputStateChanged (); break; case "removeItem": InteractionManager.instance.RemoveItem (itemToRemove); ActionBoxManager.instance.CloseFurnitureFrame (); EventsHandler.Invoke_cb_inputStateChanged (); break; case "useItem": InteractionManager.instance.OpenInventory_UseItem (ActionBoxManager.instance.currentPhysicalInteractable); break; case "changeConversation": Debug.Log ("change conversation"); DialogueManager.instance.SetConversation (conversationName); break; case "endDialogueTree": DialogueManager.instance.DestroyDialogueTree (); break; case "showInventoryText": InteractionManager.instance.DisplayInventoryText (textList); break; case "changeInventoryItemBigPicture": //InteractionManager.instance.ChangeInventoryItemBigPicture (fileName); break; case "combine": InteractionManager.instance.OpenInventory_CombineItem (); break; case "addEvent": GameManager.userData.AddEventToList (eventToAdd); break; case "removeEvent": GameManager.userData.RemoveEventFromList (eventToRemove); break; case "switchPlayer": PlayerManager.instance.SwitchPlayer (newPlayer); break; case "hidePI": PI_Handler.instance.Hide_PI (PItoHide); break; case "showPI": PhysicalInteractable tempPI = RoomManager.instance.getFurnitureByName (PItoShow); PI_Handler.instance.UnHide_PI (tempPI); break; case "special": InteractionManager.instance.SpecialInteraction (specialSubInt); break; } } public void ResetDataFields() { this.RawText = string.Empty; this.destinationRoomName = string.Empty; this.inventoryItem = null; } } // Interface public interface ISubinteractable { List<SubInteraction> SubIntList { get; set; } }
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual; using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual; using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual; using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual { /// <summary> /// Implementacion del Adaptador de Plantilla Párrafo Variable /// </summary> public class PlantillaRequerimientoParrafoVariableAdapter { /// <summary> /// Realiza la adaptación de campos para la búsqueda /// </summary> /// <param name="plantillaParrafoVariableLogic">Entidad lógica Plantilla Párrafo Variable para la búsqueda</param> /// <returns>Clase Plantilla Párrafo Variable Response con los datos de búsqueda</returns> public static PlantillaRequerimientoParrafoVariableResponse ObtenerPlantillaParrafoVariable(PlantillaRequerimientoParrafoVariableLogic plantillaParrafoVariableLogic) { var plantillaParrafoVariableResponse = new PlantillaRequerimientoParrafoVariableResponse(); plantillaParrafoVariableResponse.CodigoPlantillaParrafoVariable = plantillaParrafoVariableLogic.CodigoPlantillaParrafoVariable; plantillaParrafoVariableResponse.CodigoPlantillaParrafo = plantillaParrafoVariableLogic.CodigoPlantillaParrafo; plantillaParrafoVariableResponse.CodigoVariable = plantillaParrafoVariableLogic.CodigoVariable; plantillaParrafoVariableResponse.Orden = plantillaParrafoVariableLogic.Orden; plantillaParrafoVariableResponse.CodigoTipoVariable = plantillaParrafoVariableLogic.CodigoTipoVariable; plantillaParrafoVariableResponse.NombreVariable = plantillaParrafoVariableLogic.NombreVariable; plantillaParrafoVariableResponse.IdentificadorVariable = plantillaParrafoVariableLogic.IdentificadorVariable; plantillaParrafoVariableResponse.DescripcionVariable = plantillaParrafoVariableLogic.DescripcionVariable; return plantillaParrafoVariableResponse; } /// <summary> /// Realiza la adaptación de campos para registrar o actualizar /// </summary> /// <param name="data">Datos a registrar o actualizar</param> /// <returns>Entidad Plantilla Párrafo Variable con los datos a registrar</returns> public static PlantillaRequerimientoParrafoVariableEntity RegistrarPlantillaParrafoVariable(PlantillaRequerimientoParrafoVariableRequest data) { var plantillaParrafoVariableEntity = new PlantillaRequerimientoParrafoVariableEntity(); if (data.CodigoPlantillaParrafoVariable != null) { plantillaParrafoVariableEntity.CodigoPlantillaParrafoVariable = new Guid(data.CodigoPlantillaParrafoVariable); } else { Guid code; code = Guid.NewGuid(); plantillaParrafoVariableEntity.CodigoPlantillaParrafoVariable = code; } plantillaParrafoVariableEntity.CodigoPlantillaParrafo = new Guid(data.CodigoPlantillaParrafo); plantillaParrafoVariableEntity.CodigoVariable = new Guid(data.CodigoVariable); plantillaParrafoVariableEntity.Orden = Convert.ToInt16(data.Orden); return plantillaParrafoVariableEntity; } } }
using FluentAssertions; using NUnit.Framework; namespace Hatchet.Tests.HatchetConvertTests.DeserializeTests { [TestFixture] public class TypeFactoryTests { public class TestClass { public TestValue Value { get; set; } } public class TestValue { public string Value { get; } public TestValue(string value) { Value = value; } } public class TestClassTwo { public TestValueTwo Value { get; set; } } public class TestValueTwo { public string Value { get; set; } [HatchetConstructor] public static TestValueTwo Create(string value) { return new TestValueTwo { Value = value }; } } [Test] public void Deserialize_PropertyWithTypeThatHasAConstructorThatTakesAString_ValueIsObtainedFromTheFactory() { // Arrange var input = "{ Value 1234 }"; // Act var result = HatchetConvert.Deserialize<TestClass>(input); // Assert result.Value.Value.Should().Be("1234"); } [Test] public void Deserialize_PropertyWithTypeThatHasAStaticConstructorMethod_ValueIsObtainedFromTheFactory() { // Arrange var input = "{ Value 1234 }"; // Act var result = HatchetConvert.Deserialize<TestClassTwo>(input); // Assert result.Value.Value.Should().Be("1234"); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Communicator.Core.Domain; namespace Communicator.Infrastructure.IRepositories { public interface IMessageRepository { Task Add(Message message); Task<Message> Get(Guid id); Task<IEnumerable<Message>> GetTo(Guid toUserId); Task<IEnumerable<Message>> GetFrom(Guid fromUserId); Task Delete(Guid id); Task Update(Message message); } }
 // --------------------------------------------------------------------------- // Lab #4 Programming Exercise // Brian Herbst // CS 1400 Section X01 // -------------------------- //--------------------------- // I declare that the following code was written by me or provided // by the instructor for this project. I understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. //--------------------------- using System; class Program { static void Main() { // declarations string name; string course; int age; double value; // Here you must supply code that does the following: // Prompt the user to enter their full name Console.WriteLine("Please enter your full name: "); // Get their name and store it in the variable name name = Console.ReadLine(); // Prompt the user to enter their course and section Console.WriteLine("Now please enter your course number and section: "); // Get their course and section and store it in the variable course course = Console.ReadLine(); // Prompt the user for their age Console.WriteLine("How old are you? "); // Get their age and store it in the variable age age = int.Parse(Console.ReadLine()); // Prompt the user for how much money they have Console.WriteLine("How much money do you have on you? "); // Get the amount of money and store it in the variable value value = double.Parse(Console.ReadLine()); // Now display the following. Use format specifiers // to control the format of your output: // The person's name. You must display the full name Console.WriteLine("Thank you {0}", name); // The person's course and section Console.WriteLine("In {0}", course); // The person's age Console.WriteLine("Your age is {0}", age); // The amount of money the person has. Display the dollar symbol // and two digits after the decimal point. Console.WriteLine("You have {0:c}", value); Console.ReadLine(); }//End Main() }//End class Program
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace TestDataGenerator.Core { [DataContract] public class GenerationConfig { private string _seed; [DataMember(Name="seed")] public string Seed { get { return _seed; } set { _seed = value; if (_seed != null) _Random = new Random(GetHashCode(_seed)); } } [DataMember(Name = "patternfiles")] public List<string> PatternFiles{get;set;} private bool _loadDefaultPatternFile; [DataMember(Name = "LoadDefaultPatternFile")] public bool LoadDefaultPatternFile { get { return _loadDefaultPatternFile; } set { _loadDefaultPatternFile = value; } } [DataMember(Name = "NamedPatterns")] public NamedPatterns NamedPatterns { get; set; } private Random _Random; public Random Random { get { return _Random; } set { _Random = value; } } public GenerationConfig() { LoadDefaultPatternFile = false; PatternFiles = new List<string>(); NamedPatterns = new NamedPatterns(); var rand = new Random(); Seed = rand.Next(int.MinValue, int.MaxValue).ToString(); } private int GetHashCode(string value) { int hash; if (int.TryParse(value, out hash)) return hash; return value.GetHashCode(); } } }
using BoardGame.Domain_Model; using System; using System.Drawing; using System.Windows.Forms; namespace BoardGame.BusinessLogics { public class ActionControl { private BoardGame m_BoardGameForm; private GameHandler m_GameHandler; private Player player; private Robot robot1; private Robot robot2; private Robot robot3; public ActionControl(GameHandler gameHandler, BoardGame boardGame) { m_GameHandler = gameHandler; m_BoardGameForm = boardGame; player = gameHandler.player; robot1 = gameHandler.robot1; robot2 = gameHandler.robot2; robot3 = gameHandler.robot3; } public void PlayerAfterChangeHisPositionAction() { int Bill = 0; string ownedText = ""; bool ownedField = false; foreach (Field field in m_BoardGameForm.OwnedProperties) { if (field.FieldLocation == player.CurrentPosition) { ownedField = true; if (field.StartedField && field.FieldOwner != player) { Bill = (int)Math.Round(field.FieldFinishedValue * 0.25); if (TheFieldOwnerIsLost(field)) { ownedText = "Nem kell fizetned, mivel" + field.FieldOwner.Name + " már kiesett!"; } else { if (player.HasAFriend) { MessageBox.Show("Szerencsés vagy, hogy ilyen barátod van! Kifizette helyetted.", player.Name); } else { ChangePlayerBalanceIfItIsNeccessery(field, Bill, ref ownedText); } } UpdateRobotsBalance(field, Bill); } else if (!field.StartedField && field.FieldOwner != player) { Bill = (int)Math.Round(field.FieldFinishedValue * 0.4); if (TheFieldOwnerIsLost(field)) { ownedText = "Nem kell fizetned, mivel" + field.FieldOwner.Name + " már kiesett!"; } else { ChangePlayerBalanceIfItIsNeccessery(field, Bill, ref ownedText); } UpdateRobotsBalance(field, Bill); } else if (field.StartedField && field.FieldOwner == player) { ownedText = "Sajnáljuk " + player.Name + ", ezen a teruleten már ásatást végzel."; } else if (!field.StartedField && field.FieldOwner == player) { ownedText = "Sajnáljuk " + player.Name + ", ezen a teruleten már ásatást végeztél."; } } } if (ownedField) { MessageBox.Show(ownedText, player.Name + " ez Magánterület!"); m_BoardGameForm.DrawTheCard.Enabled = false; m_BoardGameForm.ThrowWithTheCubes.Enabled = false; m_BoardGameForm.EndTurn.Enabled = true; } else { FourCornerAction(); } } private void ButtonEnableChangeForTheEndOfTheTurn() { m_BoardGameForm.EndTurn.Enabled = true; m_BoardGameForm.ThrowWithTheCubes.Enabled = false; } private void UpdateRobotsBalance(Field field, int Bill) { if (field.FieldOwner == robot1 && !robot1.Loser) { robot1.Balance += Bill; m_BoardGameForm.Robot1Balance.Text = robot1.Balance.ToString(); } else if (field.FieldOwner == robot2 && !robot2.Loser) { robot2.Balance += Bill; m_BoardGameForm.Robot2Balance.Text = robot2.Balance.ToString(); } else if (field.FieldOwner == robot3 && !robot3.Loser) { robot3.Balance += Bill; m_BoardGameForm.Robot3Balance.Text = robot3.Balance.ToString(); } } private void ChangePlayerBalanceIfItIsNeccessery(Field field, int Bill, ref string ownedText) { player.Balance -= Bill; ownedText = "Sajnáljuk " + player.Name + ", ezen a teruleten " + field.FieldOwner.Name + " már ásatást végez. Az itt tartózkodásod nem ingyenes. A tulajdonosnak a terület jövedelmének(" + field.FieldFinishedValue + " $) a 25%-t ki kell fizetned, ami " + Bill + " $"; // if the player ballance less then 0 after the bill if (player.Balance < 0) { if (player.HasAGuardien > 0) { player.HasAGuardien -= 1; MessageBox.Show("Az őrangyalod most megmentett, de többször már nem tud!", player.Name); player.Balance += Bill; m_BoardGameForm.PlayerBalance.Text = player.Balance.ToString(); } else { m_BoardGameForm.PlayerBalance.Text = player.Balance.ToString(); m_GameHandler.PlayerGoesIntoFailure(); } } else { m_BoardGameForm.PlayerBalance.Text = player.Balance.ToString(); } } private bool TheFieldOwnerIsLost(Field field) { if ((field.FieldOwner == robot1 && robot1.Loser) || (field.FieldOwner == robot2 && robot2.Loser) || (field.FieldOwner == robot3 && robot3.Loser)) { return true; } else { return false; } } private void FourCornerAction() { if (player.CurrentPosition != 0 && player.CurrentPosition != 10 && player.CurrentPosition != 20 && player.CurrentPosition != 30) { m_BoardGameForm.DrawTheCard.Enabled = true; m_BoardGameForm.ThrowWithTheCubes.Enabled = false; m_BoardGameForm.EndTurn.Enabled = false; } else { if (player.CurrentPosition == 0) { ButtonEnableChangeForTheEndOfTheTurn(); } else if (player.CurrentPosition == 10) { if (player.IsPointful) { MessageBox.Show("Talpraesettségednek köszönhetően megúsztad a hegyomlást.", player.Name); ButtonEnableChangeForTheEndOfTheTurn(); } else { MessageBox.Show("Beszorultál, a mentőalakulatok mindjárt itt vannak. Kimaradsz 2 körböl.", player.Name); PlayerCanNotRoll(2); } } else if (player.CurrentPosition == 20) { MessageBox.Show("Enni is kell valamit, tarts egy kis szünetet. Kimaradsz egy körböl.", player.Name); PlayerCanNotRoll(1); } else if (player.CurrentPosition == 30) { MessageBox.Show("Szórakoztál kicsit, dobj egyet a két kockával és annyit vissza kell lépned.", player.Name); m_GameHandler.JumpWithTheFigureToTheNextPosition(-m_GameHandler.RollTheDice()); PlayerAfterChangeHisPositionAction(); } } } private void PlayerCanNotRoll(int howManyTurnHeWillMiss) { player.CanNotRollForXTurn += howManyTurnHeWillMiss; m_BoardGameForm.PlayerCanRoll.Text = player.CanNotRollForXTurn + "-körig kimaradsz!"; m_BoardGameForm.PlayerCanRoll.ForeColor = Color.Red; ButtonEnableChangeForTheEndOfTheTurn(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace com.Sconit.Web.Models.SearchModels.ORD { public class ReceiptDetailSearchModel : SearchModelBase { public string ReceiptNo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using BikeDistributor.Data.Entities; using BikeDistributor.Interfaces.CommonServices; using BikeDistributor.Interfaces.Services; using BikeDistributor.Models; using BikeDistributor.Services.Data; using BikeDistributor.Services.Common; using Unity.Interception.Utilities; namespace BikeDistributor.Services { public class OrderService: BaseService, IOrderService { private readonly IDataRepositoryService _dataRepositoryService; private readonly IDiscountService _discountService; public OrderService(IDataRepositoryService dataRepositoryService, IDiscountService discountService) { _dataRepositoryService = dataRepositoryService; _discountService = discountService; } public virtual OrderModel CalculateTotals(OrderModel orderModel) { if (orderModel.OrderedBy.Location == null) { var err = $"Location info was not found for {orderModel.OrderedBy.CompanyName}"; LogService.Error(err); throw new Exception(err); } var location = orderModel.OrderedBy.Location.SingleOrDefault(x => x.Type == "Billing"); if (location == null) { var err = $"Billing info was not found for {orderModel.OrderedBy.CompanyName}"; LogService.Error(err); throw new Exception(err); } foreach (var orderLineModel in orderModel.OrderLines) { if (orderLineModel.Product.DiscountedPrice.Equals(0)) { orderLineModel.Product.DiscountedPrice = orderLineModel.Product.Msrp; } orderLineModel.Product.TaxedPrice = orderLineModel.Product.DiscountedPrice * (1 + location.TaxRate); orderModel.TaxTotal += (orderLineModel.Product.TaxedPrice - orderLineModel.Product.DiscountedPrice) * orderLineModel.Quantity; orderModel.SubTotal += orderLineModel.Product.TaxedPrice * orderLineModel.Quantity; } return orderModel; } public virtual OrderModel GetOne(Expression<Func<Order, bool>> filter = null, string includeProperties = null) { var dbResult = _dataRepositoryService.GetOne<OrderModel, Order>(filter, includeProperties); var discountedResult = _discountService.CalculateDiscount(dbResult); var calculatedResult = CalculateTotals(discountedResult); return calculatedResult; } public virtual void Create(OrderModel orderModel, string createdBy = null) { try { _dataRepositoryService.Create<OrderModel,Order>(orderModel, createdBy); } catch (Exception e) { Console.WriteLine(e); throw; } } } }
using ArquiteturaLimpaMVC.Dominio.Entidades; using MediatR; namespace ArquiteturaLimpaMVC.Aplicacao.Produtos.Queries { public class ProdutoPorIdQuery : IRequest<Produto> { public int Id { get; set; } public ProdutoPorIdQuery(int id) { Id = id; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task5_Matrix { public class Logic { public void Start() { int mainMenuInput = Input.MainMenu(); if (mainMenuInput == 1) { Matrix firstMatrix = CreateMatrixbyUserVariant(); Print(firstMatrix); Console.WriteLine("Создадим вторую матрицу."); Matrix secondMatrix = CreateMatrixbyUserVariant(); Print(secondMatrix); Matrix result = firstMatrix + secondMatrix; Console.WriteLine(); Console.WriteLine("Итог:"); GetMatrixStaticInfo(result); Console.ReadLine(); } if (mainMenuInput == 2) { Matrix firstMatrix = CreateMatrixbyUserVariant(); Print(firstMatrix); Console.WriteLine("Создадим вторую матрицу."); Matrix secondMatrix = CreateMatrixbyUserVariant(); Print(secondMatrix); Matrix result = firstMatrix * secondMatrix; Console.WriteLine(); Console.WriteLine("Итог:"); GetMatrixStaticInfo(result); Console.ReadLine(); } if (mainMenuInput == 3) { Matrix firstMatrix = CreateMatrixbyUserVariant(); Print(firstMatrix); Console.WriteLine("Создадим вектор."); int vectorSize = Input.GetVectorSize(); Vector vector = FillVectorbyUserInput(vectorSize); Matrix result = firstMatrix * vector; Console.WriteLine(); Console.WriteLine("Итог:"); GetMatrixStaticInfo(result); Console.ReadLine(); } } public Matrix CreateMatrixbyUserVariant() { Matrix matrix = new Matrix(); int matrixInputVarian = Input.MatrixCreateVariant(); if (matrixInputVarian == 1) { int rows = Input.GetRowsCount(); int columns = Input.GetColumnsCount(); matrix = MatrixCreater.CreateRandomMatrix(rows, columns); } if(matrixInputVarian == 2) { int rows = Input.GetRowsCount(); int columns = Input.GetColumnsCount(); matrix = FillMatrixbyUserInput(rows, columns); } if (matrixInputVarian == 3) { matrix = GetMatrixFromFile(); } return matrix; } public Matrix GetMatrixFromFile() { Matrix matrix = new Matrix(); string fileName = "Matrix.txt"; string directory = Directory.GetCurrentDirectory(); string path = directory + "//" + fileName; string[] fileContent = File.ReadAllLines(directory + "//" + fileName); if (fileContent == null) throw new FormatException("Файл не соделжит данные для создания матрицы"); matrix.Massive = new int[3, 3]; int lineNum = 0; int elementNum = 0; int[,] massive; foreach (string line in fileContent) { string[] rowsElements = line.Split(','); foreach (string element in rowsElements) { int elementInNumberFormat = int.Parse(element); matrix.Massive[lineNum, elementNum] = elementInNumberFormat; elementNum++; } lineNum++; elementNum = 0; } return matrix; } public Matrix FillMatrixbyUserInput(int rows, int columns) { Matrix matrix = new Matrix { Massive = new int[rows, columns] }; int elementNumber = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { matrix.Massive[i, j] = Input.GetMatrixElements(elementNumber); elementNumber++; } } return matrix; } public Vector FillVectorbyUserInput(int size) { Vector vector = new Vector { Massive = new int[size] }; int elementNumber = 0; for (int i = 0; i < size; i++) { vector.Massive[i] = Input.GetMatrixElements(elementNumber); elementNumber++; } return vector; } public void Print(Matrix matrix) { Console.WriteLine(); for (int i = 0; i < matrix.RowCount; i++) { for (int j = 0; j < matrix.ColumnCount; j++) { Console.Write(matrix.Massive[i, j] + " "); } Console.WriteLine(); } } public void GetMatrixStaticInfo(Matrix matrix) { Print(matrix); GetSumOfPositiveNumbers(matrix); PrintOnlyPositiveElements(matrix); PrintEvenElements(matrix); PrintPrimeElements(matrix); } public void GetSumOfPositiveNumbers(Matrix matrix) { if (matrix.Massive == null) throw new ArgumentException("Матрица пуста"); int positiveElementsSum = 0; for (int i = 0; i < matrix.RowCount; i++) { for (int j = 0; j < matrix.ColumnCount; j++) { if (matrix.Massive[i, j] > 0) positiveElementsSum += matrix.Massive[i, j]; } Console.WriteLine(); } Console.WriteLine("Сумма положительных элементов матрицы: "+ positiveElementsSum); } public void PrintOnlyPositiveElements(Matrix matrix) { Console.WriteLine("Только положительные элементы:"); Console.WriteLine(); for (int i = 0; i < matrix.RowCount; i++) { for (int j = 0; j < matrix.ColumnCount; j++) { if (matrix.Massive[i, j] > 0) Console.Write(matrix.Massive[i, j] + " "); if (matrix.Massive[i, j] <= 0) Console.Write("*" + " "); } Console.WriteLine(); } } public void PrintEvenElements(Matrix matrix) { Console.WriteLine("Только четные элементы"); Console.WriteLine(); for (int i = 0; i < matrix.RowCount; i++) { for (int j = 0; j < matrix.ColumnCount; j++) { if (CheckForEven(matrix.Massive[i, j])) Console.Write(matrix.Massive[i, j] + " "); else Console.Write("*" + " "); } Console.WriteLine(); } } public void PrintPrimeElements(Matrix matrix) { Console.WriteLine("Только простые элементы"); Console.WriteLine(); for (int i = 0; i < matrix.RowCount; i++) { for (int j = 0; j < matrix.ColumnCount; j++) { if (IsPrimeNumber(matrix.Massive[i, j])) Console.Write(matrix.Massive[i, j] + " "); else Console.Write("*" + " "); } Console.WriteLine(); } } public bool IsPrimeNumber(int number) { int sqrtNumber = (int)(Math.Sqrt(number)); for (int i = 2; i <= sqrtNumber; i++) { if (number % 2 == 0) return false; } return true; } public bool CheckForEven(int number) { if (number % 2 == 0) return true; return false; } } }
using DataStructure.Abstractions; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace DataStructure.Models { public class Song : BaseModel { [Required] [StringLength(30, MinimumLength = 3)] public string SongName { get; set; } public int SongId { get; set; } public List<PerformerSong> PerformersSongs { get; set; } public List<PlayList> PlayLists { get; set; } } }
using Client.Helpers.Paint; using System.Windows; using System.Windows.Controls; using System.Windows.Ink; using Sardf; using Client.Helpers.Extension; using System.IO; using System.Windows.Media.Imaging; using System.Windows.Media; using System; using Client.Helpers; using MahApps.Metro.Controls.Dialogs; using WPF.NewClientl.UIHelpers; namespace WPF.NewClientl.UI.Paint { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class PaintPageWindow : Window { MyInkCanvas mycanvas; protected System.Drawing.Bitmap backgroudImage { get; set; } public PaintPageWindow() { InitializeComponent(); } private void ToolBarClick(object sender, RoutedEventArgs e) { if (sender == null) return; var button = (Button)sender; var param = button.Tag.ToString(); if (param.IsNullOrEmptry()) { return; } switch (param) { case "Pen": mycanvas.SetInkAttributes( PaintEnum.Curve); break; case "Save": GetResultImage(); break; case "Close":this.Close();break; case "Ellipse": mycanvas.SetInkAttributes(PaintEnum.Ellipse); break; case "Arrow": mycanvas.SetInkAttributes(PaintEnum.Arrow); break; case "Color": PopupColor.IsOpen = true ; break; case "Redo": StrokeCollection s = mycanvas.Strokes; if (s.Count > 0) s.Remove(s[s.Count - 1]); ; break; case "Rectangle": mycanvas.SetInkAttributes(PaintEnum.Rectangle); break; case "Clear": mycanvas.Strokes.Clear(); mycanvas.Children.Clear(); break; } } #region 将内容截图成bmp private void GetResultImage() { Rect rect = mycanvas.Strokes.GetBounds(); if (!Double.IsPositiveInfinity(rect.X) && !Double.IsPositiveInfinity(rect.Y)) { Rect r = new Rect() { X = 0, Y = 0, Width =backgroudImage.Width, Height = backgroudImage.Height }; RectangleGeometry rg = new RectangleGeometry() { Rect = r }; RenderTargetBitmap RT = CopyUIElementToClipboard(mycanvas, r); System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog(); dlg.Filter = //"Ink Serialized Format (*.isf)|*.isf|" + "Bitmap files (*.bmp)|*.bmp"; if (dlg.ShowDialog()== System.Windows.Forms.DialogResult.OK) { FileStream file = new FileStream(dlg.FileName, FileMode.Create, FileAccess.Write); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(RT)); encoder.Save(file); file.Close(); mycanvas.Clip = null; this.ShowUiMessageBox("保存成功"); } } else { System.Windows.MessageBox.Show("没有内容!"); } } public RenderTargetBitmap CopyUIElementToClipboard(FrameworkElement ui, Rect rect) { double width = rect.Width; double height = rect.Height; RenderTargetBitmap bmp = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Default); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(ui); dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height))); } bmp.Render(dv); System.Windows.Clipboard.SetImage(bmp); //剪切板 return bmp; } #endregion private void ToolColorClick(object sender, RoutedEventArgs e) { if (sender == null) return; var button = (Button)sender; var param = button.Tag.ToString(); if (param.IsNullOrEmptry()) return; switch (param) { case "BLUE": mycanvas.SetColorBrush(Brushes.Blue); break; case "WHITE": mycanvas.SetColorBrush(Brushes.White); break; case "YELLOW": mycanvas.SetColorBrush(Brushes.Yellow); break; case "BLACK": mycanvas.SetColorBrush(Brushes.Black); break; case "GREEN": mycanvas.SetColorBrush(Brushes.Green); break; case "RED": mycanvas.SetColorBrush(Brushes.Red); break; } PopupColor.IsOpen = false; } private void Window_Loaded(object sender, RoutedEventArgs e) { //backgroudImage = ScreenHelper.GetScreenImage(); //var bitImage = ScreenHelper.BitmapToBitmapImage(backgroudImage); //mycanvas = new MyInkCanvas(bitImage); //frame1.Content = mycanvas; } } }
using System; using System.Collections; using System.Collections.Generic; using com.Sconit.Entity; using com.Sconit.Entity.SYS; using System.ComponentModel.DataAnnotations; //TODO: Add other using statements here namespace com.Sconit.Entity.FMS { public partial class MaintainPlan { #region Non O/R Mapping Properties [CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.MaintainPlanType, ValueField = "Type")] [Display(Name = "MaintainPlan_Type", ResourceType = typeof(Resources.FMS.MaintainPlan))] public string TypeDescription { get; set; } #endregion } }
using System; using FluentAssertions; using Xunit; namespace PluralsightDdd.SharedKernel.UnitTests.DateTimeRangeTests { public class DateTimeRange_NewEnd { [Fact] public void ReturnsNewObjectWithGivenEndDate() { DateTime newEndTime = DateTimes.TestDateTime.AddHours(2); var dtr = new DateTimeRange(DateTimes.TestDateTime, TimeSpan.FromHours(1)); var newDtr = dtr.NewEnd(newEndTime); dtr.Should().NotBeSameAs(newDtr); newDtr.End.Should().Be(newEndTime); } } }
namespace CheckIt.Compilation { using System.Collections.Generic; public interface ICompilationInfo { ICompilationProject Project { get; } IEnumerable<T> Get<T>(ICompilationDocument document); IEnumerable<T> Get<T>(); } }
using System.Web.Http; using System.Web.Http.Cors; using Microsoft.Practices.Unity; using Owin; namespace SmallWebApi.Starter { public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.Add(config.Formatters.JsonFormatter); var container = new UnityContainer(); var unityInitializer = new UnityInitializer(); unityInitializer.Initialize(container); config.DependencyResolver = new UnityResolver(container); config.EnableCors(new EnableCorsAttribute("*", "*", "*")); app.UseWebApi(config); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using MyHotel.Business.Entity.Utilities; using MyHotel.LINQDB; using MyHotel.Utils; using System.Data; namespace MyHotel.Business.WebControls.Utilities { public class UtilitiesController { private static UtilitiesItemsEntity UtilitiesItemToUtilitiesItemsEntity(UtilitiesItem e, DateTime startDate, DateTime endDate, IEnumerable<int> utilitiesItemsDetailsIDs) { UtilitiesItemsEntity item = new UtilitiesItemsEntity() { UtilitiesItemsID = e.UtilitiesItemsID, Name = e.Name }; item.UtilitiesDetailsEntities = new List<UtilitiesDetailsEntity>(); IEnumerable<UtilitiesItemsDetail> utilitiesItemsDetails = null; if (startDate != DateTime.MinValue && endDate != DateTime.MinValue) { utilitiesItemsDetails = e.UtilitiesItemsDetails.Where(s => s.Date >= startDate && s.Date <= endDate); } else if (utilitiesItemsDetailsIDs != null) { utilitiesItemsDetails = e.UtilitiesItemsDetails.Where(s => utilitiesItemsDetailsIDs.Any(u => u == s.UtilitiesItemsDetailsID)); } if (utilitiesItemsDetails != null) { foreach (var subItem in utilitiesItemsDetails) { item.UtilitiesDetailsEntities.Add(new UtilitiesDetailsEntity() { UtilitiesItemsDetailsID = subItem.UtilitiesItemsDetailsID, UtilitiesItemsID = item.UtilitiesItemsID, Date = subItem.Date, Description = subItem.Description, Value = subItem.Value }); } } return item; } public static List<UtilitiesItemsEntity> GetUtilitiesItems(DateTime startDate, DateTime endDate) { using (DataClassesDataContext dataContext = HelperCommon.GetDataContext()) { return dataContext.UtilitiesItems.Select(e => UtilitiesItemToUtilitiesItemsEntity(e, startDate, endDate, null)).ToList(); } } public static List<UtilitiesItemsEntity> GetUtilitiesItems() { using (DataClassesDataContext dataContext = HelperCommon.GetDataContext()) { return dataContext.UtilitiesItems.Select(e => UtilitiesItemToUtilitiesItemsEntity(e, DateTime.MinValue, DateTime.MinValue, null)).ToList(); } } public static List<UtilitiesItemsEntity> GetUtilitiesItems(IEnumerable<int> utilitiesItemsDetailsIDs) { using (DataClassesDataContext dataContext = HelperCommon.GetDataContext()) { return dataContext.UtilitiesItems.Select(e => UtilitiesItemToUtilitiesItemsEntity(e, DateTime.MinValue, DateTime.MinValue, utilitiesItemsDetailsIDs)).ToList(); } } private static object utilitiesDetailsLock = new object(); public static void DeleteUtilitiesItems(IEnumerable<int> utilitiesItemsDetailsIDs) { lock (utilitiesDetailsLock) { using (DataClassesDataContext dataContext = HelperCommon.GetDataContext()) { foreach (var id in utilitiesItemsDetailsIDs) { dataContext.UtilitiesItemsDetails.DeleteAllOnSubmit(dataContext.UtilitiesItemsDetails.Where(s => s.UtilitiesItemsDetailsID == id)); } dataContext.SubmitChanges(); } } } public static void SaveUtilitiesDetails(List<UtilitiesDetailsEntity> utilitiesDetails) { lock (utilitiesDetailsLock) { if (utilitiesDetails == null || !utilitiesDetails.Any()) { throw new InvalidConstraintException("Немає даних для запису"); } using (DataClassesDataContext dataContext = HelperCommon.GetDataContext()) { foreach (var item in utilitiesDetails) { if (item.UtilitiesItemsDetailsID > 0) { UtilitiesItemsDetail utilitiesItemsDetail = dataContext.UtilitiesItemsDetails.FirstOrDefault(s => s.UtilitiesItemsDetailsID == item.UtilitiesItemsDetailsID); if (utilitiesItemsDetail != null) { UpdateDBFromBO(item, utilitiesItemsDetail); } else { throw new InvalidConstraintException("Запис про КП не знайдено №" + item.UtilitiesItemsDetailsID); } } else { dataContext.UtilitiesItemsDetails.InsertOnSubmit(ConvertBOToDB(item)); } } dataContext.SubmitChanges(); } } } private static UtilitiesItemsDetail ConvertBOToDB(UtilitiesDetailsEntity item) { UtilitiesItemsDetail utilitiesItemsDetail = new UtilitiesItemsDetail(); UpdateDBFromBO(item, utilitiesItemsDetail); utilitiesItemsDetail.UtilitiesItemsID = item.UtilitiesItemsID; if (item.UtilitiesItemsDetailsID > 0) { utilitiesItemsDetail.UtilitiesItemsDetailsID = item.UtilitiesItemsDetailsID; } return utilitiesItemsDetail; } private static void UpdateDBFromBO(UtilitiesDetailsEntity item, UtilitiesItemsDetail utilitiesItemsDetail) { utilitiesItemsDetail.Date = item.Date; utilitiesItemsDetail.Description = item.Description; utilitiesItemsDetail.Value = item.Value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SwipeInput : MonoBehaviour { public float minimumSwipeDistanceY; public float minimumSwipeDistanceX; public GameObject mainCanvas; public GameObject subCanvas; private Touch t = default(Touch); private Vector3 startPosition = Vector3.zero; private void Update() { if (Input.touches.Length > 0) { t = Input.touches[0]; switch (t.phase) { case TouchPhase.Began: startPosition = t.position; return; case TouchPhase.Ended: Vector3 positionDelta = (Vector3)t.position - startPosition; if (Mathf.Abs(positionDelta.y) > minimumSwipeDistanceY) { if (positionDelta.y > 0) { Debug.Log("UP SWIPE!!!"); mainCanvas.GetComponent<CanvasGroup>().alpha = 0; subCanvas.GetComponent<CanvasGroup>().alpha = 1; mainCanvas.GetComponent<VerticalLayoutGroup>().enabled = false; //else //{ // mainCanvas.GetComponent<CanvasGroup>().alpha = 1; // subCanvas.GetComponent<CanvasGroup>().alpha = 0; //} } else { Debug.Log("DOWN SWIPE!!!"); mainCanvas.GetComponent<CanvasGroup>().alpha = 1; subCanvas.GetComponent<CanvasGroup>().alpha = 0; mainCanvas.GetComponent<VerticalLayoutGroup>().enabled = true; } } if (Mathf.Abs(positionDelta.x) > minimumSwipeDistanceX) { if (positionDelta.x > 0) { Debug.Log("SWIPE RIGHT"); } else { Debug.Log("SWIPE LEFT"); } } return; default: return; } } } }
using System; namespace Assignemnt_1 { class Program { static void Main(string[] args) { var fruit = new { name = "Mango", amount = 5 }; Console.WriteLine("Fruit name : {0}", fruit.name); } } }
using UnityEngine; using System.Threading.Tasks; using Grpc.Core; using static NetworkService.NetworkService; using NetworkService; public class ComServiceParent : NetworkServiceBase { public override Task<PingReply> PingService(PingRequest request, ServerCallContext context) { return Task.FromResult(new PingReply { ResCode = PingReplyStatus.Success }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightBoxRectSubForm.data { public class BytesWithInfo { public byte[] bytes; public string info; public BytesWithInfo(byte[] bytes, string info) { this.bytes = bytes; this.info = info; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Generate : MonoBehaviour { public int baseStartX = -5; public int baseStartY = 5; public int baseEndX = 5; public int baseEndY = -5; public int r = 2; public int objCOunt = 5; public GameObject[] toPlace; int randomX; int randomY; List<Coordinate> coordinates = new List<Coordinate>(); private void Start() { BoxCollider colliderObj = this.GetComponent<BoxCollider>(); baseStartX = Mathf.RoundToInt(this.transform.position.x-colliderObj.size.x*0.5f); baseStartY = Mathf.RoundToInt(this.transform.position.z-colliderObj.size.z*0.5f); baseEndX = Mathf.RoundToInt(this.transform.position.x+colliderObj.size.x*0.5f); baseEndY = Mathf.RoundToInt(this.transform.position.y+colliderObj.size.z*0.5f); while(coordinates.Count != objCOunt) { randomX = Random.Range(baseStartX, baseEndX + 1); randomY = Random.Range(baseEndY, baseStartY + 1); if (randomX % r == 0 && randomY % r == 0 && !coordinates.Contains(new Coordinate(randomX, randomY))) { int whichToPlace = Random.Range(0, toPlace.Length); coordinates.Add(new Coordinate(randomX, randomY)); Instantiate(toPlace[whichToPlace], new Vector3(randomX, toPlace[whichToPlace].transform.position.y, randomY), Quaternion.Euler(0, Random.Range(0, 360f), 0)); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; using Compent.Extensions; using Compent.Shared.Search.Contract; using UBaseline.Search.Core; using Uintra.Core.Search.Entities; using Uintra.Core.Search.Repository; using Uintra.Features.Media.Helpers; using Uintra.Infrastructure.Constants; using Uintra.Infrastructure.Extensions; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; using Umbraco.Web; using File = System.IO.File; namespace Uintra.Core.Search.Indexers { public class DocumentIndexer : IDocumentIndexer { public Type Type { get; } = typeof(SearchableDocument); private readonly IIndexContext<SearchableDocument> _indexContext; private readonly IUintraSearchRepository<SearchableDocument> _searchRepository; private readonly IMediaHelper _mediaHelper; private readonly IMediaService _mediaService; private readonly ISearchSettings _searchSettings; private readonly ILogger _logger; public DocumentIndexer( IIndexContext<SearchableDocument> indexContext, IUintraSearchRepository<SearchableDocument> searchRepository, IMediaHelper mediaHelper, IMediaService mediaService, ISearchSettings searchSettings, ILogger logger) { _indexContext = indexContext; _searchRepository = searchRepository; _mediaHelper = mediaHelper; _mediaService = mediaService; _searchSettings = searchSettings; _logger = logger; } public async Task<bool> RebuildIndex() { try { var documentsToIndex = GetDocumentsForIndexing().ToList(); var rc = await _indexContext.RecreateIndex(); var r = await Index(documentsToIndex); return true; //return _indexerDiagnosticService.GetSuccessResult(typeof(DocumentIndexer).Name, documentsToIndex); } catch (Exception e) { return false; //return _indexerDiagnosticService.GetFailedResult(e.Message + e.StackTrace, typeof(DocumentIndexer).Name); } } public Task<bool> Delete(IEnumerable<string> nodeIds) { throw new NotImplementedException(); } public Task<int> Index(int id) { return Index(id.ToEnumerable()); } public Task<int> Index(IEnumerable<int> ids) { var medias = _mediaService.GetByIds(ids); var documents = new List<SearchableDocument>(); foreach (var media in medias) { var document = GetSearchableDocument(media.Id); if (!document.Any()) continue; if (!IsAllowedForIndexing(media)) { media.SetValue(UmbracoAliases.Media.UseInSearchPropertyAlias, true); _mediaService.Save(media); } documents.AddRange(document); } return _searchRepository.IndexAsync(documents); //_documentIndex.Index(documents); } public Task<bool> DeleteFromIndex(int id) { return DeleteFromIndex(id.ToEnumerable()); } public Task<bool> DeleteFromIndex(IEnumerable<int> ids) { var medias = _mediaService.GetByIds(ids); foreach (var media in medias) { if (IsAllowedForIndexing(media)) { media.SetValue(UmbracoAliases.Media.UseInSearchPropertyAlias, false); _mediaService.Save(media); } //_documentIndex.Delete(media.Id); } var idsToDelete = ids.Select(id => id.ToString()); return _searchRepository.DeleteAsync(idsToDelete); } private IEnumerable<int> GetDocumentsForIndexing() { var medias = Umbraco.Web.Composing.Current.UmbracoHelper .MediaAtRoot() .SelectMany(m => m.DescendantsOrSelf()); var result = medias .Where(c => IsAllowedForIndexing(c) && !_mediaHelper.IsMediaDeleted(c)) .Select(m => m.Id); return result.ToList(); } private bool IsAllowedForIndexing(IPublishedContent media) { return media.HasProperty(UmbracoAliases.Media.UseInSearchPropertyAlias) && media.GetProperty(UmbracoAliases.Media.UseInSearchPropertyAlias).Value<bool>(); } private bool IsAllowedForIndexing(IMedia media) { return media.HasProperty(UmbracoAliases.Media.UseInSearchPropertyAlias) && media.GetValue<bool>(UmbracoAliases.Media.UseInSearchPropertyAlias); } private IEnumerable<SearchableDocument> GetSearchableDocument(int id) { var content = Umbraco.Web.Composing.Current.UmbracoHelper.Media(id); if (content == null) { return Enumerable.Empty<SearchableDocument>(); } return GetSearchableDocument(content); } private IEnumerable<SearchableDocument> GetSearchableDocument(IPublishedContent content) { var fileName = Path.GetFileName(content.Url); var extension = Path.GetExtension(fileName)?.Trim('.'); var isFileExtensionAllowedForIndex = _searchSettings.IndexingDocumentTypes.Contains(extension, StringComparison.OrdinalIgnoreCase); if (!content.Url.IsNullOrEmpty()) { var physicalPath = HostingEnvironment.MapPath(content.Url); if (!File.Exists(physicalPath)) { _logger.Error<DocumentIndexer>(new FileNotFoundException($"Could not find file \"{physicalPath}\"")); return Enumerable.Empty<SearchableDocument>(); } var base64File = isFileExtensionAllowedForIndex ? Convert.ToBase64String(File.ReadAllBytes(physicalPath)) : string.Empty; var result = new SearchableDocument { Id = content.Id.ToString(), Title = fileName, Url = content.Url.ToLinkModel(), Data = base64File, Type = SearchableTypeEnum.Document.ToInt() }; return result.ToEnumerable(); } return Enumerable.Empty<SearchableDocument>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using RazorSample1.Models; using RazorSample1.Services; namespace RazorSample1.Pages.Catalog { public class detailsModel : PageModel { private readonly IItemRepository itemRepository; public detailsModel(IItemRepository itemRepository) { this.itemRepository = itemRepository; } public Item Item { get; private set; } public IActionResult OnGet(int id) { Item = itemRepository.GetItem(id); if (Item==null) { return RedirectToPage("/NotFound"); } return Page(); } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Game.UI { [AddComponentMenu("Layout/UIHidable")] [RequireComponent(typeof(LayoutElement))] [RequireComponent(typeof(Toggle))] /// <summary> /// 利用Toggle实现的抽屉式Panel,点击时可变换大小。 /// </summary> ///<remarks>如果是手工创建的,则需要确保registClick勾选,才会默认产生点击时的隐藏/显示事件</remarks> class UIPanelHidable:MonoBehaviour { public enum HideDirection { Vertical, Horizontal, }; //--子物体:需要隐藏的panel部分 [SerializeField]RectTransform m_hidablePanel; [SerializeField]HideDirection m_hideDirection = HideDirection.Vertical; //--默认(隐藏内容panel)时的大小(忽略height的拼写) [SerializeField]int m_defaultSize; //--展开Panel时的大小(忽略height) [SerializeField]int m_expandSize; [Tooltip("Regist click event of toggle when enable this component")] [SerializeField]bool m_registClick = false; /// <summary> /// Expand detail panel /// </summary> public void ShowPanel() { SwitchPanelTo(true); } /// <summary> /// Hide detail panel /// </summary> public void HidePanel() { SwitchPanelTo(false); } /// <summary> /// 在需要时对Toggle的valueChanged进行事件的注册,以实现勾选时的显示/隐藏效果 /// </summary> private void Awake() { if (m_registClick) { this.GetComponent<Toggle>().onValueChanged.AddListener((isOn) => { if (isOn) ShowPanel(); else HidePanel(); }); } //hide the panel HidePanel(); } private void SwitchPanelTo(bool isOn) { if (isOn) { //允许不填写expandSize,默认开启Object即可 if (m_expandSize > 0) { //switch on SetLayoutHeight(m_expandSize); } } else { //off SetLayoutHeight(m_defaultSize); } m_hidablePanel.gameObject.SetActive(isOn); } private void SetLayoutHeight(int size) { LayoutElement layout = GetComponent<LayoutElement>(); switch(m_hideDirection) { case HideDirection.Vertical: layout.preferredHeight = size; layout.minHeight = size; break; case HideDirection.Horizontal: layout.preferredWidth = size; layout.minWidth = size; break; } } } }