text
stringlengths
13
6.01M
using System.Data.Entity; using System.Linq; using System.Net; using System.Web.Mvc; using Web.Areas.Admin.Views.CheckListItems; using Web.Data; using Web.Models; namespace Web.Areas.Admin.Controllers { [Authorize(Roles = "Admin, Manager")] public class CheckListItemsController : Controller { private readonly ApplicationDbContext _context = new ApplicationDbContext(); public ActionResult Index(int id) { var checkList = _context.CheckLists.FirstOrDefault(x => x.Id == id); if (checkList != null) ViewBag.Title = checkList.Subject; var checkListItems = _context.CheckListItems.Include(c => c.CheckList).OrderBy(c => c.SortOrder); return View(checkListItems.ToList()); } public ActionResult Manage(int id) { var checkList = _context.CheckLists.FirstOrDefault(x => x.Id == id); if (checkList != null) { ViewBag.Title = checkList.Subject; ViewBag.CheckListId = checkList.Id; } var checkListItems = _context.CheckListItems.Include(c => c.CheckList).Where(i => i.CheckListId == id); return View(checkListItems.ToList()); } public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var checkListItem = _context.CheckListItems.Find(id); if (checkListItem == null) { return HttpNotFound(); } return View(checkListItem); } public ActionResult Create(int id) { var viewModel = new CreateCheckListItemViewModel(); var checkList = _context.CheckLists.FirstOrDefault(c => c.Id == id); viewModel.CheckListId = id; if (checkList != null) viewModel.ListName = checkList.Subject; return View(viewModel); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create( [Bind(Include = "Subject,Description,CheckListId,SortOrder,IsComplete")] CreateCheckListItemViewModel checkListItem) { if (ModelState.IsValid) { var item = new CheckListItem { Subject = checkListItem.Subject, Description = checkListItem.Description, CheckListId = checkListItem.CheckListId, SortOrder = checkListItem.SortOrder }; _context.CheckListItems.Add(item); _context.SaveChanges(); return RedirectToAction("Manage", new {id = item.CheckListId}); } return View(checkListItem); } public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var checkListItem = _context.CheckListItems.Find(id); if (checkListItem == null) { return HttpNotFound(); } ViewBag.CheckListId = new SelectList(_context.CheckLists, "Id", "Subject", checkListItem.CheckListId); return View(checkListItem); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit( [Bind(Include = "Id,Subject,Description,CheckListId,SortOrder,IsComplete")] CheckListItem checkListItem) { if (ModelState.IsValid) { _context.Entry(checkListItem).State = EntityState.Modified; _context.SaveChanges(); //return RedirectToAction("Index"); return RedirectToAction("Manage", new {id = checkListItem.CheckListId}); } ViewBag.CheckListId = new SelectList(_context.CheckLists, "Id", "Subject", checkListItem.CheckListId); return View(checkListItem); } public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var checkListItem = _context.CheckListItems.Find(id); if (checkListItem == null) { return HttpNotFound(); } return View(checkListItem); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { var checkListItem = _context.CheckListItems.Find(id); _context.CheckListItems.Remove(checkListItem); _context.SaveChanges(); //return RedirectToAction("Index"); return RedirectToAction("Manage", new {id = checkListItem.CheckListId}); } protected override void Dispose(bool disposing) { if (disposing) { _context.Dispose(); } base.Dispose(disposing); } } }
using System; using System.IO; using System.Text; using System.Collections.Generic; using System.Text.RegularExpressions; namespace HTMLMake { public class TextMapper { public Table LogToHtmlTable(string textElement) { // Instantiate table object Table tbl = new Table(); // Set date tbl.date = textElement.Substring(0, 19).Trim(); // Set log level Regex regx_level = new Regex(@"(\s-\s([A-Z]*)\s-\s)"); tbl.level = regx_level.Match(textElement).ToString().Replace(" - ", "").Trim(); // Set log status if (tbl.level.Contains("WARNING") | tbl.level.Contains("ERROR")) { tbl.status = "Failed"; } else { tbl.status = "Success"; } // Splitting strings Regex regx_substr = new Regex(@"(?<=\<).+?(?=\>)"); var substr = regx_substr.Match(textElement).ToString(); // Set subprocess - the actual script Regex regx_module = new Regex(@"((?<=module).[']\w+.)"); tbl.module = regx_module.Match(substr).ToString().Replace("'", "").Trim(); // Set error message Regex regx_msg = new Regex(@"((?<=Message:).*)"); tbl.message = regx_msg.Match(textElement).ToString().Trim(); // Set process Regex regx_strip = new Regex(@"((?=\/home/\w).*(\'>))"); Regex regx_process = new Regex(@"((\/[^/]*\w[^/]*){4})"); var strip = regx_strip.Match(textElement).ToString(); tbl.process = regx_process.Match(strip).ToString().Trim(); return (tbl); } } }
namespace SGDE.DataEFCoreSQL.Repositories { #region Using using System; using System.Collections.Generic; using System.Linq; using Domain.Entities; using Domain.Repositories; using Microsoft.EntityFrameworkCore; using SGDE.Domain.Helpers; #endregion public class InvoiceRepository : IInvoiceRepository, IDisposable { private readonly EFContextSQL _context; public InvoiceRepository(EFContextSQL context) { _context = context; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _context.Dispose(); } } private bool InvoiceExists(int id) { return GetById(id) != null; } public QueryResult<Invoice> GetAll(int skip = 0, int take = 0, string filter = null, int workId = 0, int clientId = 0) { if (filter != null) filter = filter.ToLower(); List<Invoice> data = new List<Invoice>(); if (workId == 0 && clientId == 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.InvoiceToCancel) //.ThenInclude(y => y.DetailsInvoice) //.Include(x => x.Work) //.ThenInclude(x => x.WorkBudgets) //.Include(x => x.DetailsInvoice) .Include(x => x.WorkBudget) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } if (workId != 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.InvoiceToCancel) //.ThenInclude(y => y.DetailsInvoice) //.Include(x => x.Work) //.ThenInclude(x => x.WorkBudgets) //.Include(x => x.DetailsInvoice) .Include(x => x.WorkBudget) .Where(x => x.WorkId == workId) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } if (workId == 0 && clientId != 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.InvoiceToCancel) //.ThenInclude(y => y.DetailsInvoice) //.Include(x => x.Work) //.ThenInclude(x => x.WorkBudgets) //.Include(x => x.DetailsInvoice) .Include(x => x.WorkBudget) .Where(x => x.Work.ClientId == clientId) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } if (!string.IsNullOrEmpty(filter)) { if (filter.Equals("pagado", StringComparison.InvariantCulture)) { data = data .Where(x => x.TaxBase != 0 && x.TotalPayment >= x.TaxBase + x.IvaTaxBase) .ToList(); } else { data = data .Where(x => Searcher.RemoveAccentsWithNormalization(x.Work.Name?.ToLower()).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.Work.Client.Name.ToLower()).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.Name.ToLower()).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.WorkBudget?.Name.ToLower()).Contains(filter) || x.TaxBase.ToString().Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.TaxBase.ToString()).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.Total.ToString()).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.StartDate.ToString("dd/MM/yyyyy")).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.EndDate.ToString("dd/MM/yyyyy")).Contains(filter) || Searcher.RemoveAccentsWithNormalization(x.IssueDate.ToString("dd/MM/yyyyy")).Contains(filter)) .ToList(); } } var count = data.Count; return (skip != 0 || take != 0) ? new QueryResult<Invoice> { Data = data.Skip(skip).Take(take).ToList(), Count = count } : new QueryResult<Invoice> { Data = data.Skip(0).Take(count).ToList(), Count = count }; } public Invoice GetById(int id) { var invoice = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.Work) .ThenInclude(x => x.Invoices) .Include(x => x.InvoiceToCancel) .ThenInclude(x => x.DetailsInvoice) .Include(x => x.InvoiceToCancel) .ThenInclude(x => x.Client) .Include(x => x.Work) .ThenInclude(x => x.WorkBudgets) .Include(x => x.DetailsInvoice) .Include(x => x.WorkBudget) .FirstOrDefault(x => x.Id == id); if (invoice == null) return null; //var ivaTaxBase = Math.Round(invoice.DetailsInvoice.Sum(x => x.Units * x.PriceUnity * x.Iva), 2); //invoice.IvaTaxBase = ivaTaxBase; //invoice.Total = invoice.IvaTaxBase + (double)invoice.TaxBase; return invoice; } public Invoice Add(Invoice newInvoice) { Validate(newInvoice); var invoiceNumber = CountInvoicesInYear(newInvoice.IssueDate.Year); var work = _context.Work.FirstOrDefault(x => x.Id == newInvoice.WorkId); newInvoice.InvoiceNumber = invoiceNumber; if (newInvoice.InvoiceToCancelId == null) { newInvoice.Name = work != null ? $"{work.WorksToRealize}{invoiceNumber:0000}_{newInvoice.IssueDate.Year.ToString().Substring(2, 2)}" : $"{invoiceNumber:0000}_{newInvoice.IssueDate.Year.ToString().Substring(2, 2)}"; } _context.Invoice.Add(newInvoice); _context.SaveChanges(); return newInvoice; } public Invoice AddInvoiceFromQuery(Invoice invoice) { var checkInvoice = CheckInvoice(invoice); if (checkInvoice == null) { using (var transaction = _context.Database.BeginTransaction()) { try { Work work = null; if (invoice.WorkId != null) { work = _context.Work.FirstOrDefault(x => x.Id == invoice.WorkId); invoice.Iva = work != null ? !work.PassiveSubject : true; } else { invoice.Iva = true; } var invoiceNumber = CountInvoicesInYear(invoice.IssueDate.Year); invoice.InvoiceNumber = invoiceNumber; invoice.Name = work != null ? $"{work.WorksToRealize}{invoiceNumber:0000}_{invoice.IssueDate.Year.ToString().Substring(2, 2)}" : $"{invoiceNumber:0000}_{invoice.IssueDate.Year.ToString().Substring(2, 2)}"; _context.Invoice.Add(invoice); _context.SaveChanges(); foreach (var detailInvoice in invoice.DetailsInvoice) { _context.DetailInvoice.Update(detailInvoice); _context.SaveChanges(); } transaction.Commit(); invoice.State = 1; return invoice; } catch (Exception ex) { transaction.Rollback(); throw ex; } } } if (checkInvoice != 0 && checkInvoice != null) { using (var transaction = _context.Database.BeginTransaction()) { try { if (invoice.WorkId != null) { var work = _context.Work.FirstOrDefault(x => x.Id == invoice.WorkId); invoice.Iva = work != null ? !work.PassiveSubject : true; } else { invoice.Iva = true; } var findInvoice = _context.Invoice .Include(x => x.DetailsInvoice) .FirstOrDefault(x => x.Id == checkInvoice); if (findInvoice == null) throw new Exception("Factura no encontrada"); findInvoice.ModifiedDate = DateTime.Now; findInvoice.IssueDate = invoice.IssueDate; findInvoice.TaxBase = invoice.TaxBase; findInvoice.IvaTaxBase = invoice.IvaTaxBase; _context.Invoice.Update(findInvoice); _context.SaveChanges(); _context.DetailInvoice.RemoveRange(findInvoice.DetailsInvoice); _context.SaveChanges(); foreach (var detailInvoice in invoice.DetailsInvoice) { detailInvoice.InvoiceId = findInvoice.Id; _context.DetailInvoice.Add(detailInvoice); _context.SaveChanges(); } transaction.Commit(); findInvoice.State = 2; return findInvoice; } catch (Exception ex) { transaction.Rollback(); throw ex; } } } if (checkInvoice == 0) { using (var transaction = _context.Database.BeginTransaction()) { try { if (invoice.WorkId != null) { var work = _context.Work.FirstOrDefault(x => x.Id == invoice.WorkId); invoice.Iva = work != null ? !work.PassiveSubject : true; } else { invoice.Iva = true; } var findInvoice = _context.Invoice .Include(x => x.DetailsInvoice) .FirstOrDefault(x => x.WorkId == invoice.WorkId && x.StartDate == invoice.StartDate && x.EndDate == invoice.EndDate); if (findInvoice == null) throw new Exception("Factura no encontrada"); _context.DetailInvoice.RemoveRange(findInvoice.DetailsInvoice); _context.SaveChanges(); findInvoice.TaxBase = invoice.TaxBase; findInvoice.IvaTaxBase = invoice.IvaTaxBase; foreach (var detailInvoice in invoice.DetailsInvoice) { detailInvoice.InvoiceId = findInvoice.Id; _context.DetailInvoice.Add(detailInvoice); _context.SaveChanges(); } transaction.Commit(); findInvoice.State = 3; return findInvoice; } catch (Exception ex) { transaction.Rollback(); throw ex; } } } var existInvoice = _context.Invoice .Include(x => x.DetailsInvoice) .FirstOrDefault(x => x.WorkId == invoice.WorkId && x.StartDate == invoice.StartDate && x.EndDate == invoice.EndDate); existInvoice.State = 3; return existInvoice; } public int? CheckInvoice(Invoice newInvoice) { var invoice = _context.Invoice .FirstOrDefault(x => x.WorkId == newInvoice.WorkId && x.StartDate == newInvoice.StartDate && x.EndDate == newInvoice.EndDate); if (invoice == null) return null; if (newInvoice.TaxBase == invoice.TaxBase) { return 0; } return invoice.Id; } public bool Update(Invoice invoice) { if (!InvoiceExists(invoice.Id)) return false; _context.Invoice.Update(invoice); _context.SaveChanges(); return true; } public bool Delete(int id) { if (!InvoiceExists(id)) return false; if (_context.Invoice.FirstOrDefault(x => x.InvoiceToCancelId == id) != null) throw new Exception("No se puede eliminar una Factura que está anulada"); var toRemove = _context.Invoice.Find(id); _context.Invoice.Remove(toRemove); _context.SaveChanges(); return true; } public int CountInvoices() { return _context.Invoice.Count(); } public int CountInvoicesInYear(int year) { var invoiceNumber = 0; var invoices = _context.Invoice .Where(x => x.IssueDate >= new DateTime(year, 1, 1) && x.IssueDate <= new DateTime(year, 12, 31, 23, 59, 59)); if (invoices.Count() > 0) { invoiceNumber = invoices.Select(x => x.InvoiceNumber).Max(); } invoiceNumber++; return invoiceNumber; } public List<Invoice> GetAllBetweenDates(DateTime startDate, DateTime endDate, int workId = 0, int clientId = 0) { List<Invoice> data = new List<Invoice>(); if (workId == 0 && clientId == 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.Work) .Include(x => x.DetailsInvoice) .Where(x => x.IssueDate >= startDate && x.IssueDate <= endDate) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } if (workId != 0 && clientId == 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.Work) .Include(x => x.DetailsInvoice) .Where(x => x.IssueDate >= startDate && x.IssueDate <= endDate && x.WorkId == workId) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } if (workId == 0 && clientId != 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.Work) .Include(x => x.DetailsInvoice) .Where(x => x.IssueDate >= startDate && x.IssueDate <= endDate && x.Work.ClientId == clientId) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } if (workId != 0 && clientId != 0) { data = _context.Invoice .Include(x => x.Work) .ThenInclude(x => x.Client) .Include(x => x.Work) .Include(x => x.DetailsInvoice) .Where(x => x.IssueDate >= startDate && x.IssueDate <= endDate && x.WorkId == workId && x.Work.ClientId == clientId) .ToList() .OrderByDescending(x => x.KeyOrder) .ToList(); } return data; } public List<Invoice> GetAllLite() { var watch = System.Diagnostics.Stopwatch.StartNew(); var result = _context.Invoice .Include(x => x.Work) .Include(x => x.DetailsInvoice) .ToList() .OrderBy(x => x.IssueDate) .Select(x => new Invoice { Id = x.Id, Name = x.Name, WorkId = x.WorkId, IssueDate = x.IssueDate, TaxBase= x.TaxBase, IvaTaxBase = x.IvaTaxBase, DetailsInvoice = x.DetailsInvoice }) .ToList(); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; System.Diagnostics.Debug.WriteLine($"Elapsed time for GetAllLite [Invoices] -> {elapsedMs}ms."); return result; } #region Auxiliary Methods private void Validate(Invoice invoice) { if (invoice.ClientId == null || invoice.WorkId == null) { throw new Exception("Factura incompleta. Revisa los datos"); } var findWork = _context.Work .Include(x => x.WorkBudgets) .FirstOrDefault(x => x.Id == invoice.WorkId); if (findWork == null) { throw new Exception("Obra no encontrada"); } if (findWork.WorksToRealize == "PA" && invoice.WorkBudgetId == null) { throw new Exception("Factura incompleta. Revisa los datos. Debes introducir el presupuesto"); } if (findWork.WorksToRealize == "PA" && invoice.WorkBudgetId != null) { var findWorkBudget = findWork.WorkBudgets.FirstOrDefault(x => x.Id == invoice.WorkBudgetId); if (findWorkBudget == null) { throw new Exception("Presupuesto no encontrado"); } } } private double GetTotalDetailInvoice(Invoice invoice, ICollection<DetailInvoice> detailsInvoices) { if (detailsInvoices?.Count() == 0) return 0; //var retentions = invoice.Work.InvoiceToOrigin == true ? (invoiceViewModel.detailInvoice.Sum(x => x.amountUnits) * (double)invoice.Work.PercentageRetention) : 0; var retentions = 0; var taxBase = Math.Round(detailsInvoices.Sum(x => x.Units * x.PriceUnity), 2); //var ivaTaxBase = Math.Round(detailsInvoices.Sum(x => x.Units * x.PriceUnity * x.Iva), 2); var ivaTaxBase = 0; var total = Math.Round(taxBase + ivaTaxBase - retentions, 2); return total; } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ChatSignalR.Chat { public interface IChatClientManager { Task AddAsync(string userId,string connectionId); Task RemoveAsync(string userId); Task<bool> IsChattingAsync(); Task<Client> GetClientAsync(string userId); Task<IEnumerable<Client>> GetClients(); Task ChangeOnlineStatus(string userId, bool isOnline); Task<bool> IsJoinedAsync(string userId); Task<bool> IsOnlineAsync(string userId); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YzkSoftWare.Data.Sql.MsSql { /// <summary> /// 修改数据MS-SQL的Sql表达式 /// </summary> /// <typeparam name="T"></typeparam> public sealed class UpdateMsSqlExpress<T> : MsSqlExpressBase where T : class { public UpdateMsSqlExpress() : base(null, DataModel.DbTypeForDataModel.Sql, SqlExpressResult.EffectCount) { } /// <summary> /// 要修改的数据 /// </summary> public T UpdateItem { get; private set; } /// <summary> /// 要修改的数据的字段范围 /// </summary> public FieldSelectRange UpdateFieldRange { get; private set; } /// <summary> /// UpdateFieldRange指定的字段范围的字段名称 /// </summary> public IEnumerable<string> UpdateFieldNames { get; private set; } /// <summary> /// 设置要修改的数据 /// </summary> /// <param name="updateItem">要修改的数据</param> /// <param name="range">修改值的字段范围</param> /// <param name="upfieldnames">range指定的字段范围的字段名称</param> public void SetUpdateItem(T updateItem, FieldSelectRange range, IEnumerable<string> upfieldnames) { UpdateItem = updateItem; UpdateFieldRange = range; UpdateFieldNames = upfieldnames; OnUpdateItemChanged(); } /// <summary> /// 新增数据发生变化 /// <para>重新生成Sql表达式</para> /// </summary> private void OnUpdateItemChanged() { if (UpdateItem == null) { Express = null; Paramet = null; } else { IEnumerable<IDataParamet> p; Express = MsSqlServerHelper.GetUpdateSql<T>(UpdateItem, UpdateFieldRange,UpdateFieldNames,out p); Paramet = p; } } public override object Clone() { UpdateMsSqlExpress<T> a = new UpdateMsSqlExpress<T>(); T item = null; if (UpdateItem != null) { if (UpdateItem is ICloneable) item = ((ICloneable)UpdateItem).Clone() as T; else item = UpdateItem; } a.SetUpdateItem(item, UpdateFieldRange, UpdateFieldNames); return a; } } }
using System; using System.Linq.Expressions; namespace IQ_Test { public static class Helpers { public static string GenerateKey(Expression<Action<String>> expression) { ParameterExpression newParam = Expression.Parameter(expression.Parameters[0].Type); Expression newExpressionBody = Expression.Call(newParam, ((MethodCallExpression)expression.Body).Method); Expression<Action<String>> newExpression = Expression.Lambda<Action<String>>(newExpressionBody, newParam); return newExpression.ToString(); } public static string GenerateKey(Expression<Func<int, int>> expression) { ParameterExpression newParam = Expression.Parameter(expression.Parameters[0].Type); Expression newExpressionBody = expression; Expression<Func<int, int>> newExpression = Expression.Lambda<Func<int, int>>(newExpressionBody, newParam); return newExpression.ToString(); } } }
namespace AdvanceMapping.Client.DTO { using Models; using System; using System.Collections.Generic; class ManagerDto { public string FirstName { get; set; } public string LastName { get; set; } public int EmployeesCount { get; set; } public IList<Employee> Employees { get; set; } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using Moq; using AirCaddy.Domain.Services; using AirCaddy.Domain.Services.Privileges; using AirCaddy.Controllers; using AirCaddy.Domain.Services.GolfCourses; using AirCaddy.Domain.Special; using AirCaddy.Domain.ViewModels.GolfCourses; namespace AirCaddy.Tests.ControllerTests { [TestFixture] public class PrivilegesControllerTest { /*private Mock<ISessionMapperService> _mockSessionMapperService; private Mock<IPrivilegeRequestHandlerService> _mockPrivilegeRequestHandlerService; private Mock<IGolfCourseService> _mockGolfCourseService; private Mock<ICourseBuilder> _mockCourseBuilder; private PrivilegesController _privilegesController; [SetUp] public void SetUp() { _mockSessionMapperService = new Mock<ISessionMapperService>(); _mockPrivilegeRequestHandlerService = new Mock<IPrivilegeRequestHandlerService>(); _mockGolfCourseService = new Mock<IGolfCourseService>(); _mockCourseBuilder = new Mock<ICourseBuilder>(); _privilegesController = new PrivilegesController(_mockSessionMapperService.Object, _mockPrivilegeRequestHandlerService.Object, _mockCourseBuilder.Object, _mockGolfCourseService.Object); var controllerContext = new Mock<ControllerContext>(); controllerContext.SetupGet(p => p.HttpContext.Session["email"]).Returns("test@test.com"); _privilegesController.ControllerContext = controllerContext.Object; } [Test] public void ShouldShowMakeRequestView() { var result = _privilegesController.MakeRequest(); Assert.AreNotEqual(result, null); }*/ [Test] public async Task YoutubeTest() { /*var testObj = new YoutubeGolfService(); var testUpload = new UploadCourseViewModel { CourseId = "1", CourseName = "Elk Valley Golf Course", HoleNumber = 3, HoleVideoPath = @"C:\Users\gfolg\Desktop\SampleGolfCourseHole.mp4" }; await testObj.UploadCourseFootageAsync(testUpload);*/ } } }
using MyCashFlow.Identity.Context; using MyCashFlow.Web.Infrastructure.ProjectsFilter; using MyCashFlow.Web.Services.PaymentMethod; using MyCashFlow.Web.Services.TransactionType; using MyCashFlow.Web.ViewModels.Home; using System.Linq; using System; namespace MyCashFlow.Web.Services.Home { public class HomeService : IHomeService { private readonly ApplicationDbContext _dbContext; private readonly ITransactionTypeService _transactionTypeService; private readonly IPaymentMethodService _paymentMethodService; public HomeService( ApplicationDbContext dbContext, ITransactionTypeService transactionTypeService, IPaymentMethodService paymentMethodService) { if (dbContext == null) { throw new ArgumentNullException(nameof(dbContext)); } if (transactionTypeService == null) { throw new ArgumentNullException(nameof(transactionTypeService)); } if (paymentMethodService == null) { throw new ArgumentNullException(nameof(paymentMethodService)); } _dbContext = dbContext; _transactionTypeService = transactionTypeService; _paymentMethodService = paymentMethodService; } public HomeIndexViewModel BuildHomeIndexViewModel(int userId) { var myProjects = _dbContext.Projects.Where(x => x.CreatorID == userId); var numberOfAllProjects = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.AllProjects)) .Count(); var numberOfOpenProjects = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.OpenProjects)) .Count(); var numberOfOpenProjectsWithSpentBudget = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.OpenProjectsWithSpentBudget)) .Count(); var numberOfOpenProjectsWithUnspentBudget = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.OpenProjectsWithUnspentBudget)) .Count(); var numberOfOpenProjectsWithReachedTargetValue = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.OpenProjectsWithReachedTargetValue)) .Count(); var numberOfOpenProjectsWithMissedTargetValue = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.OpenProjectsWithMissedTargetValue)) .Count(); var finishedProjects = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.FinishedProjects)) .Count(); var numberofFinishedProjectsWithSpentBudget = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.FinishedProjectsWithSpentBudget)) .Count(); var numberofFinishedProjectsWithUnspentBudget = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.FinishedProjectsWithUnspentBudget)) .Count(); var numberofFinishedProjectsWithReachedTargetValue = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.FinishedProjectsWithReachedTargetValue)) .Count(); var numberofFinishedProjectsWithMissedTargetValue = myProjects .Where(ProjectsFilterTypeResolver.ResolveFilter(ProjectsFilterType.FinishedProjectsWithMissedTargetValue)) .Count(); var transactionTypeIndexViewModel = _transactionTypeService.BuildTransactionTypeIndexViewModel(userId); var paymentMethodIndexViewModel = _paymentMethodService.BuildPaymentMethodIndexViewModel(userId); var model = new HomeIndexViewModel { Projects = numberOfAllProjects, OpenProjects = numberOfOpenProjects, OpenProjectsWithSpentBudget = numberOfOpenProjectsWithSpentBudget, OpenProjectsWithUnspentBudget = numberOfOpenProjectsWithUnspentBudget, OpenProjectsWithReachedTargetValue = numberOfOpenProjectsWithReachedTargetValue, OpenProjectsWithMissedTargetValue = numberOfOpenProjectsWithMissedTargetValue, FinishedProjects = finishedProjects, FinishedProjectsWithSpentBudget = numberofFinishedProjectsWithSpentBudget, FinishedProjectsWithUnspentBudget = numberofFinishedProjectsWithUnspentBudget, FinishedProjectsWithReachedTargetValue = numberofFinishedProjectsWithReachedTargetValue, FinishedProjectsWithMissedTargetValue = numberofFinishedProjectsWithMissedTargetValue, TransactionTypeIndexViewModel = transactionTypeIndexViewModel, PaymentMethodIndexViewModel = paymentMethodIndexViewModel }; return model; } } }
 namespace PartyGreenvic.Views { using PartyGreenvic.Helpers; using Xamarin.Forms; using System; using Xamarin.Forms.Xaml; [XamlCompilation(XamlCompilationOptions.Compile)] public partial class InicioPage : ContentPage { string RutGlobal; public InicioPage () { InitializeComponent (); this.txtRut.MaxLength = 8; this.btnEmpleado.Clicked += BtnEmpleado_Clicked; this.btnCheck.Clicked += BtnCheck_Clicked; } private async void BtnCheck_Clicked(object sender, EventArgs e) { try { #region ValidarRut try { if (string.IsNullOrEmpty(this.txtRut.Text)) return; if (this.txtRut.MaxLength < 7) return; //Digito Verificador RutGlobal = this.txtRut.Text; int suma = 0; for (int x = RutGlobal.Length - 1; x >= 0; x--) suma += int.Parse(char.IsDigit(RutGlobal[x]) ? RutGlobal[x].ToString() : "0") * (((RutGlobal.Length - (x + 1)) % 6) + 2); int numericDigito = (11 - suma % 11); string digito = numericDigito == 11 ? "0" : numericDigito == 10 ? "K" : numericDigito.ToString(); RutGlobal = RutGlobal + digito; } catch (Exception ex) { await DisplayAlert("Error", ex.ToString(), "Aceptar"); this.txtRut.Text = string.Empty; return; } //Existe Rut? int rutAux = int.Parse(RutGlobal.Substring(0, RutGlobal.Length - 1)); char dv = char.Parse(RutGlobal.Substring(RutGlobal.Length - 1, 1)); int m = 0, s = 1; for (; rutAux != 0; rutAux /= 10) { s = (s + rutAux % 10 * (9 - m++ % 6)) % 11; } if (dv == (char)(s != 0 ? s + 47 : 75)) { //Armar Rut con puntos y guion string rut = RutGlobal; int cont = 0; if (rut.Length == 0) { await DisplayAlert("Error", "Rut Incorrecto", "Aceptar"); this.txtRut.Text = string.Empty; return; } else { rut = rut.Replace(".", ""); rut = rut.Replace("-", ""); RutGlobal = "-" + rut.Substring(rut.Length - 1); for (int i = rut.Length - 2; i >= 0; i--) { RutGlobal = rut.Substring(i, 1) + RutGlobal; cont++; if (cont == 3 && i != 0) { RutGlobal = "." + RutGlobal; cont = 0; } } } } else { await DisplayAlert("Error", "Rut Incorrecto", "Aceptar"); RutGlobal = string.Empty; this.txtRut.Text = string.Empty; return; } #endregion var conexion = new DataAccess(); //var datos = conexion.GetEmpleado(RutGlobal); var datoss = conexion.GetEmpleado(RutGlobal); var nombre = datoss.Nombre; //var invitado = datos.Rut.Where(x => x.Rut == RutGlobal); if (datoss == null) { await DisplayAlert("Acceso Denegado", "Esta persona no tiene Invitación vigente", "Aceptar"); this.txtRut.Text = string.Empty; return; } await DisplayAlert("Acceso Permitido", nombre + " con acceso Autorizado", "Aceptar"); this.txtRut.Text = string.Empty; return; } catch (Exception ex) { ex.ToString(); return; } } private void BtnEmpleado_Clicked(object sender, EventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEngine.EventSystems; public class PauseMenu : MonoBehaviour { public static bool GameIsPaused = false,flag=false; public Button yourButton; public GameObject pauseMenuUI; void Start() { Button btn = yourButton.GetComponent<Button>(); btn.onClick.AddListener(Clicked); } void Clicked() { if (GameIsPaused) { Resume(); } else { Pause(); } } void Update() { } public void Resume() { pauseMenuUI.SetActive(false); Time.timeScale = 1f; GameIsPaused = false; flag = false; } public void Pause() { pauseMenuUI.SetActive(true); Time.timeScale = 0f; GameIsPaused = true; } public void LoadMenu() { Time.timeScale = 1f; SceneManager.LoadScene("MainMenu"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FIUChat.Enums { public enum Entitlement { Student = 10, Admin = 20, Bot = 30, Unknown = 0 } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using Newtonsoft.Json; using VolanTrans.Logic.Model; namespace VolanTrans.Logic.Helpers { public class RenewablesRepositoryHelper : IRenewablesRepositoryHelper { private string _path = ConfigurationManager.AppSettings["WorkFolder"]+@"\Renewables\"; public bool AddRenewModel(RenewableModel model) { try { if (!Directory.Exists(_path)) Directory.CreateDirectory(_path); using(StreamWriter sw = new StreamWriter(_path+model.Id+".json")) { string sm = JsonConvert.SerializeObject(model); sw.Write(sm); sw.Flush(); sw.Close(); } return true; } catch { return false; } } public bool UpdateRenewModel(RenewableModel model) { try { return DeleteRenewModel(model) && AddRenewModel(model); } catch { return false; } } public bool DeleteRenewModel(RenewableModel model) { try { File.Delete(_path + model.Id + ".json"); return true; } catch { return false; } } public bool DeleteRenewModel(Guid id) { try { File.Delete(_path + id + ".json"); return true; } catch { return false; } } public List<RenewableModel> GetRenewables() { List<RenewableModel> result = new List<RenewableModel>(); if (!Directory.Exists(_path)) Directory.CreateDirectory(_path); foreach (var file in Directory.EnumerateFiles(_path, "*.json")) { string item = File.ReadAllText(file); var renew = JsonConvert.DeserializeObject<RenewableModel>(item); result.Add(renew); } return result; } } }
using System; using System.Collections.Generic; using System.Xml.Serialization; namespace RO.Config { public class ClientServerVersionMap : XMLSerializedClass<ClientServerVersionMap> { public List<ClientServerMapInfo> infos = new List<ClientServerMapInfo>(); private static XmlSerializer serializer = new XmlSerializer(typeof(BuildBundleConfig)); [XmlIgnore] public SDictionary<int, ClientServerMapInfo> versionMap = new SDictionary<int, ClientServerMapInfo>(); private bool _isInited; public int InfosCount { get { return this.infos.get_Count(); } } public void Init() { if (!this._isInited) { this._isInited = true; for (int i = 0; i < this.infos.get_Count(); i++) { ClientServerMapInfo clientServerMapInfo = this.infos.get_Item(i); this.versionMap[clientServerMapInfo.clientCodeVersion] = clientServerMapInfo; } } } private void _AddInfo(int clientCode, string maxServerVersion, bool enabled) { ClientServerMapInfo clientServerMapInfo = new ClientServerMapInfo(); clientServerMapInfo.clientCodeVersion = clientCode; clientServerMapInfo.maxServerVersion = maxServerVersion; clientServerMapInfo.enabled = enabled; this.infos.Add(clientServerMapInfo); this.versionMap[clientServerMapInfo.clientCodeVersion] = clientServerMapInfo; } public void ModifyInfo(int clientCode, string maxServerVersion, bool enabled) { this.Init(); ClientServerMapInfo clientServerMapInfo = this.versionMap[clientCode]; if (clientServerMapInfo == null) { this._AddInfo(clientCode, maxServerVersion, enabled); } else { if (!string.IsNullOrEmpty(maxServerVersion) && maxServerVersion != "0") { clientServerMapInfo.maxServerVersion = maxServerVersion; } clientServerMapInfo.enabled = enabled; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class PersonDAO_Mock: IPersonDAO { private static PersonDAO_Mock instance = null; private List<Person>_persons; public static IPersonDAO GetInstance() { if (instance == null) { instance = new PersonDAO_Mock(); } return instance; } private PersonDAO_Mock() { _persons = new List<Person>(); _persons.Add(new Person(1, "Василий", "Фудоров", 33)); _persons.Add(new Person(2, "Касилий", "Пудоров", 25)); _persons.Add(new Person(3, "Пасилий", "Еудоров", 14)); _persons.Add(new Person(4, "Сасилий", "Рудоров", 74)); _persons.Add(new Person(5, "Тасилий", "Кудоров", 11)); _persons.Add(new Person(6, "Дасилий", "Судоров", 15)); _persons.Add(new Person(7, "Часилий", "Зудоров", 20)); _persons.Add(new Person(8, "Игнат", "Иудоров", 30)); _persons.Add(new Person(9, "Карен", "Яудоров", 23)); } IPersonDAO IPersonDAO.GetInstance() { return GetInstance(); } public void Create(Person p) { int id = _persons.Count == 0 ? 0 : _persons.Max(item => item.ID); p.ID = id + 1; _persons.Add(p); } public List<Person> Read() { return _persons.ToList(); } public void Update(Person p) { Person person = _persons.FirstOrDefault(item => item.ID == p.ID); if (person != null) { person.Age = p.Age; person.FirstName = p.FirstName; person.LastName = p.LastName; } } public void Delete(Person p) { Person person = _persons.FirstOrDefault(item => item.ID == p.ID); if (person != null) { int index = _persons.IndexOf(person); _persons.RemoveAt(index); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public delegate void ActionEndEvent(); public interface IAction { void Start(); void AddEndEvent(ActionEndEvent endEventListener); } public abstract class ActionBased : IAction { private ActionEndEvent listener; public void AddEndEvent(ActionEndEvent endEventListener) { listener += endEventListener; } public void InvokeEndEvent() { listener?.Invoke(); } abstract public void Start(); } public class GroupAction : ActionBased { private readonly IAction[] actionGroup; private int CountCallEnd = 0; public GroupAction(IAction[] actionGroup) { this.actionGroup = actionGroup; for (int i = 0; i < actionGroup.Length; ++i) { actionGroup[i].AddEndEvent(NotifyEnd); } } private void NotifyEnd() { ++CountCallEnd; if (CountCallEnd == actionGroup.Length) InvokeEndEvent(); } public override void Start() { for (int i = 0; i < actionGroup.Length; ++i) { actionGroup[i].Start(); } } } public class QueueAction : ActionBased { private readonly Queue<IAction> queue = new Queue<IAction>(); private void RunNextAction() { if (queue.Count > 0) { var action = queue.Dequeue(); action.Start(); } else { InvokeEndEvent(); } } public void AddAction(IAction action) { action.AddEndEvent(RunNextAction); queue.Enqueue(action); } public override void Start() { RunNextAction(); } } public class AutoQueue { private Queue<IAction> actionQueue = new Queue<IAction>(); public Queue<IAction> GetQueue() { return actionQueue; } private void RunNextAction() { if (actionQueue.Count > 0) { var action = actionQueue.Peek(); action.Start(); } } private void OnFinish() { actionQueue.Dequeue(); RunNextAction(); } public void AddAction(IAction action) { action.AddEndEvent(OnFinish); if (actionQueue.Count == 0) { actionQueue.Enqueue(action); RunNextAction(); } else { actionQueue.Enqueue(action); } } }
using CustomerManagementSystem.Common.cs; using System; using System.Collections.Generic; using System.Linq; namespace CustomerManagementSystem.BL { //1.Customer --------------> Name, Email Address, Home Address, Work Address // 2.Products----------------> Product Name, Description, Current Price // 3.Orders-------------------> Customer, Order date, Shipping address // 4.Order Item--------------> Products, Purchase Price, Quantities public class Customer:EntityBase,ILoggable { public Customer():this(0) //here default consturctor calling parameterized constructer.This is called Constructer chaining { } public Customer(int customerId) { // this.CustomerId = customerId; AddressList= new List<Address>(); } public static int StaticInstanceCount { get; set; } public int CustomerType { get; set; } public string FirstName { get; set; } private string _lastname; public string LastName { get { return _lastname; } set { _lastname = value; } } public string FullName { get { string FullName = FirstName; if (!string.IsNullOrWhiteSpace(LastName)) { if (!string.IsNullOrWhiteSpace(FirstName)) { FullName += " "; } FullName += LastName; } return FullName; } } public string EmailId { get; set; } public int CustomerId { get; private set; } public string HomeAddress { get; set; } public string WorkAddress { get; set; } public List<Address> AddressList{get;set;} public override bool Validate() { var IsValid = true; if (string.IsNullOrWhiteSpace(FirstName)) IsValid = false; if (string.IsNullOrWhiteSpace(LastName)) IsValid = false; return IsValid; } public override string ToString() { return FirstName+LastName; } public string Log() { var logString = this.CustomerId + " " + this.FullName + " " + "Email:" + this.EmailId + " "; return logString; } } }
using Domen; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemOperations.ProizvodjacLekovaSO { public class AddProizvodjacSO : SystemOperationBase { protected override object ExecuteSO(IEntity entity) { ProizvodjacLekova proizvodjac = (ProizvodjacLekova)entity; if (broker.Insert(proizvodjac)==1) { return true; } return false; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CustomerInStore : MonoBehaviour { public List<GameObject> characters = new List<GameObject>(); //このステージで入店する客のリスト float nextSpawnTime = 0; //客が入ってくる間隔の処理 [SerializeField] float interval = 4.0f; //客が入ってくる間隔 [SerializeField] public bool isStopPlayer = false; //キャラを止めるか止めないか public bool isAddCharacter = false; //キャラが増える面で生成するキャラの種類を増やしたか public bool isFirstCustomer = false; public List<string> comeCharacterList = new List<string> (); //入店してる客の名前リスト private StageManager stageManagerScript; void Awake() { stageManagerScript = GameObject.Find ("StageManager").GetComponent<StageManager> (); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (StageManager.stageLevel >= 2 && isAddCharacter == false) { characters.Add(Resources.Load<GameObject>("Prefab/Object/CharacterN004")); characters.Add(Resources.Load<GameObject>("Prefab/Object/CharacterN005")); characters.Add(Resources.Load<GameObject>("Prefab/Object/CharacterN008")); characters.Add(Resources.Load<GameObject>("Prefab/Object/CharacterN011")); isAddCharacter = true; } //キャラを一定時間(interval)ごとに生成する if (nextSpawnTime < Time.timeSinceLevelLoad && isStopPlayer == false) { nextSpawnTime = Time.timeSinceLevelLoad + interval; LocalInstantate (); } } void LocalInstantate( ) { Debug.Log ("LocalInstantate in"); //どのキャラを入店させるかの乱数生成 int rand = Random.Range (0, characters.Count - comeCharacterList.Count); //全てのキャラが出ていないなら if (characters.Count > comeCharacterList.Count) { //ダブリチェック rand = checkDoubleCharacter (rand); //全てのキャラが出ていなければ if (rand <= characters.Count) { //キャラを指定の位置に生成 GameObject obj = (GameObject)GameObject.Instantiate (characters [rand]); obj.transform.parent = transform; if (StageManager.stageLevel <= 3) { obj.transform.localPosition = new Vector3 (-38.0f, 193.0f, 0); } else { obj.transform.localPosition = new Vector3 (-78.0f, 193.0f, 0); } //stageLevelによってサイズを変える if ( stageManagerScript.stageData [StageManager.stageLevel].stageScale != 1 ) { float scale = obj.transform.localScale.x; scale *= stageManagerScript.stageData [StageManager.stageLevel].stageScale; obj.transform.localScale = new Vector3 (scale, scale, scale); } //生成したキャラを保存する comeCharacterList.Add (obj.name.Substring (0, 13)); //CharacterNXXX の部分 } } if (isFirstCustomer == false) { SEManager.isSeSound [(int)SEManager.SE_LIST.FIRST_COME_CUSTOMER] = true; isFirstCustomer = true; } } //ダブっていたらダブっていない変数に進める //[0][1][2][3][4]で2,3が既に生成されていて、残りの0,3,4を0,1,2と捉え、 //これに2が入ったら足して[4]に進める int checkDoubleCharacter(int tempRand) { for ( int i = 0; i < comeCharacterList.Count; i++ ) { if ( comeCharacterList[i] == characters[tempRand].name){ tempRand++; //再度ダブってないか1から確認する tempRand = checkDoubleCharacter (tempRand); i = comeCharacterList.Count; } } return tempRand; } }
using Microsoft.Azure.Management.DataLake.Store.Models; using Microsoft.DataStudio.AzureResources.AzureDataLake; using Microsoft.DataStudio.AzureResources.AzureSql; using Microsoft.DataStudio.AzureResources.AzureStorage; using Microsoft.DataStudio.AzureResources.HDInsight; using Microsoft.DataStudio.Diagnostics; using Microsoft.WindowsAzure.Management.HDInsight; using Microsoft.WindowsAzure.Management.Sql.Models; using Microsoft.WindowsAzure.Management.Storage.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.DataStudio.AzureResources { /// <summary> /// This class returns a list of Azure Resources providing the subscription and the token /// </summary> public class AzureResourcesHelper { public AzureResourcesHelper(string subscriptionId, string token, ILogger logger) { this.SubscriptionId = subscriptionId; this.Token = token; this.Credentials = new Azure.TokenCloudCredentials(subscriptionId, token); this.Logger = logger; } private string SubscriptionId; private string Token; public Azure.TokenCloudCredentials Credentials { get; private set; } private ILogger Logger; public async Task<IEnumerable<StorageAccount>> GetStorageAccountsAsync() { return await AzureStorageHelper.GetStorageAccountsAsync(this.Credentials, this.Logger); } public async Task<IEnumerable<ClusterDetails>> GetHDInsightClustersAsync() { return await HDInsightHelper.GetClustersAsync(Guid.Parse(this.SubscriptionId), this.Token, this.Logger); } public async Task<IEnumerable<DataLakeStoreAccount>> GetDataLakeStoreAccountsAsync() { return await AzureDataLakeHelper.GetAccountsFromAzureInternalAsync(this.Credentials, this.Logger); } public async Task<Dictionary<Server, IEnumerable<Database>>> GetSqlServersAsync() { return await SqlAzureHelper.GetServersAsync(this.Credentials, this.Logger); } } }
namespace Rentalis_v2.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddedInformationsForCars : DbMigration { public override void Up() { AddColumn("dbo.CarModels", "Doors", c => c.Byte()); AddColumn("dbo.CarModels", "Seets", c => c.Byte()); AddColumn("dbo.CarModels", "FuelType", c => c.Byte()); AddColumn("dbo.CarModels", "Type", c => c.Byte()); AddColumn("dbo.CarModels", "Abs", c => c.Boolean()); AddColumn("dbo.CarModels", "PowerSteering", c => c.Boolean()); AddColumn("dbo.CarModels", "GearBox", c => c.Boolean()); AddColumn("dbo.CarModels", "AirConditioning", c => c.Boolean()); AddColumn("dbo.CarModels", "CentralLocking", c => c.Boolean()); AddColumn("dbo.CarModels", "AirBags", c => c.Boolean()); } public override void Down() { DropColumn("dbo.CarModels", "AirBags"); DropColumn("dbo.CarModels", "CentralLocking"); DropColumn("dbo.CarModels", "AirConditioning"); DropColumn("dbo.CarModels", "GearBox"); DropColumn("dbo.CarModels", "PowerSteering"); DropColumn("dbo.CarModels", "Abs"); DropColumn("dbo.CarModels", "Type"); DropColumn("dbo.CarModels", "FuelType"); DropColumn("dbo.CarModels", "Seets"); DropColumn("dbo.CarModels", "Doors"); } } }
using MetroFramework; using MetroFramework.Forms; using NFe.Utils.NFe; using PDV.DAO.Entidades; using PDV.UTIL; using PDV.VIEW.App_Context; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace PDV.VIEW.Forms.Gerenciamento { public partial class GER_EnviarPorEmail : DevExpress.XtraEditors.XtraForm { private Dictionary<string, string> TAGS { get { Dictionary<string, string> Tags = new Dictionary<string, string>(); Tags.Add("[nomeEmit]", Emitente.NomeFantasia); Tags.Add("[nomeDest]", Nfe.infNFe.dest != null ? Nfe.infNFe.dest.xNome : string.Empty); Tags.Add("[cnpjEmit]", Emitente.CNPJ); Tags.Add("[nNFe]", Nfe.infNFe.ide.nNF.ToString()); Tags.Add("[serieNFe]", Nfe.infNFe.ide.serie.ToString()); Tags.Add("[chNFe]", Nfe.infNFe.ide.cNF); Tags.Add("[Link]", Nfe.infNFe.Id); return Tags; } } private string Xml = null; private EmailEmitente Email = null; private NFe.Classes.NFe Nfe; private Emitente Emitente = null; private bool Cancelada = false; private string NOME_TELA = "ENVIAR NFC-E/NFE POR E-MAIL"; public GER_EnviarPorEmail(string XmlEnvio, bool _Cancelada, Emitente _Emitente, EmailEmitente _Email) { InitializeComponent(); Xml = XmlEnvio; Emitente = _Emitente; Email = _Email; Nfe = new NFe.Classes.NFe().CarregarDeXmlString(Xml); ovTXT_Email.Text = Nfe.infNFe.dest != null ? Nfe.infNFe.dest.email : string.Empty; Cancelada = _Cancelada; } private void EnviarEmail() { if (string.IsNullOrEmpty(ovTXT_Email.Text.Trim())) { MessageBox.Show(this, "Preencha o Campo E-mail.", NOME_TELA); return; } List<string> Destinatarios = new List<string>(); Destinatarios.Add(ovTXT_Email.Text); List<byte[]> Anexos = new List<byte[]>(); Anexos.Add(Encoding.Default.GetBytes(Xml)); string RetornoEnvio = ZeusUtil.EnviarEmail(new Email() { Assunto = ReplaceAssuntoEmail(), Mensagem = ReplaceMensagemEmail(), EmailDestinatario = Destinatarios, Anexos = Anexos, }, Contexto.USUARIOLOGADO.Nome); if (RetornoEnvio.Equals("OK")) { MessageBox.Show(this, "Enviado com Sucesso.", NOME_TELA); Close(); } else MessageBox.Show(this, RetornoEnvio, NOME_TELA); } private string ReplaceAssuntoEmail() { string Assunto = Cancelada ? Email.CancelarAssunto : Email.AutorizarAssunto; foreach (var Tag in TAGS) Assunto = Assunto.Replace(Tag.Key, Tag.Value); return Assunto; } private string ReplaceMensagemEmail() { string Mensagem = Cancelada ? Email.CancelarMensagem : Email.AutorizarMensagem; foreach (var Tag in TAGS) Mensagem = Mensagem.Replace(Tag.Key, Tag.Value); return Mensagem; } private void ovBTN_Cancelar_Click(object sender, System.EventArgs e) { EnviarEmail(); } } }
#! "netcoreapp1.0"
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("DeckTrayDeckTileVisual")] public class DeckTrayDeckTileVisual : PegUIElement { public DeckTrayDeckTileVisual(IntPtr address) : this(address, "DeckTrayDeckTileVisual") { } public DeckTrayDeckTileVisual(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public CollectionDeckTileActor GetActor() { return base.method_14<CollectionDeckTileActor>("GetActor", Array.Empty<object>()); } public Bounds GetBounds() { return base.method_11<Bounds>("GetBounds", Array.Empty<object>()); } public string GetCardID() { return base.method_13("GetCardID", Array.Empty<object>()); } public TAG_PREMIUM GetPremium() { return base.method_11<TAG_PREMIUM>("GetPremium", Array.Empty<object>()); } public CollectionDeckSlot GetSlot() { return base.method_14<CollectionDeckSlot>("GetSlot", Array.Empty<object>()); } public void Hide() { base.method_8("Hide", Array.Empty<object>()); } public bool IsInUse() { return base.method_11<bool>("IsInUse", Array.Empty<object>()); } public bool IsOwnedSlot() { return base.method_11<bool>("IsOwnedSlot", Array.Empty<object>()); } public void MarkAsUnused() { base.method_8("MarkAsUnused", Array.Empty<object>()); } public void MarkAsUsed() { base.method_8("MarkAsUsed", Array.Empty<object>()); } public void SetHighlight(bool highlight) { object[] objArray1 = new object[] { highlight }; base.method_8("SetHighlight", objArray1); } public void SetInArena(bool inArena) { object[] objArray1 = new object[] { inArena }; base.method_8("SetInArena", objArray1); } public void SetSlot(CollectionDeckSlot s, bool useSliderAnimations) { object[] objArray1 = new object[] { s, useSliderAnimations }; base.method_8("SetSlot", objArray1); } public void SetUpActor() { base.method_8("SetUpActor", Array.Empty<object>()); } public void Show() { base.method_8("Show", Array.Empty<object>()); } public Vector3 BOX_COLLIDER_CENTER { get { return base.method_2<Vector3>("BOX_COLLIDER_CENTER"); } } public Vector3 BOX_COLLIDER_SIZE { get { return base.method_2<Vector3>("BOX_COLLIDER_SIZE"); } } public static int DEFAULT_PORTRAIT_QUALITY { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "DeckTrayDeckTileVisual", "DEFAULT_PORTRAIT_QUALITY"); } } public static GameLayer LAYER { get { return MonoClass.smethod_6<GameLayer>(TritonHs.MainAssemblyPath, "", "DeckTrayDeckTileVisual", "LAYER"); } } public CollectionDeckTileActor m_actor { get { return base.method_3<CollectionDeckTileActor>("m_actor"); } } public BoxCollider m_collider { get { return base.method_3<BoxCollider>("m_collider"); } } public bool m_inArena { get { return base.method_2<bool>("m_inArena"); } } public bool m_isInUse { get { return base.method_2<bool>("m_isInUse"); } } public CollectionDeckSlot m_slot { get { return base.method_3<CollectionDeckSlot>("m_slot"); } } public bool m_useSliderAnimations { get { return base.method_2<bool>("m_useSliderAnimations"); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; namespace GITRepoManager { public static class Configuration { #region Old public static XML.Root Parsed_Raw { get; set; } public class XML { [XmlRoot(ElementName = "root")] public class Root { [XmlElement(ElementName = "Store")] public List<Store> Stores { get; set; } } [XmlRoot(ElementName = "Store")] public class Store { [XmlElement(ElementName = "Location")] public string Location { get; set; } [XmlElement(ElementName = "Repos")] public Repos Repos { get; set; } } [XmlRoot(ElementName = "Repos")] public class Repos { [XmlElement(ElementName = "Repo")] public List<Repo> Items { get; set; } } [XmlRoot(ElementName = "Repo")] public class Repo { [XmlElement(ElementName = "Name")] public string Name { get; set; } [XmlElement(ElementName = "Status")] public string Status { get; set; } [XmlElement(ElementName = "Notes")] public Notes Notes { get; set; } } [XmlRoot(ElementName = "Notes")] public class Notes { [XmlElement(ElementName = "Note")] public List<Note> Items { get; set; } } [XmlRoot(ElementName = "Note")] public class Note { [XmlElement(ElementName = "Title")] public string Title { get; set; } [XmlElement(ElementName = "Body")] public string Body { get; set; } } } #endregion #region File Class public static class File { public enum NODE_T { NOTHING, STORE, REPO, NOTE }; public enum ATTRIBUTE_T { NOTHING, LOCATION, NAME, STATUS, TITLE }; public static string NODE_T_ToString(NODE_T node) { switch (node) { case NODE_T.NOTE: return "Note"; case NODE_T.REPO: return "Repo"; case NODE_T.STORE: return "Store"; default: return string.Empty; } } public static string ATTRIBUTE_T_ToString(ATTRIBUTE_T attr) { switch (attr) { case ATTRIBUTE_T.LOCATION: return "Location"; case ATTRIBUTE_T.NAME: return "Name"; case ATTRIBUTE_T.STATUS: return "Status"; case ATTRIBUTE_T.TITLE: return "Title"; default: return string.Empty; } } public static NODE_T String_ToNODE_T(string str) { str = str.ToLower(); switch (str) { case "note": return NODE_T.NOTE; case "repo": return NODE_T.REPO; case "store": return NODE_T.STORE; default: return NODE_T.NOTHING; } } public static ATTRIBUTE_T String_ToATTRIBUTE_T(string str) { str = str.ToLower(); switch (str) { case "location": return ATTRIBUTE_T.LOCATION; case "name": return ATTRIBUTE_T.NAME; case "status": return ATTRIBUTE_T.STATUS; case "title": return ATTRIBUTE_T.TITLE; default: return ATTRIBUTE_T.NOTHING; } } } #endregion #region Helpers Class public static class Helpers { #region Deserialize Raw Packet Structure public static void Deserialize(string source) { Parsed_Raw = null; XmlSerializer deserializer = new XmlSerializer(typeof(XML.Root)); StreamReader reader = new StreamReader(source); XML.Root input = null; try { input = (XML.Root)deserializer.Deserialize(reader); } catch(Exception ex) { MessageBox.Show(ex.Message); return; } reader.Close(); Parsed_Raw = input; Get_Stores(); return; } #endregion #region Replace Config File Data With New Data public static void Serialize_Replace(string destination, Dictionary<string, StoreCell> ToAdd) { XML.Root tempRoot = new XML.Root(); tempRoot.Stores = new List<XML.Store>(); foreach (KeyValuePair<string, StoreCell> Store in ToAdd) { XML.Store tempStore = new XML.Store(); tempStore.Location = Store.Value._Path; tempStore.Repos = new XML.Repos(); tempStore.Repos.Items = new List<XML.Repo>(); foreach (KeyValuePair<string, RepoCell> Repo in Store.Value._Repos) { XML.Repo tempRepo = new XML.Repo(); tempRepo.Name = Repo.Key; tempRepo.Status = RepoCell.Status.ToString(Repo.Value.Current_Status); tempRepo.Notes = new XML.Notes(); tempRepo.Notes.Items = new List<XML.Note>(); foreach (KeyValuePair<string, string> Note in Repo.Value.Notes) { XML.Note tempNote = new XML.Note(); tempNote.Title = Note.Key; tempNote.Body = Note.Value; tempRepo.Notes.Items.Add(tempNote); } tempStore.Repos.Items.Add(tempRepo); } tempRoot.Stores.Add(tempStore); } XmlSerializer serializer = new XmlSerializer(typeof(XML.Root)); StreamWriter writer = new StreamWriter(destination); serializer.Serialize(writer, tempRoot); writer.Close(); } #endregion #region Parse The Raw Packet To Class Data public static void Get_Stores() { if (Parsed_Raw != null) { ManagerData.Stores = new Dictionary<string, StoreCell>(); StoreCell currStore = null; try { foreach (XML.Store Parsed_Store in Parsed_Raw.Stores) { currStore = new StoreCell(Parsed_Store.Location); currStore._Path = Parsed_Store.Location; currStore._Repos = Get_Repos(Parsed_Store.Repos); DirectoryInfo currStoreInfo = new DirectoryInfo(Parsed_Store.Location); ManagerData.Stores.Add(currStoreInfo.Name, currStore); } foreach (StoreCell store in ManagerData.Stores.Values) { foreach (RepoCell repo in store._Repos.Values) { repo.Path = store._Path + @"\" + repo.Name; } } } catch (Exception ex) { ManagerData.Stores = null; } } } #endregion #region Parse The Repos In The Raw Packet To Class Data public static Dictionary<string, RepoCell> Get_Repos(XML.Repos ReposObj) { Dictionary<string, RepoCell> RepoDict = new Dictionary<string, RepoCell>(); try { foreach (XML.Repo Parsed_Repo in ReposObj.Items) { RepoCell currRepo = Get_Repo(Parsed_Repo); currRepo.Logs = new Dictionary<string, List<EntryCell>>(); if (currRepo != null) { RepoDict.Add(Parsed_Repo.Name, currRepo); } } } catch (Exception ex) { RepoDict = null; } return RepoDict; } #endregion #region Create A Repo Cell For An Config Repo public static RepoCell Get_Repo(XML.Repo RepoObj) { RepoCell currRepo = null; try { currRepo = new RepoCell(); currRepo.Name = RepoObj.Name; currRepo.Current_Status = RepoCell.Status.ToType(RepoObj.Status); currRepo.Notes = Get_Notes(RepoObj.Notes); } catch(Exception ex) { } return currRepo; } #endregion #region Parse The Notes In The Raw Packet To Class Data public static Dictionary<string, string> Get_Notes(XML.Notes NotesObj) { Dictionary<string, string> NoteDict = new Dictionary<string, string>(); try { foreach (XML.Note note in NotesObj.Items) { NoteDict.Add(note.Title, note.Body); } } catch (Exception ex) { NoteDict = null; } return NoteDict; } #endregion #region Deserialize Condensed Packet Structure public static void Deserialize_Condensed(string file, CircularProgressBar.CircularProgressBar cpb = null) { // Load the document XmlDocument Config = new XmlDocument(); Config.Load(file); if (ManagerData.Stores != null) { ManagerData.Stores.Clear(); } else { ManagerData.Stores = new Dictionary<string, StoreCell>(); } string currStoreLocation = string.Empty; string currRepoName = string.Empty; RepoCell.Status.Type currRepoStatus = RepoCell.Status.Type.NONE; string currNoteTitle = string.Empty; string currNoteMessage = string.Empty; StoreCell newStore = null; RepoCell newRepo = null; // Under the root the layers will be Stores => Repos => Notes foreach (XmlNode storeNode in Config.DocumentElement.ChildNodes) { foreach (XmlAttribute storeAttr in storeNode.Attributes) { switch (File.String_ToATTRIBUTE_T(storeAttr.Name)) { case File.ATTRIBUTE_T.LOCATION: currStoreLocation = storeAttr.Value; break; } } newStore = new StoreCell(currStoreLocation) { _Repos = new Dictionary<string, RepoCell>() }; foreach (XmlNode repoNode in storeNode.ChildNodes) { foreach (XmlAttribute repoAttr in repoNode.Attributes) { switch (File.String_ToATTRIBUTE_T(repoAttr.Name)) { case File.ATTRIBUTE_T.NAME: currRepoName = repoAttr.Value; break; case File.ATTRIBUTE_T.STATUS: currRepoStatus = RepoCell.Status.ToType(repoAttr.Value); break; } } newRepo = new RepoCell() { Name = currRepoName, Current_Status = currRepoStatus, Path = currStoreLocation + @"\" + currRepoName, Notes = new Dictionary<string, string>() }; foreach (XmlNode noteNode in repoNode.ChildNodes) { foreach (XmlAttribute noteAttr in noteNode.Attributes) { switch (File.String_ToATTRIBUTE_T(noteAttr.Name)) { case File.ATTRIBUTE_T.TITLE: currNoteTitle = noteAttr.Value; break; } } currNoteMessage = noteNode.InnerText; newRepo.Notes.Add(currNoteTitle, currNoteMessage); currNoteMessage = string.Empty; currNoteTitle = string.Empty; } newRepo.Logs_Parsed = false; newStore._Repos.Add(currRepoName, newRepo); currRepoStatus = RepoCell.Status.Type.NONE; } if (currStoreLocation != "") { DirectoryInfo dirInfo = new DirectoryInfo(currStoreLocation); ManagerData.Stores.Add(dirInfo.Name, newStore); } } } #endregion #region Serialize Condensed Packet Structure /* * Node for each store, repo, and note * * Attributes * Store: Location - Path to store * Repo: Name - Name of the repository, not path * Status - Current status of the repository i.e New, Development, Production * Note Title - The title of the note * * Other Data * Note body needs to be inner text of the Note node */ public static bool Serialize_Condensed_All(string file, CircularProgressBar.CircularProgressBar cpb = null) { XmlDocument Config = new XmlDocument(); Config.Load(file); try { Config.DocumentElement.RemoveAll(); Config.Save(file); } catch { return false; } XmlNode storeNode = null; XmlNode repoNode = null; XmlNode noteNode = null; XmlAttribute storeLocationAttr = null; XmlAttribute repoNameAttr = Config.CreateAttribute("Name"); XmlAttribute repoStatusAttr = Config.CreateAttribute("Status"); XmlAttribute noteTitleAttr = Config.CreateAttribute("Title"); if (ManagerData.Stores.Count > 0) { // Cycle through each store cell and create a node. // The only attribute is the location of the store. foreach (StoreCell storeCell in ManagerData.Stores.Values) { storeLocationAttr = Config.CreateAttribute("Location"); storeLocationAttr.Value = storeCell._Path; // Create a store node and add the location attribute storeNode = Config.CreateElement("Store"); storeNode.Attributes.Append(storeLocationAttr); try { if (storeCell._Repos.Count > 0) { // Cycle through each store's repo cells and create nodes // Attributes: Name, Status foreach (RepoCell repoCell in storeCell._Repos.Values) { repoNameAttr = Config.CreateAttribute(File.ATTRIBUTE_T_ToString(File.ATTRIBUTE_T.NAME)); repoNameAttr.Value = repoCell.Name; repoStatusAttr = Config.CreateAttribute(File.ATTRIBUTE_T_ToString(File.ATTRIBUTE_T.STATUS)); repoStatusAttr.Value = RepoCell.Status.ToString(repoCell.Current_Status); // Create a repo node and add all it's attributes repoNode = Config.CreateElement("Repo"); repoNode.Attributes.Append(repoNameAttr); repoNode.Attributes.Append(repoStatusAttr); if (repoCell.Notes.Count > 0) { // Cycle through each repo's notes and create nodes // The only attribute is the note's title // The inner text is the note body foreach (KeyValuePair<string, string> note in repoCell.Notes) { noteTitleAttr = Config.CreateAttribute("Title"); noteTitleAttr.Value = note.Key; // Create a note node and add it's attribute as well as body noteNode = Config.CreateElement("Note"); noteNode.Attributes.Append(noteTitleAttr); noteNode.InnerText = note.Value; repoNode.AppendChild(noteNode); } } storeNode.AppendChild(repoNode); } } } catch { } // After all information has been added to the store node add it to the file. Config.DocumentElement.AppendChild(storeNode); } } Config.Save(file); return true; } #endregion #region Get Parent A Node (Store, Repo, Note) public static List<XmlNode> Search_Nodes(string searchItem, bool getParent) { List<XmlNode> FoundNodes = new List<XmlNode>(); searchItem = searchItem.ToLower(); XmlDocument Config = new XmlDocument(); //Config.Load(Properties.Settings.Default.ConfigPath); Config.Load(@"C:\Temp\test.gmc"); if (Config.DocumentElement.ChildNodes.Count > 0) { foreach (XmlNode storeNode in Config.DocumentElement.ChildNodes) { foreach (XmlAttribute storeAttr in storeNode.Attributes) { if (storeAttr.Value.ToLower() == searchItem) { if (getParent) { if (!FoundNodes.Contains(storeNode.ParentNode)) { FoundNodes.Add(storeNode.ParentNode); } } else { if (!FoundNodes.Contains(storeNode)) { FoundNodes.Add(storeNode); } } } } if (storeNode.ChildNodes.Count > 0) { foreach (XmlNode repoNode in storeNode.ChildNodes) { foreach (XmlAttribute repoAttr in repoNode.Attributes) { if (repoAttr.Value.ToLower() == searchItem) { if (getParent) { if (!FoundNodes.Contains(repoNode.ParentNode)) { FoundNodes.Add(repoNode.ParentNode); } } else { if (!FoundNodes.Contains(repoNode)) { FoundNodes.Add(repoNode); } } } } if (repoNode.ChildNodes.Count > 0) { foreach (XmlNode noteNode in repoNode.ChildNodes) { foreach (XmlAttribute noteAttr in noteNode.Attributes) { if (noteAttr.Value.ToLower() == searchItem) { if (getParent) { if (!FoundNodes.Contains(noteNode.ParentNode)) { FoundNodes.Add(noteNode.ParentNode); } } else { if (!FoundNodes.Contains(noteNode)) { FoundNodes.Add(noteNode); } } } } } } } } } } return FoundNodes; } public static XmlNode Get_Selected_Store() { bool HasLocation = false; foreach (XmlNode store in Search_Nodes(ManagerData.Selected_Repo.Name, false)) { foreach (XmlAttribute attr in store.Attributes) { switch (attr.Name) { case "Location": if (attr.Value == ManagerData.Selected_Store._Path) { HasLocation = true; } break; } } if (HasLocation) { return store; } } return null; } public static XmlNode Get_Selected_Repo() { foreach (XmlNode repo in Search_Nodes(ManagerData.Selected_Repo.Name, false)) { bool HasName = false; bool HasStatus = false; foreach (XmlAttribute attr in repo.Attributes) { switch (attr.Name) { case "Name": if (attr.Value == ManagerData.Selected_Repo.Name) { HasName = true; } break; case "Status": if (attr.Value == RepoCell.Status.ToString(ManagerData.Selected_Repo.Current_Status)) { HasStatus = true; } break; } } if (HasName && HasStatus) { return repo; } } return null; } #endregion #region Append New Store public static bool Append_New_Store(StoreCell newStore) { // Convert store cell to store node // Append store node to the XmlDocument.DocumentElement children return true; } #endregion #region Append New Repo public static bool Append_New_Repo(RepoCell newRepo) { // Convert repo cell to repo node // Get the node of the currently selected store // Append the repo node to the store node's children return true; } #endregion #region Append New Note public static bool Append_New_Note(string noteTitle, string noteBody) { // Convert the strings to note node // Get the node of the currently selected repo // Append the note node to the repo node's children return true; } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace ConsoleCalculator { public class CalculationOperationNotSupportedException : CalculationException { public string Operation { get; } /// <summary> /// /// </summary> public CalculationOperationNotSupportedException() : base("Specified operation is pout of the range") { } /// <summary> /// /// </summary> /// <param name="operation"></param> public CalculationOperationNotSupportedException(string operation) : this() { Operation = operation; } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public CalculationOperationNotSupportedException(string message, Exception innerException) : base(message,innerException) { } /// <summary> /// /// </summary> /// <param name="operation"></param> /// <param name="message"></param> public CalculationOperationNotSupportedException(string operation ,string message) : base(message) { Operation = operation; } public override string Message { get { string message = base.Message; if(Operation != null) { return message + Environment.NewLine + $"Unsuported operation {Operation}"; } else { return message; } } } } }
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved. namespace Naninovel { /// <summary> /// Used to store serialized data describing a pre-defined custom variable. /// </summary> [System.Serializable] public class CustomVariableData { public string Name; public string Value; } }
namespace _Tests { using System; using System.IO; using System.Reflection; using System.Security.Cryptography; using System.Text; public static class SimpleZip { internal class Inflater { private const int DECODE_HEADER = 0; private const int DECODE_DICT = 1; private const int DECODE_BLOCKS = 2; private const int DECODE_STORED_LEN1 = 3; private const int DECODE_STORED_LEN2 = 4; private const int DECODE_STORED = 5; private const int DECODE_DYN_HEADER = 6; private const int DECODE_HUFFMAN = 7; private const int DECODE_HUFFMAN_LENBITS = 8; private const int DECODE_HUFFMAN_DIST = 9; private const int DECODE_HUFFMAN_DISTBITS = 10; private const int DECODE_CHKSUM = 11; private const int FINISHED = 12; private static readonly int[] CPLENS = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; private static readonly int[] CPLEXT = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; private static readonly int[] CPDIST = new int[] { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; private static readonly int[] CPDEXT = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; private int mode; private int neededBits; private int repLength; private int repDist; private int uncomprLen; private bool isLastBlock; private SimpleZip.StreamManipulator input; private SimpleZip.OutputWindow outputWindow; private SimpleZip.InflaterDynHeader dynHeader; private SimpleZip.InflaterHuffmanTree litlenTree; private SimpleZip.InflaterHuffmanTree distTree; public Inflater(byte[] bytes) { this.input = new SimpleZip.StreamManipulator(); this.outputWindow = new SimpleZip.OutputWindow(); this.mode = 2; this.input.SetInput(bytes, 0, bytes.Length); } private bool DecodeHuffman() { int i = this.outputWindow.GetFreeSpace(); while(i >= 258) { int symbol; switch(this.mode) { case 7: while(((symbol = this.litlenTree.GetSymbol(this.input)) & -256) == 0) { this.outputWindow.Write(symbol); if(--i < 258) { return true; } } if(symbol >= 257) { this.repLength = SimpleZip.Inflater.CPLENS[symbol - 257]; this.neededBits = SimpleZip.Inflater.CPLEXT[symbol - 257]; goto IL_B7; } if(symbol < 0) { return false; } this.distTree = null; this.litlenTree = null; this.mode = 2; return true; case 8: goto IL_B7; case 9: goto IL_106; case 10: break; default: continue; } IL_138: if(this.neededBits > 0) { this.mode = 10; int num = this.input.PeekBits(this.neededBits); if(num < 0) { return false; } this.input.DropBits(this.neededBits); this.repDist += num; } this.outputWindow.Repeat(this.repLength, this.repDist); i -= this.repLength; this.mode = 7; continue; IL_106: symbol = this.distTree.GetSymbol(this.input); if(symbol < 0) { return false; } this.repDist = SimpleZip.Inflater.CPDIST[symbol]; this.neededBits = SimpleZip.Inflater.CPDEXT[symbol]; goto IL_138; IL_B7: if(this.neededBits > 0) { this.mode = 8; int num2 = this.input.PeekBits(this.neededBits); if(num2 < 0) { return false; } this.input.DropBits(this.neededBits); this.repLength += num2; } this.mode = 9; goto IL_106; } return true; } private bool Decode() { switch(this.mode) { case 2: { if(this.isLastBlock) { this.mode = 12; return false; } int num = this.input.PeekBits(3); if(num < 0) { return false; } this.input.DropBits(3); if((num & 1) != 0) { this.isLastBlock = true; } switch(num >> 1) { case 0: this.input.SkipToByteBoundary(); this.mode = 3; break; case 1: this.litlenTree = SimpleZip.InflaterHuffmanTree.defLitLenTree; this.distTree = SimpleZip.InflaterHuffmanTree.defDistTree; this.mode = 7; break; case 2: this.dynHeader = new SimpleZip.InflaterDynHeader(); this.mode = 6; break; } return true; } case 3: if((this.uncomprLen = this.input.PeekBits(16)) < 0) { return false; } this.input.DropBits(16); this.mode = 4; break; case 4: break; case 5: goto IL_137; case 6: if(!this.dynHeader.Decode(this.input)) { return false; } this.litlenTree = this.dynHeader.BuildLitLenTree(); this.distTree = this.dynHeader.BuildDistTree(); this.mode = 7; goto IL_1BB; case 7: case 8: case 9: case 10: goto IL_1BB; case 11: return false; case 12: return false; default: return false; } int num2 = this.input.PeekBits(16); if(num2 < 0) { return false; } this.input.DropBits(16); this.mode = 5; IL_137: int num3 = this.outputWindow.CopyStored(this.input, this.uncomprLen); this.uncomprLen -= num3; if(this.uncomprLen == 0) { this.mode = 2; return true; } return !this.input.IsNeedingInput; IL_1BB: return this.DecodeHuffman(); } public int Inflate(byte[] buf, int offset, int len) { int num = 0; while(true) { if(this.mode != 11) { int num2 = this.outputWindow.CopyOutput(buf, offset, len); offset += num2; num += num2; len -= num2; if(len == 0) { break; } } if(!this.Decode() && (this.outputWindow.GetAvailable() <= 0 || this.mode == 11)) { return num; } } return num; } } internal class StreamManipulator { private byte[] window; private int window_start; private int window_end; private uint buffer; private int bits_in_buffer; public int AvailableBits { get { return this.bits_in_buffer; } } public int AvailableBytes { get { return this.window_end - this.window_start + (this.bits_in_buffer >> 3); } } public bool IsNeedingInput { get { return this.window_start == this.window_end; } } public int PeekBits(int n) { if(this.bits_in_buffer < n) { if(this.window_start == this.window_end) { return -1; } this.buffer |= (uint)((uint)((int)(this.window[this.window_start++] & 255) | (int)(this.window[this.window_start++] & 255) << 8) << this.bits_in_buffer); this.bits_in_buffer += 16; } return (int)((ulong)this.buffer & (ulong)((long)((1 << n) - 1))); } public void DropBits(int n) { this.buffer >>= n; this.bits_in_buffer -= n; } public void SkipToByteBoundary() { this.buffer >>= (this.bits_in_buffer & 7); this.bits_in_buffer &= -8; } public int CopyBytes(byte[] output, int offset, int length) { int num = 0; while(this.bits_in_buffer > 0 && length > 0) { output[offset++] = (byte)this.buffer; this.buffer >>= 8; this.bits_in_buffer -= 8; length--; num++; } if(length == 0) { return num; } int num2 = this.window_end - this.window_start; if(length > num2) { length = num2; } Array.Copy(this.window, this.window_start, output, offset, length); this.window_start += length; if((this.window_start - this.window_end & 1) != 0) { this.buffer = (uint)(this.window[this.window_start++] & 255); this.bits_in_buffer = 8; } return num + length; } public void Reset() { this.buffer = (uint)(this.window_start = (this.window_end = (this.bits_in_buffer = 0))); } public void SetInput(byte[] buf, int off, int len) { if(this.window_start < this.window_end) { throw new InvalidOperationException(); } int num = off + len; if(0 > off || off > num || num > buf.Length) { throw new ArgumentOutOfRangeException(); } if((len & 1) != 0) { this.buffer |= (uint)((uint)(buf[off++] & 255) << this.bits_in_buffer); this.bits_in_buffer += 8; } this.window = buf; this.window_start = off; this.window_end = num; } } internal class OutputWindow { private const int WINDOW_SIZE = 32768; private const int WINDOW_MASK = 32767; private byte[] window = new byte[32768]; private int windowEnd; private int windowFilled; public void Write(int abyte) { if(this.windowFilled++ == 32768) { throw new InvalidOperationException(); } this.window[this.windowEnd++] = (byte)abyte; this.windowEnd &= 32767; } private void SlowRepeat(int repStart, int len, int dist) { while(len-- > 0) { this.window[this.windowEnd++] = this.window[repStart++]; this.windowEnd &= 32767; repStart &= 32767; } } public void Repeat(int len, int dist) { if((this.windowFilled += len) > 32768) { throw new InvalidOperationException(); } int num = this.windowEnd - dist & 32767; int num2 = 32768 - len; if(num > num2 || this.windowEnd >= num2) { this.SlowRepeat(num, len, dist); return; } if(len <= dist) { Array.Copy(this.window, num, this.window, this.windowEnd, len); this.windowEnd += len; return; } while(len-- > 0) { this.window[this.windowEnd++] = this.window[num++]; } } public int CopyStored(SimpleZip.StreamManipulator input, int len) { len = Math.Min(Math.Min(len, 32768 - this.windowFilled), input.AvailableBytes); int num = 32768 - this.windowEnd; int num2; if(len > num) { num2 = input.CopyBytes(this.window, this.windowEnd, num); if(num2 == num) { num2 += input.CopyBytes(this.window, 0, len - num); } } else { num2 = input.CopyBytes(this.window, this.windowEnd, len); } this.windowEnd = (this.windowEnd + num2 & 32767); this.windowFilled += num2; return num2; } public void CopyDict(byte[] dict, int offset, int len) { if(this.windowFilled > 0) { throw new InvalidOperationException(); } if(len > 32768) { offset += len - 32768; len = 32768; } Array.Copy(dict, offset, this.window, 0, len); this.windowEnd = (len & 32767); } public int GetFreeSpace() { return 32768 - this.windowFilled; } public int GetAvailable() { return this.windowFilled; } public int CopyOutput(byte[] output, int offset, int len) { int num = this.windowEnd; if(len > this.windowFilled) { len = this.windowFilled; } else { num = (this.windowEnd - this.windowFilled + len & 32767); } int num2 = len; int num3 = len - num; if(num3 > 0) { Array.Copy(this.window, 32768 - num3, output, offset, num3); offset += num3; len = num; } Array.Copy(this.window, num - len, output, offset, len); this.windowFilled -= num2; if(this.windowFilled < 0) { throw new InvalidOperationException(); } return num2; } public void Reset() { this.windowFilled = (this.windowEnd = 0); } } internal class InflaterHuffmanTree { private const int MAX_BITLEN = 15; private short[] tree; public static readonly SimpleZip.InflaterHuffmanTree defLitLenTree; public static readonly SimpleZip.InflaterHuffmanTree defDistTree; static InflaterHuffmanTree() { byte[] array = new byte[288]; int i = 0; while(i < 144) { array[i++] = 8; } while(i < 256) { array[i++] = 9; } while(i < 280) { array[i++] = 7; } while(i < 288) { array[i++] = 8; } SimpleZip.InflaterHuffmanTree.defLitLenTree = new SimpleZip.InflaterHuffmanTree(array); array = new byte[32]; i = 0; while(i < 32) { array[i++] = 5; } SimpleZip.InflaterHuffmanTree.defDistTree = new SimpleZip.InflaterHuffmanTree(array); } public InflaterHuffmanTree(byte[] codeLengths) { this.BuildTree(codeLengths); } private void BuildTree(byte[] codeLengths) { int[] array = new int[16]; int[] array2 = new int[16]; for(int i = 0; i < codeLengths.Length; i++) { int num = (int)codeLengths[i]; if(num > 0) { array[num]++; } } int num2 = 0; int num3 = 512; for(int j = 1; j <= 15; j++) { array2[j] = num2; num2 += array[j] << 16 - j; if(j >= 10) { int num4 = array2[j] & 130944; int num5 = num2 & 130944; num3 += num5 - num4 >> 16 - j; } } this.tree = new short[num3]; int num6 = 512; for(int k = 15; k >= 10; k--) { int num7 = num2 & 130944; num2 -= array[k] << 16 - k; int num8 = num2 & 130944; for(int l = num8; l < num7; l += 128) { this.tree[(int)SimpleZip.DeflaterHuffman.BitReverse(l)] = (short)(-num6 << 4 | k); num6 += 1 << k - 9; } } for(int m = 0; m < codeLengths.Length; m++) { int num9 = (int)codeLengths[m]; if(num9 != 0) { num2 = array2[num9]; int num10 = (int)SimpleZip.DeflaterHuffman.BitReverse(num2); if(num9 <= 9) { do { this.tree[num10] = (short)(m << 4 | num9); num10 += 1 << num9; } while(num10 < 512); } else { int num11 = (int)this.tree[num10 & 511]; int num12 = 1 << (num11 & 15); num11 = -(num11 >> 4); do { this.tree[num11 | num10 >> 9] = (short)(m << 4 | num9); num10 += 1 << num9; } while(num10 < num12); } array2[num9] = num2 + (1 << 16 - num9); } } } public int GetSymbol(SimpleZip.StreamManipulator input) { int num; if((num = input.PeekBits(9)) >= 0) { int num2; if((num2 = (int)this.tree[num]) >= 0) { input.DropBits(num2 & 15); return num2 >> 4; } int num3 = -(num2 >> 4); int n = num2 & 15; if((num = input.PeekBits(n)) >= 0) { num2 = (int)this.tree[num3 | num >> 9]; input.DropBits(num2 & 15); return num2 >> 4; } int availableBits = input.AvailableBits; num = input.PeekBits(availableBits); num2 = (int)this.tree[num3 | num >> 9]; if((num2 & 15) <= availableBits) { input.DropBits(num2 & 15); return num2 >> 4; } return -1; } else { int availableBits2 = input.AvailableBits; num = input.PeekBits(availableBits2); int num2 = (int)this.tree[num]; if(num2 >= 0 && (num2 & 15) <= availableBits2) { input.DropBits(num2 & 15); return num2 >> 4; } return -1; } } } internal class InflaterDynHeader { private const int LNUM = 0; private const int DNUM = 1; private const int BLNUM = 2; private const int BLLENS = 3; private const int LENS = 4; private const int REPS = 5; private static readonly int[] repMin = new int[] { 3, 3, 11 }; private static readonly int[] repBits = new int[] { 2, 3, 7 }; private byte[] blLens; private byte[] litdistLens; private SimpleZip.InflaterHuffmanTree blTree; private int mode; private int lnum; private int dnum; private int blnum; private int num; private int repSymbol; private byte lastLen; private int ptr; private static readonly int[] BL_ORDER = new int[] { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; public bool Decode(SimpleZip.StreamManipulator input) { while(true) { switch(this.mode) { case 0: this.lnum = input.PeekBits(5); if(this.lnum < 0) { return false; } this.lnum += 257; input.DropBits(5); this.mode = 1; goto IL_61; case 1: goto IL_61; case 2: goto IL_B9; case 3: break; case 4: goto IL_1A8; case 5: goto IL_1DE; default: continue; } IL_13B: while(this.ptr < this.blnum) { int num = input.PeekBits(3); if(num < 0) { return false; } input.DropBits(3); this.blLens[SimpleZip.InflaterDynHeader.BL_ORDER[this.ptr]] = (byte)num; this.ptr++; } this.blTree = new SimpleZip.InflaterHuffmanTree(this.blLens); this.blLens = null; this.ptr = 0; this.mode = 4; IL_1A8: int symbol; while(((symbol = this.blTree.GetSymbol(input)) & -16) == 0) { this.litdistLens[this.ptr++] = (this.lastLen = (byte)symbol); if(this.ptr == this.num) { return true; } } if(symbol < 0) { return false; } if(symbol >= 17) { this.lastLen = 0; } this.repSymbol = symbol - 16; this.mode = 5; IL_1DE: int n = SimpleZip.InflaterDynHeader.repBits[this.repSymbol]; int num2 = input.PeekBits(n); if(num2 < 0) { return false; } input.DropBits(n); num2 += SimpleZip.InflaterDynHeader.repMin[this.repSymbol]; while(num2-- > 0) { this.litdistLens[this.ptr++] = this.lastLen; } if(this.ptr == this.num) { return true; } this.mode = 4; continue; IL_B9: this.blnum = input.PeekBits(4); if(this.blnum < 0) { return false; } this.blnum += 4; input.DropBits(4); this.blLens = new byte[19]; this.ptr = 0; this.mode = 3; goto IL_13B; IL_61: this.dnum = input.PeekBits(5); if(this.dnum < 0) { return false; } this.dnum++; input.DropBits(5); this.num = this.lnum + this.dnum; this.litdistLens = new byte[this.num]; this.mode = 2; goto IL_B9; } return false; } public SimpleZip.InflaterHuffmanTree BuildLitLenTree() { byte[] array = new byte[this.lnum]; Array.Copy(this.litdistLens, 0, array, 0, this.lnum); return new SimpleZip.InflaterHuffmanTree(array); } public SimpleZip.InflaterHuffmanTree BuildDistTree() { byte[] array = new byte[this.dnum]; Array.Copy(this.litdistLens, this.lnum, array, 0, this.dnum); return new SimpleZip.InflaterHuffmanTree(array); } } internal class Deflater { private const int IS_FLUSHING = 4; private const int IS_FINISHING = 8; private const int BUSY_STATE = 16; private const int FLUSHING_STATE = 20; private const int FINISHING_STATE = 28; private const int FINISHED_STATE = 30; private int state = 16; private long totalOut; private SimpleZip.DeflaterPending pending; private SimpleZip.DeflaterEngine engine; public long TotalOut { get { return this.totalOut; } } public bool IsFinished { get { return this.state == 30 && this.pending.IsFlushed; } } public bool IsNeedingInput { get { return this.engine.NeedsInput(); } } public Deflater() { this.pending = new SimpleZip.DeflaterPending(); this.engine = new SimpleZip.DeflaterEngine(this.pending); } public void Finish() { this.state |= 12; } public void SetInput(byte[] buffer) { this.engine.SetInput(buffer); } public int Deflate(byte[] output) { int num = 0; int num2 = output.Length; int num3 = num2; while(true) { int num4 = this.pending.Flush(output, num, num2); num += num4; this.totalOut += (long)num4; num2 -= num4; if(num2 == 0 || this.state == 30) { goto IL_E2; } if(!this.engine.Deflate((this.state & 4) != 0, (this.state & 8) != 0)) { if(this.state == 16) { break; } if(this.state == 20) { for(int i = 8 + (-this.pending.BitCount & 7); i > 0; i -= 10) { this.pending.WriteBits(2, 10); } this.state = 16; } else if(this.state == 28) { this.pending.AlignToByte(); this.state = 30; } } } return num3 - num2; IL_E2: return num3 - num2; } } internal class DeflaterHuffman { public class Tree { public short[] freqs; public byte[] length; public int minNumCodes; public int numCodes; private short[] codes; private int[] bl_counts; private int maxLength; private SimpleZip.DeflaterHuffman dh; public Tree(SimpleZip.DeflaterHuffman dh, int elems, int minCodes, int maxLength) { this.dh = dh; this.minNumCodes = minCodes; this.maxLength = maxLength; this.freqs = new short[elems]; this.bl_counts = new int[maxLength]; } public void WriteSymbol(int code) { this.dh.pending.WriteBits((int)this.codes[code] & 65535, (int)this.length[code]); } public void SetStaticCodes(short[] stCodes, byte[] stLength) { this.codes = stCodes; this.length = stLength; } public void BuildCodes() { int[] array = new int[this.maxLength]; int num = 0; this.codes = new short[this.freqs.Length]; for(int i = 0; i < this.maxLength; i++) { array[i] = num; num += this.bl_counts[i] << 15 - i; } for(int j = 0; j < this.numCodes; j++) { int num2 = (int)this.length[j]; if(num2 > 0) { this.codes[j] = SimpleZip.DeflaterHuffman.BitReverse(array[num2 - 1]); array[num2 - 1] += 1 << 16 - num2; } } } private void BuildLength(int[] childs) { this.length = new byte[this.freqs.Length]; int num = childs.Length / 2; int num2 = (num + 1) / 2; int num3 = 0; for(int i = 0; i < this.maxLength; i++) { this.bl_counts[i] = 0; } int[] array = new int[num]; array[num - 1] = 0; for(int j = num - 1; j >= 0; j--) { if(childs[2 * j + 1] != -1) { int num4 = array[j] + 1; if(num4 > this.maxLength) { num4 = this.maxLength; num3++; } array[childs[2 * j]] = (array[childs[2 * j + 1]] = num4); } else { int num5 = array[j]; this.bl_counts[num5 - 1]++; this.length[childs[2 * j]] = (byte)array[j]; } } if(num3 == 0) { return; } int num6 = this.maxLength - 1; while(true) { if(this.bl_counts[--num6] != 0) { do { this.bl_counts[num6]--; this.bl_counts[++num6]++; num3 -= 1 << this.maxLength - 1 - num6; } while(num3 > 0 && num6 < this.maxLength - 1); if(num3 <= 0) { break; } } } this.bl_counts[this.maxLength - 1] += num3; this.bl_counts[this.maxLength - 2] -= num3; int num7 = 2 * num2; for(int num8 = this.maxLength; num8 != 0; num8--) { int k = this.bl_counts[num8 - 1]; while(k > 0) { int num9 = 2 * childs[num7++]; if(childs[num9 + 1] == -1) { this.length[childs[num9]] = (byte)num8; k--; } } } } public void BuildTree() { int num = this.freqs.Length; int[] array = new int[num]; int i = 0; int num2 = 0; for(int j = 0; j < num; j++) { int num3 = (int)this.freqs[j]; if(num3 != 0) { int num4 = i++; int num5; while(num4 > 0 && (int)this.freqs[array[num5 = (num4 - 1) / 2]] > num3) { array[num4] = array[num5]; num4 = num5; } array[num4] = j; num2 = j; } } while(i < 2) { int num6 = (num2 < 2) ? (++num2) : 0; array[i++] = num6; } this.numCodes = Math.Max(num2 + 1, this.minNumCodes); int num7 = i; int[] array2 = new int[4 * i - 2]; int[] array3 = new int[2 * i - 1]; int num8 = num7; for(int k = 0; k < i; k++) { int num9 = array[k]; array2[2 * k] = num9; array2[2 * k + 1] = -1; array3[k] = (int)this.freqs[num9] << 8; array[k] = k; } do { int num10 = array[0]; int num11 = array[--i]; int num12 = 0; int l; for(l = 1; l < i; l = l * 2 + 1) { if(l + 1 < i && array3[array[l]] > array3[array[l + 1]]) { l++; } array[num12] = array[l]; num12 = l; } int num13 = array3[num11]; while((l = num12) > 0 && array3[array[num12 = (l - 1) / 2]] > num13) { array[l] = array[num12]; } array[l] = num11; int num14 = array[0]; num11 = num8++; array2[2 * num11] = num10; array2[2 * num11 + 1] = num14; int num15 = Math.Min(array3[num10] & 255, array3[num14] & 255); num13 = (array3[num11] = array3[num10] + array3[num14] - num15 + 1); num12 = 0; for(l = 1; l < i; l = num12 * 2 + 1) { if(l + 1 < i && array3[array[l]] > array3[array[l + 1]]) { l++; } array[num12] = array[l]; num12 = l; } while((l = num12) > 0 && array3[array[num12 = (l - 1) / 2]] > num13) { array[l] = array[num12]; } array[l] = num11; } while(i > 1); this.BuildLength(array2); } public int GetEncodedLength() { int num = 0; for(int i = 0; i < this.freqs.Length; i++) { num += (int)(this.freqs[i] * (short)this.length[i]); } return num; } public void CalcBLFreq(SimpleZip.DeflaterHuffman.Tree blTree) { int num = -1; int i = 0; while(i < this.numCodes) { int num2 = 1; int num3 = (int)this.length[i]; int num4; int num5; if(num3 == 0) { num4 = 138; num5 = 3; } else { num4 = 6; num5 = 3; if(num != num3) { short[] expr_3B_cp_0 = blTree.freqs; int expr_3B_cp_1 = num3; expr_3B_cp_0[expr_3B_cp_1] += 1; num2 = 0; } } num = num3; i++; while(i < this.numCodes && num == (int)this.length[i]) { i++; if(++num2 >= num4) { break; } } if(num2 < num5) { short[] expr_8A_cp_0 = blTree.freqs; int expr_8A_cp_1 = num; expr_8A_cp_0[expr_8A_cp_1] += (short)num2; } else if(num != 0) { short[] expr_AB_cp_0 = blTree.freqs; int expr_AB_cp_1 = 16; expr_AB_cp_0[expr_AB_cp_1] += 1; } else if(num2 <= 10) { short[] expr_CD_cp_0 = blTree.freqs; int expr_CD_cp_1 = 17; expr_CD_cp_0[expr_CD_cp_1] += 1; } else { short[] expr_EA_cp_0 = blTree.freqs; int expr_EA_cp_1 = 18; expr_EA_cp_0[expr_EA_cp_1] += 1; } } } public void WriteTree(SimpleZip.DeflaterHuffman.Tree blTree) { int num = -1; int i = 0; while(i < this.numCodes) { int num2 = 1; int num3 = (int)this.length[i]; int num4; int num5; if(num3 == 0) { num4 = 138; num5 = 3; } else { num4 = 6; num5 = 3; if(num != num3) { blTree.WriteSymbol(num3); num2 = 0; } } num = num3; i++; while(i < this.numCodes && num == (int)this.length[i]) { i++; if(++num2 >= num4) { break; } } if(num2 < num5) { while(num2-- > 0) { blTree.WriteSymbol(num); } } else if(num != 0) { blTree.WriteSymbol(16); this.dh.pending.WriteBits(num2 - 3, 2); } else if(num2 <= 10) { blTree.WriteSymbol(17); this.dh.pending.WriteBits(num2 - 3, 3); } else { blTree.WriteSymbol(18); this.dh.pending.WriteBits(num2 - 11, 7); } } } } private const int BUFSIZE = 16384; private const int LITERAL_NUM = 286; private const int DIST_NUM = 30; private const int BITLEN_NUM = 19; private const int REP_3_6 = 16; private const int REP_3_10 = 17; private const int REP_11_138 = 18; private const int EOF_SYMBOL = 256; private static readonly int[] BL_ORDER; private static readonly byte[] bit4Reverse; private SimpleZip.DeflaterPending pending; private SimpleZip.DeflaterHuffman.Tree literalTree; private SimpleZip.DeflaterHuffman.Tree distTree; private SimpleZip.DeflaterHuffman.Tree blTree; private short[] d_buf; private byte[] l_buf; private int last_lit; private int extra_bits; private static readonly short[] staticLCodes; private static readonly byte[] staticLLength; private static readonly short[] staticDCodes; private static readonly byte[] staticDLength; public static short BitReverse(int toReverse) { return (short)((int)SimpleZip.DeflaterHuffman.bit4Reverse[toReverse & 15] << 12 | (int)SimpleZip.DeflaterHuffman.bit4Reverse[toReverse >> 4 & 15] << 8 | (int)SimpleZip.DeflaterHuffman.bit4Reverse[toReverse >> 8 & 15] << 4 | (int)SimpleZip.DeflaterHuffman.bit4Reverse[toReverse >> 12]); } static DeflaterHuffman() { SimpleZip.DeflaterHuffman.BL_ORDER = new int[] { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; SimpleZip.DeflaterHuffman.bit4Reverse = new byte[] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; SimpleZip.DeflaterHuffman.staticLCodes = new short[286]; SimpleZip.DeflaterHuffman.staticLLength = new byte[286]; int i = 0; while(i < 144) { SimpleZip.DeflaterHuffman.staticLCodes[i] = SimpleZip.DeflaterHuffman.BitReverse(48 + i << 8); SimpleZip.DeflaterHuffman.staticLLength[i++] = 8; } while(i < 256) { SimpleZip.DeflaterHuffman.staticLCodes[i] = SimpleZip.DeflaterHuffman.BitReverse(256 + i << 7); SimpleZip.DeflaterHuffman.staticLLength[i++] = 9; } while(i < 280) { SimpleZip.DeflaterHuffman.staticLCodes[i] = SimpleZip.DeflaterHuffman.BitReverse(-256 + i << 9); SimpleZip.DeflaterHuffman.staticLLength[i++] = 7; } while(i < 286) { SimpleZip.DeflaterHuffman.staticLCodes[i] = SimpleZip.DeflaterHuffman.BitReverse(-88 + i << 8); SimpleZip.DeflaterHuffman.staticLLength[i++] = 8; } SimpleZip.DeflaterHuffman.staticDCodes = new short[30]; SimpleZip.DeflaterHuffman.staticDLength = new byte[30]; for(i = 0; i < 30; i++) { SimpleZip.DeflaterHuffman.staticDCodes[i] = SimpleZip.DeflaterHuffman.BitReverse(i << 11); SimpleZip.DeflaterHuffman.staticDLength[i] = 5; } } public DeflaterHuffman(SimpleZip.DeflaterPending pending) { this.pending = pending; this.literalTree = new SimpleZip.DeflaterHuffman.Tree(this, 286, 257, 15); this.distTree = new SimpleZip.DeflaterHuffman.Tree(this, 30, 1, 15); this.blTree = new SimpleZip.DeflaterHuffman.Tree(this, 19, 4, 7); this.d_buf = new short[16384]; this.l_buf = new byte[16384]; } public void Init() { this.last_lit = 0; this.extra_bits = 0; } private int Lcode(int len) { if(len == 255) { return 285; } int num = 257; while(len >= 8) { num += 4; len >>= 1; } return num + len; } private int Dcode(int distance) { int num = 0; while(distance >= 4) { num += 2; distance >>= 1; } return num + distance; } public void SendAllTrees(int blTreeCodes) { this.blTree.BuildCodes(); this.literalTree.BuildCodes(); this.distTree.BuildCodes(); this.pending.WriteBits(this.literalTree.numCodes - 257, 5); this.pending.WriteBits(this.distTree.numCodes - 1, 5); this.pending.WriteBits(blTreeCodes - 4, 4); for(int i = 0; i < blTreeCodes; i++) { this.pending.WriteBits((int)this.blTree.length[SimpleZip.DeflaterHuffman.BL_ORDER[i]], 3); } this.literalTree.WriteTree(this.blTree); this.distTree.WriteTree(this.blTree); } public void CompressBlock() { for(int i = 0; i < this.last_lit; i++) { int num = (int)(this.l_buf[i] & 255); int num2 = (int)this.d_buf[i]; if(num2-- != 0) { int num3 = this.Lcode(num); this.literalTree.WriteSymbol(num3); int num4 = (num3 - 261) / 4; if(num4 > 0 && num4 <= 5) { this.pending.WriteBits(num & (1 << num4) - 1, num4); } int num5 = this.Dcode(num2); this.distTree.WriteSymbol(num5); num4 = num5 / 2 - 1; if(num4 > 0) { this.pending.WriteBits(num2 & (1 << num4) - 1, num4); } } else { this.literalTree.WriteSymbol(num); } } this.literalTree.WriteSymbol(256); } public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { this.pending.WriteBits(lastBlock ? 1 : 0, 3); this.pending.AlignToByte(); this.pending.WriteShort(storedLength); this.pending.WriteShort(~storedLength); this.pending.WriteBlock(stored, storedOffset, storedLength); this.Init(); } public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) { short[] expr_15_cp_0 = this.literalTree.freqs; int expr_15_cp_1 = 256; expr_15_cp_0[expr_15_cp_1] += 1; this.literalTree.BuildTree(); this.distTree.BuildTree(); this.literalTree.CalcBLFreq(this.blTree); this.distTree.CalcBLFreq(this.blTree); this.blTree.BuildTree(); int num = 4; for(int i = 18; i > num; i--) { if(this.blTree.length[SimpleZip.DeflaterHuffman.BL_ORDER[i]] > 0) { num = i + 1; } } int num2 = 14 + num * 3 + this.blTree.GetEncodedLength() + this.literalTree.GetEncodedLength() + this.distTree.GetEncodedLength() + this.extra_bits; int num3 = this.extra_bits; for(int j = 0; j < 286; j++) { num3 += (int)(this.literalTree.freqs[j] * (short)SimpleZip.DeflaterHuffman.staticLLength[j]); } for(int k = 0; k < 30; k++) { num3 += (int)(this.distTree.freqs[k] * (short)SimpleZip.DeflaterHuffman.staticDLength[k]); } if(num2 >= num3) { num2 = num3; } if(storedOffset >= 0 && storedLength + 4 < num2 >> 3) { this.FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); return; } if(num2 == num3) { this.pending.WriteBits(2 + (lastBlock ? 1 : 0), 3); this.literalTree.SetStaticCodes(SimpleZip.DeflaterHuffman.staticLCodes, SimpleZip.DeflaterHuffman.staticLLength); this.distTree.SetStaticCodes(SimpleZip.DeflaterHuffman.staticDCodes, SimpleZip.DeflaterHuffman.staticDLength); this.CompressBlock(); this.Init(); return; } this.pending.WriteBits(4 + (lastBlock ? 1 : 0), 3); this.SendAllTrees(num); this.CompressBlock(); this.Init(); } public bool IsFull() { return this.last_lit >= 16384; } public bool TallyLit(int lit) { this.d_buf[this.last_lit] = 0; this.l_buf[this.last_lit++] = (byte)lit; short[] expr_39_cp_0 = this.literalTree.freqs; expr_39_cp_0[lit] += 1; return this.IsFull(); } public bool TallyDist(int dist, int len) { this.d_buf[this.last_lit] = (short)dist; this.l_buf[this.last_lit++] = (byte)(len - 3); int num = this.Lcode(len - 3); short[] expr_46_cp_0 = this.literalTree.freqs; int expr_46_cp_1 = num; expr_46_cp_0[expr_46_cp_1] += 1; if(num >= 265 && num < 285) { this.extra_bits += (num - 261) / 4; } int num2 = this.Dcode(dist - 1); short[] expr_95_cp_0 = this.distTree.freqs; int expr_95_cp_1 = num2; expr_95_cp_0[expr_95_cp_1] += 1; if(num2 >= 4) { this.extra_bits += num2 / 2 - 1; } return this.IsFull(); } } internal class DeflaterEngine { private const int MAX_MATCH = 258; private const int MIN_MATCH = 3; private const int WSIZE = 32768; private const int WMASK = 32767; private const int HASH_SIZE = 32768; private const int HASH_MASK = 32767; private const int HASH_SHIFT = 5; private const int MIN_LOOKAHEAD = 262; private const int MAX_DIST = 32506; private const int TOO_FAR = 4096; private int ins_h; private short[] head; private short[] prev; private int matchStart; private int matchLen; private bool prevAvailable; private int blockStart; private int strstart; private int lookahead; private byte[] window; private byte[] inputBuf; private int totalIn; private int inputOff; private int inputEnd; private SimpleZip.DeflaterPending pending; private SimpleZip.DeflaterHuffman huffman; public DeflaterEngine(SimpleZip.DeflaterPending pending) { this.pending = pending; this.huffman = new SimpleZip.DeflaterHuffman(pending); this.window = new byte[65536]; this.head = new short[32768]; this.prev = new short[32768]; this.blockStart = (this.strstart = 1); } private void UpdateHash() { this.ins_h = ((int)this.window[this.strstart] << 5 ^ (int)this.window[this.strstart + 1]); } private int InsertString() { int num = (this.ins_h << 5 ^ (int)this.window[this.strstart + 2]) & 32767; short num2 = this.prev[this.strstart & 32767] = this.head[num]; this.head[num] = (short)this.strstart; this.ins_h = num; return (int)num2 & 65535; } private void SlideWindow() { Array.Copy(this.window, 32768, this.window, 0, 32768); this.matchStart -= 32768; this.strstart -= 32768; this.blockStart -= 32768; for(int i = 0; i < 32768; i++) { int num = (int)this.head[i] & 65535; this.head[i] = (short)((num >= 32768) ? (num - 32768) : 0); } for(int j = 0; j < 32768; j++) { int num2 = (int)this.prev[j] & 65535; this.prev[j] = (short)((num2 >= 32768) ? (num2 - 32768) : 0); } } public void FillWindow() { if(this.strstart >= 65274) { this.SlideWindow(); } while(this.lookahead < 262 && this.inputOff < this.inputEnd) { int num = 65536 - this.lookahead - this.strstart; if(num > this.inputEnd - this.inputOff) { num = this.inputEnd - this.inputOff; } Array.Copy(this.inputBuf, this.inputOff, this.window, this.strstart + this.lookahead, num); this.inputOff += num; this.totalIn += num; this.lookahead += num; } if(this.lookahead >= 3) { this.UpdateHash(); } } private bool FindLongestMatch(int curMatch) { int num = 128; int num2 = 128; short[] array = this.prev; int num3 = this.strstart; int num4 = this.strstart + this.matchLen; int num5 = Math.Max(this.matchLen, 2); int num6 = Math.Max(this.strstart - 32506, 0); int num7 = this.strstart + 258 - 1; byte b = this.window[num4 - 1]; byte b2 = this.window[num4]; if(num5 >= 8) { num >>= 2; } if(num2 > this.lookahead) { num2 = this.lookahead; } do { if(this.window[curMatch + num5] == b2 && this.window[curMatch + num5 - 1] == b && this.window[curMatch] == this.window[num3] && this.window[curMatch + 1] == this.window[num3 + 1]) { int num8 = curMatch + 2; num3 += 2; while(this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && this.window[++num3] == this.window[++num8] && num3 < num7) { } if(num3 > num4) { this.matchStart = curMatch; num4 = num3; num5 = num3 - this.strstart; if(num5 >= num2) { break; } b = this.window[num4 - 1]; b2 = this.window[num4]; } num3 = this.strstart; } } while((curMatch = ((int)array[curMatch & 32767] & 65535)) > num6 && --num != 0); this.matchLen = Math.Min(num5, this.lookahead); return this.matchLen >= 3; } private bool DeflateSlow(bool flush, bool finish) { if(this.lookahead < 262 && !flush) { return false; } while(this.lookahead >= 262 || flush) { if(this.lookahead == 0) { if(this.prevAvailable) { this.huffman.TallyLit((int)(this.window[this.strstart - 1] & 255)); } this.prevAvailable = false; this.huffman.FlushBlock(this.window, this.blockStart, this.strstart - this.blockStart, finish); this.blockStart = this.strstart; return false; } if(this.strstart >= 65274) { this.SlideWindow(); } int num = this.matchStart; int num2 = this.matchLen; if(this.lookahead >= 3) { int num3 = this.InsertString(); if(num3 != 0 && this.strstart - num3 <= 32506 && this.FindLongestMatch(num3) && this.matchLen <= 5 && this.matchLen == 3 && this.strstart - this.matchStart > 4096) { this.matchLen = 2; } } if(num2 >= 3 && this.matchLen <= num2) { this.huffman.TallyDist(this.strstart - 1 - num, num2); num2 -= 2; do { this.strstart++; this.lookahead--; if(this.lookahead >= 3) { this.InsertString(); } } while(--num2 > 0); this.strstart++; this.lookahead--; this.prevAvailable = false; this.matchLen = 2; } else { if(this.prevAvailable) { this.huffman.TallyLit((int)(this.window[this.strstart - 1] & 255)); } this.prevAvailable = true; this.strstart++; this.lookahead--; } if(this.huffman.IsFull()) { int num4 = this.strstart - this.blockStart; if(this.prevAvailable) { num4--; } bool flag = finish && this.lookahead == 0 && !this.prevAvailable; this.huffman.FlushBlock(this.window, this.blockStart, num4, flag); this.blockStart += num4; return !flag; } } return true; } public bool Deflate(bool flush, bool finish) { bool flag; do { this.FillWindow(); bool flush2 = flush && this.inputOff == this.inputEnd; flag = this.DeflateSlow(flush2, finish); } while(this.pending.IsFlushed && flag); return flag; } public void SetInput(byte[] buffer) { this.inputBuf = buffer; this.inputOff = 0; this.inputEnd = buffer.Length; } public bool NeedsInput() { return this.inputEnd == this.inputOff; } } internal class DeflaterPending { protected byte[] buf = new byte[65536]; private int start; private int end; private uint bits; private int bitCount; public int BitCount { get { return this.bitCount; } } public bool IsFlushed { get { return this.end == 0; } } public void WriteShort(int s) { this.buf[this.end++] = (byte)s; this.buf[this.end++] = (byte)(s >> 8); } public void WriteBlock(byte[] block, int offset, int len) { Array.Copy(block, offset, this.buf, this.end, len); this.end += len; } public void AlignToByte() { if(this.bitCount > 0) { this.buf[this.end++] = (byte)this.bits; if(this.bitCount > 8) { this.buf[this.end++] = (byte)(this.bits >> 8); } } this.bits = 0u; this.bitCount = 0; } public void WriteBits(int b, int count) { this.bits |= (uint)((uint)b << this.bitCount); this.bitCount += count; if(this.bitCount >= 16) { this.buf[this.end++] = (byte)this.bits; this.buf[this.end++] = (byte)(this.bits >> 8); this.bits >>= 16; this.bitCount -= 16; } } public int Flush(byte[] output, int offset, int length) { if(this.bitCount >= 8) { this.buf[this.end++] = (byte)this.bits; this.bits >>= 8; this.bitCount -= 8; } if(length > this.end - this.start) { length = this.end - this.start; Array.Copy(this.buf, this.start, output, offset, length); this.start = 0; this.end = 0; } else { Array.Copy(this.buf, this.start, output, offset, length); this.start += length; } return length; } } internal class ZipStream : MemoryStream { public void WriteShort(int value) { this.WriteByte((byte)(value & 255)); this.WriteByte((byte)(value >> 8 & 255)); } public void WriteInt(int value) { this.WriteShort(value); this.WriteShort(value >> 16); } public int ReadShort() { return this.ReadByte() | this.ReadByte() << 8; } public int ReadInt() { return this.ReadShort() | this.ReadShort() << 16; } public ZipStream() { } public ZipStream(byte[] buffer) : base(buffer, false) { } } public static string ExceptionMessage; private static bool PublicKeysMatch(Assembly executingAssembly, Assembly callingAssembly) { byte[] publicKey = executingAssembly.GetName().GetPublicKey(); byte[] publicKey2 = callingAssembly.GetName().GetPublicKey(); if(publicKey2 == null != (publicKey == null)) { return false; } if(publicKey2 != null) { for(int i = 0; i < publicKey2.Length; i++) { if(publicKey2[i] != publicKey[i]) { return false; } } } return true; } private static ICryptoTransform GetAesTransform(byte[] key, byte[] iv, bool decrypt) { ICryptoTransform result; using(SymmetricAlgorithm symmetricAlgorithm = new RijndaelManaged()) { result = (decrypt ? symmetricAlgorithm.CreateDecryptor(key, iv) : symmetricAlgorithm.CreateEncryptor(key, iv)); } return result; } private static ICryptoTransform GetDesTransform(byte[] key, byte[] iv, bool decrypt) { ICryptoTransform result; using(DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider()) { result = (decrypt ? dESCryptoServiceProvider.CreateDecryptor(key, iv) : dESCryptoServiceProvider.CreateEncryptor(key, iv)); } return result; } public static byte[] Unzip(byte[] buffer) { Assembly callingAssembly = Assembly.GetCallingAssembly(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); if(callingAssembly != executingAssembly && !SimpleZip.PublicKeysMatch(executingAssembly, callingAssembly)) { return null; } SimpleZip.ZipStream zipStream = new SimpleZip.ZipStream(buffer); byte[] array = new byte[0]; int num = zipStream.ReadInt(); if(num != 67324752) { int num2 = num >> 24; num -= num2 << 24; if(num == 8223355) { if(num2 == 1) { int num3 = zipStream.ReadInt(); array = new byte[num3]; int num5; for(int i = 0; i < num3; i += num5) { int num4 = zipStream.ReadInt(); num5 = zipStream.ReadInt(); byte[] array2 = new byte[num4]; zipStream.Read(array2, 0, array2.Length); SimpleZip.Inflater inflater = new SimpleZip.Inflater(array2); inflater.Inflate(array, i, num5); } } if(num2 == 2) { byte[] key = new byte[] { 154, 41, 66, 148, 125, 6, 16, 238 }; byte[] iv = new byte[] { 223, 25, 36, 206, 144, 228, 102, 121 }; using(ICryptoTransform desTransform = SimpleZip.GetDesTransform(key, iv, true)) { byte[] buffer2 = desTransform.TransformFinalBlock(buffer, 4, buffer.Length - 4); array = SimpleZip.Unzip(buffer2); } } if(num2 != 3) { goto IL_26B; } byte[] key2 = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; byte[] iv2 = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; using(ICryptoTransform aesTransform = SimpleZip.GetAesTransform(key2, iv2, true)) { byte[] buffer3 = aesTransform.TransformFinalBlock(buffer, 4, buffer.Length - 4); array = SimpleZip.Unzip(buffer3); goto IL_26B; } } throw new FormatException("Unknown Header"); } short num6 = (short)zipStream.ReadShort(); int num7 = zipStream.ReadShort(); int num8 = zipStream.ReadShort(); if(num != 67324752 || num6 != 20 || num7 != 0 || num8 != 8) { throw new FormatException("Wrong Header Signature"); } zipStream.ReadInt(); zipStream.ReadInt(); zipStream.ReadInt(); int num9 = zipStream.ReadInt(); int num10 = zipStream.ReadShort(); int num11 = zipStream.ReadShort(); if(num10 > 0) { byte[] buffer4 = new byte[num10]; zipStream.Read(buffer4, 0, num10); } if(num11 > 0) { byte[] buffer5 = new byte[num11]; zipStream.Read(buffer5, 0, num11); } byte[] array3 = new byte[zipStream.Length - zipStream.Position]; zipStream.Read(array3, 0, array3.Length); SimpleZip.Inflater inflater2 = new SimpleZip.Inflater(array3); array = new byte[num9]; inflater2.Inflate(array, 0, array.Length); IL_26B: zipStream.Close(); zipStream = null; return array; } public static byte[] Zip(byte[] buffer) { return SimpleZip.Zip(buffer, 1, null, null); } public static byte[] ZipAndEncrypt(byte[] buffer, byte[] key, byte[] iv) { return SimpleZip.Zip(buffer, 2, key, iv); } public static byte[] ZipAndAES(byte[] buffer, byte[] key, byte[] iv) { return SimpleZip.Zip(buffer, 3, key, iv); } private static byte[] Zip(byte[] buffer, int version, byte[] key, byte[] iv) { byte[] result; try { SimpleZip.ZipStream zipStream = new SimpleZip.ZipStream(); if(version == 0) { SimpleZip.Deflater deflater = new SimpleZip.Deflater(); DateTime now = DateTime.Now; long num = (long)((ulong)((now.Year - 1980 & 127) << 25 | now.Month << 21 | now.Day << 16 | now.Hour << 11 | now.Minute << 5 | (int)((uint)now.Second >> 1))); uint[] array = new uint[] { 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u }; uint num2 = 4294967295u; uint num3 = num2; int num4 = 0; int num5 = buffer.Length; while(--num5 >= 0) { num3 = (array[(int)((UIntPtr)((num3 ^ (uint)buffer[num4++]) & 255u))] ^ num3 >> 8); } num3 ^= num2; zipStream.WriteInt(67324752); zipStream.WriteShort(20); zipStream.WriteShort(0); zipStream.WriteShort(8); zipStream.WriteInt((int)num); zipStream.WriteInt((int)num3); long position = zipStream.Position; zipStream.WriteInt(0); zipStream.WriteInt(buffer.Length); byte[] bytes = Encoding.UTF8.GetBytes("{data}"); zipStream.WriteShort(bytes.Length); zipStream.WriteShort(0); zipStream.Write(bytes, 0, bytes.Length); deflater.SetInput(buffer); while(!deflater.IsNeedingInput) { byte[] array2 = new byte[512]; int num6 = deflater.Deflate(array2); if(num6 <= 0) { break; } zipStream.Write(array2, 0, num6); } deflater.Finish(); while(!deflater.IsFinished) { byte[] array3 = new byte[512]; int num7 = deflater.Deflate(array3); if(num7 <= 0) { break; } zipStream.Write(array3, 0, num7); } long totalOut = deflater.TotalOut; zipStream.WriteInt(33639248); zipStream.WriteShort(20); zipStream.WriteShort(20); zipStream.WriteShort(0); zipStream.WriteShort(8); zipStream.WriteInt((int)num); zipStream.WriteInt((int)num3); zipStream.WriteInt((int)totalOut); zipStream.WriteInt(buffer.Length); zipStream.WriteShort(bytes.Length); zipStream.WriteShort(0); zipStream.WriteShort(0); zipStream.WriteShort(0); zipStream.WriteShort(0); zipStream.WriteInt(0); zipStream.WriteInt(0); zipStream.Write(bytes, 0, bytes.Length); zipStream.WriteInt(101010256); zipStream.WriteShort(0); zipStream.WriteShort(0); zipStream.WriteShort(1); zipStream.WriteShort(1); zipStream.WriteInt(46 + bytes.Length); zipStream.WriteInt((int)((long)(30 + bytes.Length) + totalOut)); zipStream.WriteShort(0); zipStream.Seek(position, SeekOrigin.Begin); zipStream.WriteInt((int)totalOut); } else if(version == 1) { zipStream.WriteInt(25000571); zipStream.WriteInt(buffer.Length); byte[] array4; for(int i = 0; i < buffer.Length; i += array4.Length) { array4 = new byte[Math.Min(2097151, buffer.Length - i)]; Buffer.BlockCopy(buffer, i, array4, 0, array4.Length); long position2 = zipStream.Position; zipStream.WriteInt(0); zipStream.WriteInt(array4.Length); SimpleZip.Deflater deflater2 = new SimpleZip.Deflater(); deflater2.SetInput(array4); while(!deflater2.IsNeedingInput) { byte[] array5 = new byte[512]; int num8 = deflater2.Deflate(array5); if(num8 <= 0) { break; } zipStream.Write(array5, 0, num8); } deflater2.Finish(); while(!deflater2.IsFinished) { byte[] array6 = new byte[512]; int num9 = deflater2.Deflate(array6); if(num9 <= 0) { break; } zipStream.Write(array6, 0, num9); } long position3 = zipStream.Position; zipStream.Position = position2; zipStream.WriteInt((int)deflater2.TotalOut); zipStream.Position = position3; } } else { if(version == 2) { zipStream.WriteInt(41777787); byte[] array7 = SimpleZip.Zip(buffer, 1, null, null); using(ICryptoTransform desTransform = SimpleZip.GetDesTransform(key, iv, false)) { byte[] array8 = desTransform.TransformFinalBlock(array7, 0, array7.Length); zipStream.Write(array8, 0, array8.Length); goto IL_44F; } } if(version == 3) { zipStream.WriteInt(58555003); byte[] array9 = SimpleZip.Zip(buffer, 1, null, null); using(ICryptoTransform aesTransform = SimpleZip.GetAesTransform(key, iv, false)) { byte[] array10 = aesTransform.TransformFinalBlock(array9, 0, array9.Length); zipStream.Write(array10, 0, array10.Length); } } } IL_44F: zipStream.Flush(); zipStream.Close(); result = zipStream.ToArray(); } catch(Exception ex) { SimpleZip.ExceptionMessage = "ERR 2003: " + ex.Message; throw; } return result; } } }
using Core.Services.Data.Dto; using Newtonsoft.Json; using System.Collections.Generic; namespace Core.Services.Data { public class Activity { [JsonProperty(PropertyName = "id")] public string Id { get; set; } public string Notes { get; set; } public int Order { get; set; } public EquipmentDto Equipment { get; set; } public List<Set> Sets { get; set; } } }
namespace CVBuilder.Core { public interface IUpdatableBuilder<T> where T : class { void UpdateParrentBuilder(T model); } }
/* Copyright (c) 2014, Direct Project All rights reserved. Authors: Joe Shook Joseph.Shook@Surescripts.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of The Direct Project (directproject.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.ServiceModel; using Health.Direct.Config.Client; using Health.Direct.Config.Client.DomainManager; using Health.Direct.Config.Store; using Health.Direct.Config.Tools; using Health.Direct.Config.Tools.Command; using Health.Direct.Policy.Extensions; namespace Health.Direct.Config.Console.Command { /// <summary> /// Commands to manage Certificate Policies /// </summary> public class CertPolicyCommands : CommandsBase<CertPolicyStoreClient> { const int DefaultChunkSize = 10; //--------------------------------------- // // Commands // Sections: CertPolicy and CertPolicyGroup // //--------------------------------------- internal CertPolicyCommands(ConfigConsole console, Func<CertPolicyStoreClient> client) : base(console, client) { } /* * * * CertPolicy section * * * */ /// <summary> /// Import and add a certificate policy /// </summary> [Command(Name = "CertPolicy_Add", Usage = CertPolicyAddUsage)] public void CertPolicyAdd(string[] args) { string name = args.GetRequiredValue(0); string policyFile = args.GetRequiredValue(1); if (!File.Exists(policyFile)) { WriteLine("File does not exist", policyFile); return; } string policyText = File.ReadAllText(policyFile); string description = args.GetOptionalValue(3, string.Empty); PushPolicy(name, policyText, description, false); } private const string CertPolicyAddUsage = "Import a certificate policy from a file and push it into the config store." + Constants.CRLF + "Policies are associated to policy groups. Policy groups are linked to owners(domains or emails)." + Constants.CRLF + " name filePath options" + Constants.CRLF + " \t description: (optional) additional description"; /// <summary> /// Import and add a certificate policy, if one does not already exist /// </summary> [Command(Name = "CertPolicy_Ensure", Usage = CertPolicyEnsureUsage)] public void CertPolicyEnsure(string[] args) { string name = args.GetRequiredValue(0); string policyFile = args.GetRequiredValue(1); if (!File.Exists(policyFile)) { WriteLine("File does not exist", policyFile); return; } string policyText = File.ReadAllText(policyFile); string description = args.GetOptionalValue(3, string.Empty); PushPolicy(name, policyText, description, true); } private const string CertPolicyEnsureUsage = "Import a certificate policy from a file and push it into the config store - if not already there." + Constants.CRLF + "Policies are associated to policy groups. Policy groups are linked to owners(domains or emails)." + Constants.CRLF + " name filePath options" + Constants.CRLF + " \t description: (optional) additional description"; /// <summary> /// Retrieve a certificate policy /// </summary> [Command(Name = "CertPolicy_Get", Usage = CertPolicyGetUsage)] public void CertPolicyGet(string[] args) { string name = args.GetRequiredValue(0); Print(GetCertPolicy(name)); } private const string CertPolicyGetUsage = "Retrieve information for an existing certificate policy by name." + Constants.CRLF + " name"; /// <summary> /// List all certificate policies /// </summary> [Command(Name = "CertPolicies_List", Usage = "List all Policies")] public void CertPoliciesList(string[] args) { int chunkSize = args.GetOptionalValue(0, DefaultChunkSize); Print(Client.EnumerateCertPolicies(chunkSize)); } /// <summary> /// How many certificate policies exist? /// </summary> [Command(Name = "CertPolicies_Count", Usage = "Retrieve # of certificate policies.")] public void CertPoliciesCount(string[] args) { WriteLine("{0} certificate polices", Client.GetCertPoliciesCount()); } /// <summary> /// Delete policy from system by policy name. /// </summary> [Command(Name = "CertPolicy_Delete", Usage = CertPolicyDeleteUsage)] public void CertPolicyDelete(string[] args) { string name = args.GetRequiredValue(0); Client.RemovePolicy(name); } private const string CertPolicyDeleteUsage = "Delete policy from system by policy name." + Constants.CRLF + "policyName" + Constants.CRLF + " \t policyName: Name of the policy. Place the policy name in quotes (\"\") if there are spaces in the name."; /// <summary> /// Delete policy from a policy group /// </summary> [Command(Name = "CertPolicy_DeleteFromGroup", Usage = CertPolicyDeleteFromGroupUsage)] public void CertPolicyDeleteFromGroup(string[] args) { long mapId = args.GetRequiredValue<long>(0); Client.RemovePolicyUseFromGroup(mapId); } private const string CertPolicyDeleteFromGroupUsage = "Delete policy from a policy group ." + Constants.CRLF + "mapId" + Constants.CRLF + " \t mapId: Id that associates a group to a policy usage."; /* * * * CertPolicyGroup section * * * */ /// <summary> /// Create a certificate policy group /// </summary> [Command(Name = "CertPolicyGroup_Add", Usage = CertPolicyGroupAddUsage)] public void CertPolicyGroupAdd(string[] args) { string name = args.GetRequiredValue(0); string description = args.GetOptionalValue(1, string.Empty); PushPolicyGroup(name, description, false); } private const string CertPolicyGroupAddUsage = "Create a certificate policy group." + Constants.CRLF + "Certificate policy groups are created. " + Constants.CRLF + "Use CertPolicy_AddToGroup to join policies to groups and assign usage." + Constants.CRLF + "Use CertPolicy_AddToOwner to join groups to Domains or emails" + Constants.CRLF + " name options" + Constants.CRLF + " \t description: (optional) additional description"; /// <summary> /// Create a certificate policy group if one does not already exist /// </summary> [Command(Name = "CertPolicyGroup_Ensure", Usage = CertPolicyGroupEnsureUsage)] public void CertPolicyGroupEnsure(string[] args) { string name = args.GetRequiredValue(0); string description = args.GetOptionalValue(1, string.Empty); PushPolicyGroup(name, description, true); } private const string CertPolicyGroupEnsureUsage = "Create a certificate policy group - if not already there." + Constants.CRLF + "Certificate policy groups are created. " + Constants.CRLF + "Use CertPolicy_AddToGroup to join policies to groups and assign usage." + Constants.CRLF + "Use CertPolicy_AddToOwner to join groups to Domains or emails" + Constants.CRLF + " name options" + Constants.CRLF + " \t description: (optional) additional description"; /// <summary> /// Retrieve a certificate policy group /// </summary> [Command(Name = "CertPolicyGroup_Get", Usage = CertPolicyGroupGetUsage)] public void CertPolicyGroupGet(string[] args) { string name = args.GetRequiredValue(0); Print(GetCertPolicyGroup(name)); } private const string CertPolicyGroupGetUsage = "Retrieve information for an existing certificate policy group by name." + Constants.CRLF + " name"; /// <summary> /// Create a certificate policy group /// </summary> [Command(Name = "CertPolicy_AddToGroup", Usage = CertPolicyAddToGroupUsage)] public void CertPolicyAddToGroup(string[] args) { string policyName = args.GetRequiredValue(0); string groupName = args.GetRequiredValue(1); string use = args.GetRequiredValue(2); CertPolicyUse policyUse; if (!Enum.TryParse(use, true, out policyUse)) { WriteLine("Invalid CertPolicyUse{0}", use); } bool incoming = args.GetOptionalValue<bool>(3, true); bool outgoing = args.GetOptionalValue<bool>(4, true); PushAddPolicyToGroup(policyName, groupName, policyUse, incoming, outgoing, false); } private const string CertPolicyAddToGroupUsage = "Adds an existing policy to a group with a provided usage." + Constants.CRLF + "policyName groupNames policyUse incoming outgoing" + Constants.CRLF + " \t policyName: Name of the policy to add to the group. Place the policy name in quotes (\") if there are spaces in the name." + Constants.CRLF + " \t groupName: Name of the policy group to add the policy to. Place the policy group name in quotes (\") if there are spaces in the name." + Constants.CRLF + " \t policyUse: Usage name of the policy in the group. Must be one of the following values: TRUST, PRIVATE_RESOLVER, PUBLIC_RESOLVER." + Constants.CRLF + " \t forIncoming: Indicates if policy is used for incoming messages. Defaults to true" + Constants.CRLF + " \t forOutgoing: Indicates if policy is used for outgoing messages. Defaults to true"; /// <summary> /// Add policy to group with usage, if one does not already exist /// </summary> [Command(Name = "CertPolicy_EnsureToGroup", Usage = CertPolicyEnsureToGroupUsage)] public void CertPolicyEnsureToGroup(string[] args) { string policyName = args.GetRequiredValue(0); string groupName = args.GetRequiredValue(1); string use = args.GetRequiredValue(2); CertPolicyUse policyUse; if (!Enum.TryParse(use, true, out policyUse)) { WriteLine("Invalid CertPolicyUse{0}", use); } bool incoming = args.GetOptionalValue<bool>(3, true); bool outgoing = args.GetOptionalValue<bool>(4, true); PushAddPolicyToGroup(policyName, groupName, policyUse, incoming, outgoing, true); } private const string CertPolicyEnsureToGroupUsage = "Adds an existing policy to a group with a provided usage - if not already there." + Constants.CRLF + "policyName groupNames policyUse incoming outgoing" + Constants.CRLF + " \t policyName: Name of the policy to add to the group. Place the policy name in quotes (\") if there are spaces in the name." + Constants.CRLF + " \t groupName: Name of the policy group to add the policy to. Place the policy group name in quotes (\") if there are spaces in the name." + Constants.CRLF + " \t policyUse: Usage name of the policy in the group. Must be one of the following values: TRUST, PRIVATE_RESOLVER, PUBLIC_RESOLVER." + Constants.CRLF + " \t forIncoming: Indicates if policy is used for incoming messages. Defaults to true" + Constants.CRLF + " \t forOutgoing: Indicates if policy is used for outgoing messages. Defaults to true"; /// <summary> /// List all polici /// </summary> [Command(Name = "CertPolicyGroups_List", Usage = "List all policy groups")] public void CertPolicyGroupList(string[] args) { int chunkSize = args.GetOptionalValue(0, DefaultChunkSize); Print(Client.EnumerateCertPolicyGroups(chunkSize)); } /// <summary> /// How many certificate policies exist? /// </summary> [Command(Name = "CertPolicyGroups_Count", Usage = "Retrieve # of certificate policy groups.")] public void CertPolicyGroupCount(string[] args) { WriteLine("{0} certificate polices", Client.GetCertPolicyGroupCount()); } /// <summary> /// List all polici /// </summary> [Command(Name = "CertPolicyUsage_List", Usage = CertPolicyUsageListUsage)] public void CertPolicyUsageList(string[] args) { string groupName = args.GetRequiredValue(0); Print(GetCertPolicyGroupWithPolicies(groupName)); } private const string CertPolicyUsageListUsage = "List policies and their usage with in a policy group." + Constants.CRLF + "groupName" + Constants.CRLF + " \t groupName: Name of the policy group to search on. Place the policy group name in quotes (\") if there are spaces in the name."; /// <summary> /// Associate a certificate policy group to an owner /// </summary> [Command(Name = "CertPolicyGroup_AddOwner", Usage = CertPolicyGroupAddOwnerUsage)] public void CertPolicyGroupAddOwner(string[] args) { string groupName = args.GetRequiredValue(0); string owner = args.GetRequiredValue(1); AssociatePolicyGroupToDomain(groupName, owner, false); } private const string CertPolicyGroupAddOwnerUsage = "Adds an existing policy group to an existing owner." + Constants.CRLF + "groupName owner" + Constants.CRLF + " \t groupName: Name of the policy group. Place the policy group name in quotes (\") if there are spaces in the name." + Constants.CRLF + " \t owner: Name of the owner to associate with groupName."; /// <summary> /// Associate a certificate policy group to an owner, if one does not already exist /// </summary> [Command(Name = "CertPolicyGroup_EnsureOwner", Usage = CertPolicyGroupEnsureOwnerUsage)] public void CertPolicyGroupEnsureOwner(string[] args) { string groupName = args.GetRequiredValue(0); string owner = args.GetRequiredValue(1); AssociatePolicyGroupToDomain(groupName, owner, true); } private const string CertPolicyGroupEnsureOwnerUsage = "Adds an existing policy group to an existing owner. - if not already there." + Constants.CRLF + "groupName owner" + Constants.CRLF + " \t groupName: Name of the policy group. Place the policy group name in quotes (\") if there are spaces in the name." + Constants.CRLF + " \t owner: Name of the owner to associate with groupName."; /// <summary> /// List all owners associated to a policy group /// </summary> [Command(Name = "CertPolicyGroup_OwnersList", Usage = CertPolicyGroupOwnersListUsage)] public void CertPolicyGroup_OwnersList(string[] args) { string groupName = args.GetRequiredValue(0); Print(getCertPolicyGroupWithOwners(groupName)); } private const string CertPolicyGroupOwnersListUsage = "List owners associated with in a policy group." + Constants.CRLF + "groupName" + Constants.CRLF + " \t groupName: Name of the policy group to search on. Place the policy group name in quotes (\") if there are spaces in the name."; /// <summary> /// Delete policy group from system by group name. /// </summary> [Command(Name = "CertPolicyGroup_Delete", Usage = CertPolicyGroupDeleteUsage)] public void CertPolicyGroupDelete(string[] args) { string name = args.GetRequiredValue(0); Client.RemovePolicyGroup(name); } private const string CertPolicyGroupDeleteUsage = "Delete policy group from system by group name." + Constants.CRLF + "groupName" + Constants.CRLF + " \t groupName: Name of the policy group. Place the group name in quotes (\"\") if there are spaces in the name."; /// <summary> /// Deletes an existing policy group from a owner. /// </summary> [Command(Name = "CertPolicyGroup_DeleteFromOwner", Usage = CertPolicyGroupDeleteFromOwnerUsage)] public void CertPolicyGroupDeleteFromOwner(string[] args) { string groupName = args.GetRequiredValue(0); string ownerName = args.GetRequiredValue(1); Client.DisassociatePolicyGroupFromDomain(groupName, ownerName); } private const string CertPolicyGroupDeleteFromOwnerUsage = "Deletes an existing policy group from a owner." + Constants.CRLF + "groupName, ownerName" + Constants.CRLF + " \t groupId: Name of the policy group to delete from the owner. Place the policy group name in quotes (\"\") if there are spaces in the name." + Constants.CRLF + " \t ownerName: Name of the owner to delete the policy group from."; //--------------------------------------- // // Implementation details // //--------------------------------------- internal void PushPolicy(string name, string policyText, string description, bool checkForDupes) { try { if (!checkForDupes || !Client.Contains(name)) { CertPolicy certPolicy = new CertPolicy(name, description,policyText.ToBytesUtf8()); Client.AddPolicy(certPolicy); WriteLine("Added {0}", certPolicy.Name); } else { WriteLine("Exists {0}", name); } } catch (FaultException<ConfigStoreFault> ex) { if (ex.Detail.Error == ConfigStoreError.UniqueConstraint) { WriteLine("Exists {0}", name); } else { throw; } } } internal void PushPolicyGroup(string name, string description, bool checkForDupes) { try { if (!checkForDupes || !Client.Contains(name)) { CertPolicyGroup certPolicyGroup = new CertPolicyGroup(name, description); Client.AddPolicyGroup(certPolicyGroup); WriteLine("Added {0}", certPolicyGroup.Name); } else { WriteLine("Exists {0}", name); } } catch (FaultException<ConfigStoreFault> ex) { if (ex.Detail.Error == ConfigStoreError.UniqueConstraint) { WriteLine("Exists {0}", name); } else { throw; } } } internal void PushAddPolicyToGroup(string policyName, string groupName, CertPolicyUse policyUse, bool incoming, bool outgoing, bool checkForDupes) { try { if (!checkForDupes || !Client.Contains(policyName, groupName, policyUse, incoming, outgoing)) { Client.AddPolicyToGroup(policyName, groupName, policyUse, incoming, outgoing); WriteLine("Added {0} to {1}", policyName, groupName); WriteLine("With the following usage >"); WriteLine(" \t policyUse: {0}", policyUse.ToString()); WriteLine(" \t forIncoming: {0}", incoming); WriteLine(" \t forOutgoing: {0}", outgoing); } else { WriteLine("Policy to group association already exists"); } } catch (FaultException<ConfigStoreFault> ex) { if (ex.Detail.Error == ConfigStoreError.UniqueConstraint) { WriteLine("Policy to group association already exists"); } else { throw; } } } private void AssociatePolicyGroupToDomain(string groupName, string owner, bool checkForDupes) { try { if (!checkForDupes || !Client.Contains(groupName, owner)) { Client.AssociatePolicyGroupToDomain(groupName, owner); WriteLine("Associated {0} to {1}", groupName, owner); } else { WriteLine("Group to owner association already exists"); } } catch (FaultException<ConfigStoreFault> ex) { if (ex.Detail.Error == ConfigStoreError.UniqueConstraint) { WriteLine("Policy to group association already exists"); } else { throw; } } } private CertPolicy GetCertPolicy(string name) { CertPolicy certPolicy = Client.GetPolicyByName(name); if (certPolicy == null) { throw new ArgumentException(string.Format("CertPolicy {0} not found", name)); } return certPolicy; } private CertPolicyGroup GetCertPolicyGroup(string name) { CertPolicyGroup certPolicy = Client.GetPolicyGroupByName(name); if (certPolicy == null) { throw new ArgumentException(string.Format("CertPolicy {0} not found", name)); } return certPolicy; } private List<CertPolicyGroupMap> GetCertPolicyGroupWithPolicies(string name) { List<CertPolicyGroupMap> maps = Client.GetPolicyGroupByNameWithPolicies(name).ToList(); if (maps == null) { throw new ArgumentException(string.Format("CertPolicy {0} not found", name)); } return maps; } private List<CertPolicyGroupDomainMap> getCertPolicyGroupWithOwners(string name) { List<CertPolicyGroupDomainMap> maps = Client.GetPolicyGroupByNameWithOwners(name).ToList(); if (maps == null) { throw new ArgumentException(string.Format("CertPolicy {0} not found", name)); } return maps; } public void Print(IEnumerable<CertPolicy> policies) { foreach (CertPolicy policy in policies) { Print(policy); CommandUI.PrintSectionBreak(); } } public void Print(CertPolicy policy) { CommandUI.Print("ID", policy.ID); CommandUI.Print("Name", policy.Name); CommandUI.Print("Description", policy.Description); CommandUI.Print("CreateDate", policy.CreateDate); CommandUI.Print("Data", policy.Data.ToUtf8String()); CommandUI.Print("# of Groups", policy.CertPolicyGroups == null ? 0 : policy.CertPolicyGroups.Count); } public void Print(IEnumerable<CertPolicyGroup> policies) { foreach (CertPolicyGroup group in policies) { Print(group); CommandUI.PrintSectionBreak(); } } public void Print(CertPolicyGroup group) { CommandUI.Print("ID", group.ID); CommandUI.Print("Name", group.Name); CommandUI.Print("Description", group.Description); CommandUI.Print("CreateDate", group.CreateDate); } public void Print(List<CertPolicyGroupMap> maps) { if (!maps.Any()) { WriteLine("Group has no policies associated with it."); return; } CommandUI.Print("GroupName", maps.First().CertPolicyGroup.Name); CommandUI.Print("Description", maps.First().CertPolicyGroup.Description); foreach (CertPolicyGroupMap map in maps) { CommandUI.Print(" \t PolicyName \t ", map.CertPolicy.Name); CommandUI.Print(" \t Description \t ", map.CertPolicy.Description); CommandUI.Print(" \t MapId (link) \t ", map.ID); CommandUI.Print(" \t PolicyUse \t ", map.Use); CommandUI.Print(" \t ForIncoming \t ", map.ForIncoming); CommandUI.Print(" \t ForOutgoing \t ", map.ForOutgoing); CommandUI.Print(" \t CreateDate \t ", map.CreateDate); CommandUI.PrintDivider(); } } public void Print(List<CertPolicyGroupDomainMap> maps) { if (!maps.Any()) { WriteLine("Group has no owners associated with it."); return; } CommandUI.Print("GroupName", maps.First().CertPolicyGroup.Name); CommandUI.Print("Description", maps.First().CertPolicyGroup.Description); foreach (CertPolicyGroupDomainMap map in maps) { CommandUI.Print(" \t Owner \t ", map.Owner); CommandUI.Print(" \t CreateDate \t ", map.CreateDate); CommandUI.PrintDivider(); } } } }
using System; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; using Terraria.ObjectData; using Terraria.DataStructures; using Terraria.Enums; namespace Malum.Tiles { public class AzuriteBar : ModTile { public override void SetDefaults() { Main.tileSolid[Type] = false; Main.tileMergeDirt[Type] = false; drop = mod.ItemType("AzuriteBar"); AddMapEntry(new Color(0, 125, 125)); } } }
using UnityEngine; using System.Collections; public class P4_Purple_Particle : P0_Compound_Particle { //--------------------------------------- private Vector3 start; private Vector3 end; private float scalar = 0; private float sine = 0; private bool outgoing = true; //--------------------------------------- // Initializes start & endpoints // *** // Need to do more work here, and calculate endpoint based on // parents' movements (maybe this calc occurs during collision). // Sine_rate should be calculated in terms of the distance - // the particle should probably come to rest at the endpoint. // Not huge problem since lerp, but will look nicer. // *** void Start () { end = transform.position - (transform.forward * distance); start = transform.position; vertices = 2; } // Test whether particle is observed & call movement function if so. void FixedUpdate() { visible = renderer.isVisible; if (visible) { actual_decay -= Time.deltaTime; if (actual_decay > 0) { Oscillate(); } else { Decay(); } } } // This particle needs to move in a sinusoidal way along an axis. // The movement along the principle direction is handled by lerping. // Orthogonal movement (sinusoidal up-down) is handled by adding the .Sin() to its transform. void Oscillate (){ scalar += (Time.deltaTime / period) * vertices; sine += 360 / (distance * Time.deltaTime); if (outgoing){ transform.position = Vector3.Lerp (start, end, scalar); } else { transform.position = Vector3.Lerp (end, start, scalar); } if (transform.position == end || transform.position == start){ outgoing = !outgoing; scalar = 0; } transform.position += new Vector3 (0, Mathf.Sin (sine), 0); } void OnTriggerEnter(Collider other){ switch (other.tag) { case "Red": case "Blue": case "Yellow": break; default: messenger.Set(transform, other.gameObject.transform); gameObject.SendMessageUpwards ("Collide", messenger); break; } } }
using MassTransit; using Shared.Classes; using SyncService.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SyncService.Consumers { public class TestReadyConsumer : IConsumer<TestReadyMessage> { private readonly ISyncronisationService _syncronisationService; public TestReadyConsumer(ISyncronisationService syncronisationService) { _syncronisationService = syncronisationService; } public async Task Consume(ConsumeContext<TestReadyMessage> context) { await _syncronisationService.TestReady(context.Message); } } }
using Microsoft.Extensions.Logging; using QAToolKit.Auth.Keycloak; using System; using Xunit; using Xunit.Abstractions; namespace QAToolKit.Auth.Test.Keycloak { public class KeycloakOptionsTests { private readonly ILogger<KeycloakOptionsTests> _logger; public KeycloakOptionsTests(ITestOutputHelper testOutputHelper) { var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new XunitLoggerProvider(testOutputHelper)); _logger = loggerFactory.CreateLogger<KeycloakOptionsTests>(); } [Fact] public void KeycloakOptionsTest_Successful() { var options = new KeycloakOptions(); options.AddClientCredentialFlowParameters(new Uri("https://api.com/token"), "12345", "12345"); Assert.Equal("12345", options.ClientId); Assert.Equal("12345", options.Secret); Assert.Equal(new Uri("https://api.com/token"), options.TokenEndpoint); } [Fact] public void KeycloakOptionsNoImpersonationTest_Successful() { var options = new KeycloakOptions(); options.AddClientCredentialFlowParameters(new Uri("https://api.com/token"), "12345", "12345"); Assert.Equal("12345", options.ClientId); Assert.Equal("12345", options.Secret); Assert.Equal(new Uri("https://api.com/token"), options.TokenEndpoint); } [Theory] [InlineData("", "")] [InlineData(null, null)] [InlineData(null, "test")] [InlineData("test", null)] public void KeycloakOptionsUriNullTest_Fails(string clientId, string clientSecret) { var options = new KeycloakOptions(); Assert.Throws<ArgumentNullException>(() => options.AddClientCredentialFlowParameters(null, clientId, clientSecret)); } [Theory] [InlineData("", "")] [InlineData(null, null)] [InlineData(null, "test")] [InlineData("test", null)] public void KeycloakOptionsWrongUriTest_Fails(string clientId, string clientSecret) { var options = new KeycloakOptions(); Assert.Throws<UriFormatException>(() => options.AddClientCredentialFlowParameters(new Uri("https"), clientId, clientSecret)); } [Theory] [InlineData("", "")] [InlineData(null, null)] [InlineData(null, "test")] [InlineData("test", null)] public void KeycloakOptionsCorrectUriTest_Fails(string clientId, string clientSecret) { var options = new KeycloakOptions(); Assert.Throws<ArgumentNullException>(() => options.AddClientCredentialFlowParameters(new Uri("https://localhost/token"), clientId, clientSecret)); } } }
using Moq; using NETCommunity.FsCheck.Discounts.Payment; namespace NETCommunity.FsCheck.Tests.Discounts.Payment { public class ThreeSevenNetThirtyExtraTenSeasonalDiscountTests { private MockRepository mockRepository; [TestInitialize] public void TestInitialize() { this.mockRepository = new MockRepository(MockBehavior.Strict); } [TestCleanup] public void TestCleanup() { this.mockRepository.VerifyAll(); } [TestMethod] public void TestMethod1() { // Arrange // Act ThreeSevenNetThirtyExtraTenSeasonalDiscount threeSevenNetThirtyExtraTenSeasonalDiscount = this.CreateThreeSevenNetThirtyExtraTenSeasonalDiscount(); // Assert } private ThreeSevenNetThirtyExtraTenSeasonalDiscount CreateThreeSevenNetThirtyExtraTenSeasonalDiscount() { return new ThreeSevenNetThirtyExtraTenSeasonalDiscount(); } } }
using Kowalski.DataAccessLayer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kowalski.BusinessLayer.Services { public class JokeService : IJokeService { private readonly IDbContext dbContext; public JokeService(IDbContext dbContext) { this.dbContext = dbContext; } public async Task<string> GetJokeAsync() { var query = "SELECT TOP 1 Content FROM JOKES ORDER BY NEWID()"; var joke = await dbContext.GetAsync<string>(query); return joke; } } }
using Checkout.Payment.Query.Seedwork.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Checkout.Payment.Query.Application.Services; using Checkout.Payment.Query.Application.Interfaces; using Checkout.Payment.Query.Seedwork.Models; using MediatR; using System.Reflection; using Checkout.Payment.Query.Domain; using Checkout.Payment.Query.Seedwork.Extensions; using Checkout.Payment.Query.Domain.CommandHandlers; using Checkout.Payment.Query.Domain.Interfaces; using Checkout.Payment.Query.Data; using Microsoft.AspNetCore.Mvc; namespace Checkout.Payment.Query { public class Startup { public IConfiguration Configuration { get; } public ApplicationManifest Manifest { get; } public Startup(IConfiguration configuration) { Configuration = configuration; Manifest = Configuration.GetSection("ApplicationManifest").Get<ApplicationManifest>(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddSingleton(Manifest); services.AddScoped<IDomainNotification, DomainNotification>(); services.AddScoped<IPaymentService, PaymentService>(); services.AddScoped<IPaymentRepository, PaymentRepository>(); services.AddScoped<IRequestHandler<GetPaymentQuery, ITryResult<GetPaymentQueryResponse>>, PaymentQueryHandler>(); services.AddStackExchangeRedisCache(options => { options.Configuration = Configuration.GetConnectionString("PaymentCache"); }); services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; }); services.AddVersionedApiExplorer(options => { options.GroupNameFormat = "'v'VVV"; options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = true; options.SubstituteApiVersionInUrl = true; }); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = Manifest.Name, Version = Manifest.Version }); }); services.AddRouting(options => options.LowercaseUrls = true); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //app.UseHttpsRedirection(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using System; using System.Collections.Generic; using System.Linq; using serializacja; using Microsoft.VisualStudio.TestTools.UnitTesting; using kolekcje; namespace SerializacjaTests { [TestClass()] public class JsonConverterTests { [TestMethod()] public void SerializujTest() { new JsonConverter().Serializuj(new Gra("Fallout", "CD Projekt", 2008, 100, 10), "gra3"); new JsonConverter().Serializuj(new Gracz("Dariusz", "Krecina"), "gracz1"); new JsonConverter().Serializuj(new Zakup(new Gracz("Janusz", "Kowalski"), new Gra("Pokemon", "CD Projekt", 2008, 100, 10)), "zakup1"); Kolekcja k = new Kolekcja(); k.WypelnijZakupy(); new JsonConverter().Serializuj(k._gracze, "gracze1"); new JsonConverter().Serializuj(k._zakupy, "zakupy1"); new JsonConverter().Serializuj(k, "kolekcja1"); } [TestMethod()] public void DeSerializujTest() { Gra g = new JsonConverter().DeSerializuj<Gra>("gra3"); Console.WriteLine(g.ToString()); Gracz gr = new JsonConverter().DeSerializuj<Gracz>("gracz1"); Console.WriteLine(gr.ToString()); Zakup zak = new JsonConverter().DeSerializuj<Zakup>("zakup1"); Console.WriteLine(zak.ToString()); var gracze = new JsonConverter().DeSerializuj<List<Gracz>>("gracze1"); Console.WriteLine("Lista graczy:"); foreach(var gracz in gracze) { Console.WriteLine(gracz.ToString()); } Kolekcja k = new JsonConverter().DeSerializuj<Kolekcja>("kolekcja1"); Console.WriteLine(k.ToString()); } } }
using Microsoft.AspNetCore.Mvc.Filters; using System.Threading.Tasks; namespace iCopy.SERVICES.Attributes { public class LoggedInRedirectToActionAttribute : ActionFilterAttribute { public string RedirectToAction { get; set; } public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (context.HttpContext.User.Identity.IsAuthenticated) context.HttpContext.Response.Redirect(RedirectToAction); else { await next(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Converter.Units { [Unit(nameof(LenghtUnit))] class Inches : LenghtUnit { protected override double UnitDevidedByMeter => 0.0254; public override string ToString() { return nameof(Inches); } } }
using System; using System.Threading.Tasks; using Newtonsoft.Json; namespace Currency.Client.Model.Storage { public class JsonDao<T> : IDao<T> { private readonly Func<Task<string>> _streamReader; private readonly Func<string, Task> _streamWriter; public JsonDao(Func<string, Task> streamWriter, Func<Task<string>> streamReader) { _streamWriter = streamWriter; _streamReader = streamReader; } public Task WriteAsync(T dict) { string json = JsonConvert.SerializeObject(dict); return _streamWriter.Invoke(json); } public async Task<T> ReadAsync() { string json = await _streamReader.Invoke(); return string.IsNullOrEmpty(json) ? default : JsonConvert.DeserializeObject<T>(json); } } }
using UnityEngine; using UnityEngine.UI; public class LocalizedText : MonoBehaviour { public string key; private Text text; // Start is called before the first frame update void Start() { text = GetComponent<Text>(); //cogemos el texto del objeto text.text = LocalizationManager.localizationInstance.GetLocalizedValue(key); //cambiamos el texto } public void UpdateText() { text.text = LocalizationManager.localizationInstance.GetLocalizedValue(key); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerShoot : MonoBehaviour { public bool facingRight = true; public float fireRate = 5; public float timeToFire = 1; public Transform playerEntity; public GameObject bulletRightPrefab; public GameObject bulletLeftPrefab; Vector2 move; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { move.x = Input.GetAxis("Horizontal"); if (Input.GetButtonDown ("Fire1") && facingRight) bulletShootRight(); if (Input.GetButtonDown ("Fire1") && facingRight==false) bulletShootLeft(); if (move.x > 0.01f) facingRight = true; else if (move.x < -0.01f) facingRight = false; } public void bulletShootRight() { GameObject b = Instantiate(bulletRightPrefab) as GameObject; b.transform.position = playerEntity.transform.position; } public void bulletShootLeft() { GameObject b = Instantiate(bulletLeftPrefab) as GameObject; b.transform.position = playerEntity.transform.position; } }
using System; using System.Collections.Generic; namespace RMAT3.Models { public class WarrantyType { public WarrantyType() { AuditWarranties = new List<AuditWarranty>(); SectionQuestionTypes = new List<SectionQuestionType>(); } public int WarrantyTypeId { get; set; } public string AddedByUserId { get; set; } public DateTime AddTs { get; set; } public string UpdatedByUserId { get; set; } public string UpdatedCommentTxt { get; set; } public DateTime UpdatedTs { get; set; } public bool IsActiveInd { get; set; } public DateTime EffectiveFromDt { get; set; } public DateTime? EffectiveToDt { get; set; } public string WarrantyNm { get; set; } public string WarrantyTimelineTxt { get; set; } public string WarrantyTypeTxt { get; set; } public virtual ICollection<AuditWarranty> AuditWarranties { get; set; } public virtual ICollection<SectionQuestionType> SectionQuestionTypes { get; set; } } }
using MKService.Queries; using MKService.Updates; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MKService.ModelFactories { internal class ClickFactory : ModelFactoryBase<IUpdatableClick> { public override IUpdatableClick Create() { return new ClickQuery(); } } }
using ServerKinect.DataSource; using ServerKinect.Shape; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.HandTracking { public class HandDataSource : DataSourceProcessor<HandCollection, ShapeCollection>, IHandDataSource { private IntSize size; private ShapeHandDataFactory factory; public HandDataSource(IShapeDataSource shapeDataSource) : this(shapeDataSource, new HandDataSourceSettings()) { } public HandDataSource(IShapeDataSource shapeDataSource, HandDataSourceSettings settings) : base(shapeDataSource) { this.factory = new ShapeHandDataFactory(settings); this.size = shapeDataSource.Size; this.CurrentValue = new HandCollection(); } public int Width { get { return this.size.Width; } } public int Height { get { return this.size.Height; } } public IntSize Size { get { return this.size; } } protected override unsafe HandCollection Process(ShapeCollection shapeData) { return this.factory.Create(shapeData); } } }
using BPiaoBao.AppServices.Contracts.Cashbag; using BPiaoBao.AppServices.DataContracts.Cashbag; using BPiaoBao.Client.UIExt; using GalaSoft.MvvmLight.Threading; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace BPiaoBao.Client.Account.ViewModel { /// <summary> /// 交易记录视图模型 /// </summary> public class TransactionLogViewModel : PageBaseViewModel { #region 构造函数 /// <summary> /// Initializes a new instance of the <see cref="TransactionLogViewModel"/> class. /// </summary> public TransactionLogViewModel() { if (IsInDesignMode) return; Initialize(); } /// <summary> /// 初始化数据 /// </summary> public override void Initialize() { if (CanExecuteQueryCommand()) ExecuteQueryCommand();//第一次默认加载数据 } #endregion #region 公开属性 #region BargainLogs /// <summary> /// The <see cref="BargainLogs" /> property's name. /// </summary> private const string BargainLogsPropertyName = "BargainLogs"; private ObservableCollection<BargainLogDto> _bargainLogs = new ObservableCollection<BargainLogDto>(); /// <summary> /// 交易记录 /// </summary> public ObservableCollection<BargainLogDto> BargainLogs { get { return _bargainLogs; } set { if (_bargainLogs == value) return; RaisePropertyChanging(BargainLogsPropertyName); _bargainLogs = value; RaisePropertyChanged(BargainLogsPropertyName); } } #endregion #region OutTradeNo /// <summary> /// The <see cref="OutTradeNo" /> property's name. /// </summary> private const string OutTradeNoPropertyName = "OutTradeNo"; private string _outTradeNo; /// <summary> /// 交易号 /// </summary> public string OutTradeNo { get { return _outTradeNo; } set { if (_outTradeNo == value) return; RaisePropertyChanging(OutTradeNoPropertyName); _outTradeNo = value; RaisePropertyChanged(OutTradeNoPropertyName); } } #endregion #endregion #region 公开命令 /// <summary> /// 检查是否可以执行命令 /// </summary> /// <returns></returns> protected override bool CanExecuteQueryCommand() { return !IsBusy; } /// <summary> /// 执行查询命令 /// </summary> protected override void ExecuteQueryCommand() { IsBusy = true; BargainLogs.Clear(); Action action = () => CommunicateManager.Invoke<IAccountService>(service => { var dataPack = service.GetBargainLog(StartTime, EndTime, (CurrentPageIndex - 1) * PageSize, PageSize,OutTradeNo); TotalCount = dataPack.TotalCount; foreach (var item in dataPack.List) { DispatcherHelper.UIDispatcher.Invoke(new Action<BargainLogDto>(BargainLogs.Add), item); } }, UIManager.ShowErr); Task.Factory.StartNew(action).ContinueWith(task => { Action setAction = () => { IsBusy = false; }; DispatcherHelper.UIDispatcher.Invoke(setAction); }); } #endregion } }
using System.Security.Claims; using GraphQL.Types; using Im.Access.GraphPortal.Repositories; namespace Im.Access.GraphPortal.Graph.OperationalGroup.Mutations { public class OperationalMutationType : ObjectGraphType { public OperationalMutationType( ICircuitBreakerPolicyRepository circuitBreakerPolicyRepository, IChaosPolicyRepository chaosPolicyRepository) { FieldAsync<CircuitBreakerPolicyType>( "updateCircuitBreakerPolicy", arguments: new QueryArguments( new QueryArgument<NonNullGraphType<CircuitBreakerPolicyInputType>> { Name = "circuitBreakerPolicy" }), resolve: async (context) => { var circuitBreakerPolicy = context.GetArgument<CircuitBreakerPolicyInput>("circuitBreakerPolicy"); return await circuitBreakerPolicyRepository.UpdateAsync( context.UserContext as ClaimsPrincipal, circuitBreakerPolicy, context.CancellationToken); }); FieldAsync<ChaosPolicyType>( "updateChaosPolicy", arguments: new QueryArguments( new QueryArgument<NonNullGraphType<ChaosPolicyInputType>> { Name = "chaosPolicy" }), resolve: async (context) => { var chaosPolicy = context.GetArgument<ChaosPolicyInput>("chaosPolicy"); return await chaosPolicyRepository.UpdateAsync( context.UserContext as ClaimsPrincipal, chaosPolicy, context.CancellationToken); }); } } }
using System.Collections.Generic; using System.Linq; using SearchFoodServer.CompositeClass; namespace SearchFoodServer.CAD { public class TypesCuisineCad { public List<CompositeTypesCuisine> GetTypesCuisine() { List<CompositeTypesCuisine> typesCuisinesList = new List<CompositeTypesCuisine>(); List<Type_Cuisine> typesCuisine; using (var bdd = new searchfoodEntities()) { var requete = from tc in bdd.Type_Cuisine select tc; typesCuisine = requete.ToList(); } if (typesCuisine.Count > 0) { foreach (Type_Cuisine tc in typesCuisine) { CompositeTypesCuisine composite = new CompositeTypesCuisine(); composite.IdTypesCuisineValue = tc.Id_Type_Cuisine; composite.TypesCuisineValue = tc.Type_Cuisine1; typesCuisinesList.Add(composite); } } return typesCuisinesList; } public CompositeTypesCuisine GetTypeCuisine(int id) { CompositeTypesCuisine compositeTypesCuisine = new CompositeTypesCuisine(); Type_Cuisine typesCuisine; using (var bdd = new searchfoodEntities()) { var requete = from tc in bdd.Type_Cuisine where tc.Id_Type_Cuisine == id select tc; typesCuisine = requete.FirstOrDefault(); } if (typesCuisine != null) { compositeTypesCuisine.IdTypesCuisineValue = typesCuisine.Id_Type_Cuisine; compositeTypesCuisine.TypesCuisineValue = typesCuisine.Type_Cuisine1; } return compositeTypesCuisine; } public void AddTypesCuisine(Type_Cuisine tc) { using (var bdd = new searchfoodEntities()) { bdd.Type_Cuisine.Add(tc); bdd.SaveChanges(); } } public void DeleteTypesCuisine(int id) { using (var bdd = new searchfoodEntities()) { var requete = from tc in bdd.Type_Cuisine where tc.Id_Type_Cuisine == id select tc; Type_Cuisine typesCuisine = requete.FirstOrDefault(); if (typesCuisine != null) { bdd.Type_Cuisine.Remove(typesCuisine); bdd.SaveChanges(); } } } public void UpdateTypesCuisine(Type_Cuisine tc) { using (var bdd = new searchfoodEntities()) { Type_Cuisine typesCuisine = bdd.Type_Cuisine.Find(tc.Id_Type_Cuisine); if (typesCuisine != null) { bdd.Entry(typesCuisine).CurrentValues.SetValues(tc); bdd.SaveChanges(); } } } } }
using Microsoft.Practices.Unity; using Microsoft.Web.Infrastructure.DynamicModuleHelper; [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ZSharp.Demo.WebApi.UnityApiActivator), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(ZSharp.Demo.WebApi.UnityApiActivator), "Shutdown")] namespace ZSharp.Demo.WebApi { /// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary> public static class UnityApiActivator { /// <summary>Integrates Unity when the application starts.</summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule)); } /// <summary>Disposes the Unity container when the application is shut down.</summary> public static void Shutdown() { var container = UnityConfig.GetConfiguredContainer(); container.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BPiaoBao.Common.Enums; using JoveZhao.Framework.DDD; namespace BPiaoBao.DomesticTicket.Domain.Models.TravelPaper { /// <summary> /// 行程单发放记录 /// </summary> public class TravelGrantRecord : EntityBase, IAggregationRoot { public TravelGrantRecord() { this.GrantTime = DateTime.Parse("1900-01-01"); } protected override string GetIdentity() { return ID.ToString(); } public int ID { get; set; } /// <summary> /// 运营商户号 /// </summary> public string BusinessmanCode { get; set; } /// <summary> /// 运营商户名 /// </summary> public string BusinessmanName { get; set; } /// <summary> /// 采购商户号 /// </summary> public string UseBusinessmanCode { get; set; } /// <summary> /// 采购商户名 /// </summary> public string UseBusinessmanName { get; set; } /// <summary> /// 分配行程单号段范围 /// </summary> public string TripScope { set; get; } /// <summary> /// Office /// </summary> public string Office { set; get; } /// <summary> /// 分配行程单张数 /// </summary> public int TripCount { set; get; } /// <summary> /// 分配行程单备注 /// </summary> public string TripRemark { set; get; } /// <summary> /// 分配时间 /// </summary> public DateTime GrantTime { get; set; } } }
namespace PhotographerSystem.Models { using Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; public class Tag { public Tag() { this.Albums = new HashSet<Album>(); } [Key] public int Id { get; set; } [Tag] public string Name { get; set; } public virtual ICollection<Album> Albums { get; set; } } }
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 Entity; using LogicHandler; using Ultilities; using System.Globalization; namespace SightExam { public partial class QuestionControl : UserControl { private static QuestionControl _instance; public static QuestionControl GetInstance() { if (_instance == null) _instance = new QuestionControl(); return _instance; } private String AutoGenQuizID() { Questions quiz = new Questions(); QuestionsHandler Qhan = new QuestionsHandler(quiz); Int32 n = Int32.Parse(Qhan.CountId().Rows[0][0].ToString()) + 1; return "Q" + n; } public QuestionControl() { InitializeComponent(); } private void Display() { btnAdd.Enabled = false; Questions quiz = new Questions(); QuestionsHandler Qhan = new QuestionsHandler(quiz); try { dgvQuiz.DataSource = Qhan.GetList(); dgvQuiz.Columns[0].HeaderText = "Mã câu hỏi"; dgvQuiz.Columns[1].HeaderText = "Câu hỏi"; dgvQuiz.Columns[2].HeaderText = "Mã người tạo"; dgvQuiz.Columns[3].HeaderText = "Thời gian tạo"; } catch (CustomException cex) { MessageBox.Show("Lỗi " + cex.Error.ErrorMessage); } } private void GetAnswer() { Answers ans = new Answers(); AnswersHandler Ahan = new AnswersHandler(ans); ans.QuestionId = lblQId.Text.Trim(); try { dgvAnswer.DataSource = Ahan.GetList(); } catch (CustomException cex) { MessageBox.Show("Lỗi " + cex.Error.ErrorMessage); } } private void QuestionControl_Load(object sender, EventArgs e) { Display(); } private void dgvQuiz_CellClick(object sender, DataGridViewCellEventArgs e) { int row = e.RowIndex; if (row >= 0) { lblQId.Text = dgvQuiz.Rows[row].Cells[0].Value.ToString(); txtQuiz.Text = dgvQuiz.Rows[row].Cells[1].Value.ToString(); GetAnswer(); //lấy các câu trả lời của câu hỏi đc chọn //gán giá trị lấy được từ bảng đc trả về từ GetAnswer() txtAn1.Text = dgvAnswer.Rows[0].Cells[2].Value.ToString(); if (dgvAnswer.Rows[0].Cells[3].Value.ToString() == "True") cbox1.Checked = true; else cbox1.Checked = false; txtAn2.Text = dgvAnswer.Rows[1].Cells[2].Value.ToString(); if (dgvAnswer.Rows[1].Cells[3].Value.ToString() == "True") cbox2.Checked = true; else cbox2.Checked = false; txtAn3.Text = dgvAnswer.Rows[2].Cells[2].Value.ToString(); if (dgvAnswer.Rows[2].Cells[3].Value.ToString() == "True") cbox3.Checked = true; else cbox3.Checked = false; txtAn4.Text = dgvAnswer.Rows[3].Cells[2].Value.ToString(); if (dgvAnswer.Rows[3].Cells[3].Value.ToString() == "True") cbox4.Checked = true; else cbox4.Checked = false; } } private void btnAdd_Click(object sender, EventArgs e) { Questions quiz = new Questions(); QuestionsHandler Qhan = new QuestionsHandler(quiz); List<Answers> lst = new List<Answers>(); Answers an1 = new Answers(); Answers an2 = new Answers(); Answers an3 = new Answers(); Answers an4 = new Answers(); AnswersHandler Ahan = new AnswersHandler(lst); try { quiz.QuestionId = AutoGenQuizID(); quiz.Question = txtQuiz.Text; quiz.CreatorId = MainUI.UserID; quiz.CreatedTime = Int32.Parse(DateTime.Now.ToString("yyyyMMdd")); an1.AnswerId = "A1" + quiz.QuestionId; an2.AnswerId = "A2" + quiz.QuestionId; an3.AnswerId = "A3" + quiz.QuestionId; an4.AnswerId = "A4" + quiz.QuestionId; an1.Answer = txtAn1.Text; an2.Answer = txtAn2.Text; an3.Answer = txtAn3.Text; an4.Answer = txtAn4.Text; an1.QuestionId = quiz.QuestionId; an2.QuestionId = quiz.QuestionId; an3.QuestionId = quiz.QuestionId; an4.QuestionId = quiz.QuestionId; if (cbox1.Checked) an1.Correct = true; else an1.Correct = false; if (cbox2.Checked) an2.Correct = true; else an2.Correct = false; if (cbox3.Checked) an3.Correct = true; else an3.Correct = false; if (cbox4.Checked) an4.Correct = true; else an4.Correct = false; lst.Add(an1); lst.Add(an2); lst.Add(an3); lst.Add(an4); if(txtAn1.Text == "" || txtAn2.Text == "" || txtAn3.Text == "" || txtAn4.Text == ""|| txtQuiz.Text == "") { throw new CustomException(ErrorInfo.EMPTY); } else if(!cbox1.Checked && !cbox2.Checked && !cbox3.Checked && !cbox4.Checked) { MessageBox.Show("Phải có ít nhất 1 câu trả lời đúng!"); throw new CustomException(ErrorInfo.EMPTY); } Qhan.CreateSingle(); Ahan.CreateMultiple(); MessageBox.Show("Thêm thành công", "Thông báo", MessageBoxButtons.OK); QuestionControl_Load(sender, e); } catch (CustomException cex) { MessageBox.Show("Lỗi: " + cex.Error.ErrorMessage); } catch (FormatException exx) { MessageBox.Show("Lỗi: Bạn đã nhập sai định dạng, hãy kiểm tra lại"); } catch (Exception ex) { MessageBox.Show("Lỗi: " + ex.Message.ToString()); } } private void btnEdit_Click(object sender, EventArgs e) { Questions quiz = new Questions(); QuestionsHandler Qhan = new QuestionsHandler(quiz); Answers an1 = new Answers(); Answers an2 = new Answers(); Answers an3 = new Answers(); Answers an4 = new Answers(); AnswersHandler Ahan1 = new AnswersHandler(an1); AnswersHandler Ahan2 = new AnswersHandler(an2); AnswersHandler Ahan3 = new AnswersHandler(an3); AnswersHandler Ahan4 = new AnswersHandler(an4); try { quiz.Question = txtQuiz.Text; quiz.CreatorId = MainUI.UserID; quiz.CreatedTime = Int32.Parse(DateTime.Now.ToString("yyyyMMdd")); an1.AnswerId = dgvAnswer.Rows[0].Cells[0].Value.ToString(); an2.AnswerId = dgvAnswer.Rows[1].Cells[0].Value.ToString(); an3.AnswerId = dgvAnswer.Rows[2].Cells[0].Value.ToString(); an4.AnswerId = dgvAnswer.Rows[3].Cells[0].Value.ToString(); an1.Answer = txtAn1.Text; an2.Answer = txtAn2.Text; an3.Answer = txtAn3.Text; an4.Answer = txtAn4.Text; an1.QuestionId = lblQId.Text; an2.QuestionId = lblQId.Text; an3.QuestionId = lblQId.Text; an4.QuestionId = lblQId.Text; if (cbox1.Checked) an1.Correct = true; else an1.Correct = false; if (cbox2.Checked) an2.Correct = true; else an2.Correct = false; if (cbox3.Checked) an3.Correct = true; else an3.Correct = false; if (cbox4.Checked) an4.Correct = true; else an4.Correct = false; if (txtAn1.Text == "" || txtAn2.Text == "" || txtAn3.Text == "" || txtAn4.Text == "" || txtQuiz.Text == "") { throw new CustomException(ErrorInfo.EMPTY); } else if (!cbox1.Checked && !cbox2.Checked && !cbox3.Checked && !cbox4.Checked) { MessageBox.Show("Phải có ít nhất 1 câu trả lời đúng!"); throw new CustomException(ErrorInfo.EMPTY); } Qhan.Update(); Ahan1.Update(); Ahan2.Update(); Ahan3.Update(); Ahan4.Update(); MessageBox.Show("Sửa thành công", "Thông báo", MessageBoxButtons.OK); QuestionControl_Load(sender, e); } catch (CustomException cex) { MessageBox.Show("Lỗi: " + cex.Error.ErrorMessage); } catch (FormatException exx) { MessageBox.Show("Lỗi: Bạn đã nhập sai định dạng, hãy kiểm tra lại"); } catch (Exception ex) { MessageBox.Show("Lỗi: " + ex.Message.ToString()); } } private void btnDelete_Click(object sender, EventArgs e) { Questions quiz = new Questions(); QuestionsHandler Qhan = new QuestionsHandler(quiz); Answers an1 = new Answers(); Answers an2 = new Answers(); Answers an3 = new Answers(); Answers an4 = new Answers(); AnswersHandler Ahan1 = new AnswersHandler(an1); AnswersHandler Ahan2 = new AnswersHandler(an2); AnswersHandler Ahan3 = new AnswersHandler(an3); AnswersHandler Ahan4 = new AnswersHandler(an4); try { quiz.QuestionId = lblQId.Text; an1.AnswerId = dgvAnswer.Rows[0].Cells[0].Value.ToString(); an2.AnswerId = dgvAnswer.Rows[1].Cells[0].Value.ToString(); an3.AnswerId = dgvAnswer.Rows[2].Cells[0].Value.ToString(); an4.AnswerId = dgvAnswer.Rows[3].Cells[0].Value.ToString(); Ahan1.Delete(); Ahan2.Delete(); Ahan3.Delete(); Ahan4.Delete(); Qhan.Delete(); MessageBox.Show("Xóa thành công", "Thông báo", MessageBoxButtons.OK); QuestionControl_Load(sender, e); } catch (CustomException cex) { MessageBox.Show("Lỗi: " + cex.Error.ErrorMessage); } catch (FormatException exx) { MessageBox.Show("Lỗi: Bạn đã nhập sai định dạng, hãy kiểm tra lại"); } catch (Exception ex) { MessageBox.Show("Lỗi: " + ex.Message.ToString()); } } private void btnRefresh_Click(object sender, EventArgs e) { btnAdd.Enabled = true; txtAn1.Text = ""; txtAn2.Text = ""; txtAn3.Text = ""; txtAn4.Text = ""; txtQuiz.Text = ""; cbox1.Checked = false; cbox2.Checked = false; cbox3.Checked = false; cbox4.Checked = false; } } }
using CDSShareLib; using IoTHubReceiver.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IoTHubReceiver.Model { public class EventRuleCatalogEngine { public int EventRuleCatalogId { get; set; } public EventRuleCatalog EventRuleCatalog { get; set; } public Dictionary<string, RuleEngineItem> RuleEngineItems { get; set; } public DateTime LastTriggerTime { get; set; } public bool Triggered { get; set; } } public class RuleEngineItem { public string ElementName { get; set; } public SupportDataTypeEnum DataType { get; set; } public string OrderOperation { get; set; } public bool Result { get; set; } public Func<DynamicMessageElement, bool> Equality { get; set; } public string StringRightValue; public string StringEqualOperation; } public class DynamicMessageElement { public string Name { get; set; } public string StringValue { get; set; } public decimal DecimalValue { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Flyweight.Iinterfaces; namespace Flyweight.Clases { //Clase Fabrica class Factory { //Se utilizo una lista para guardar los objetos private List<Iflyweight> Flyweights = new List<Iflyweight>(); //La variable de apoyo private int conteo = 0; //Propiedad public int Conteo { get => Conteo; set => Conteo = value; } //Metodo adiciona, nos ayudara para adicionar nuevas recetas public int Adiciona (string pNombre) { //verificamos si ya existe bool existe = false; foreach (Iflyweight f in Flyweights) { if (f.ObtenNombre() == pNombre) existe = true; } if (existe) { Console.WriteLine("El objeto ya existe, no se ha adicionado"); return -1; } //Si, si existe creamos una nueva receta else { Recetas miReceta = new Recetas(); miReceta.Nombre(pNombre); Flyweights.Add(miReceta); conteo = Flyweights.Count; return conteo - 1; } } //Se hace un Indexer para facilitar la sintesis del cliente public Iflyweight this[int index] { get { return Flyweights[index]; } } } }
using Flunt.Notifications; using Flunt.Validations; using GameLoanManager.Domain.Enums; namespace GameLoanManager.Domain.ViewModels.Game { public class GameCreateViewModel : Notifiable { public GameCreateViewModel(string name, EGameType type, string description, long idOwner) { this.Name = name; this.Type = type; this.Description = description; this.IdOwner = idOwner; this.Available = true; AddNotifications( new Contract() .Requires() .HasMaxLen(Name, 60, "Name", "O nome deve conter até 60 caracteres") .HasMinLen(Name, 3, "Name", "O nome deve conter pelo menos 3 caracteres") .HasMaxLen(Description, 200, "Description", "A descriçao deve conter até 200 caracteres") ); } public string Name { get; private set; } public EGameType Type { get; private set; } public string Description { get; private set; } public long IdOwner { get; set; } public bool Available { get; private set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Ai { public enum AiDifficulty { Easy, Normal, Hard, } public struct RandomProbability { public RandomProbability(float min, float max) { Min = min; Max = max; } public float Min; public float Max; public float GetRandom() { return Random.Range(Min, Max); } } public class AiDifficultyController : Singleton<AiDifficultyController> { public bool IsInitialized { get; protected set; } public Dictionary<string, float> Probabilities { get; private set; } public Dictionary<string, Vector2> RandomRanges { get; private set; } public Dictionary<string, float> StatusValues { get; private set; } private AiDifficulty difficulty; private Data.AiDifficultyData difficultyData; AiDifficultyController() { Probabilities = new Dictionary<string, float>(); RandomRanges = new Dictionary<string, Vector2>(); StatusValues = new Dictionary<string, float>(); } protected override void Awake() { base.Awake(); } public void Initialize() { if(IsInitialized == true) { return; } difficulty = TeamController.AiDifficulty; difficultyData = Resources.Load<Data.AiDifficultyData>("Data/Ai/AiDifficultyData_" + difficulty.ToString()); difficultyData.Probabilities.GetDatas(Probabilities); difficultyData.RandomRanges.GetDatas(RandomRanges); difficultyData.StatusValues.GetDatas(StatusValues); } public Vector2 GetRawRandomValue(string statusId) { if (RandomRanges.ContainsKey(statusId) == false) { Debug.LogError(string.Format("{0} status not found. Difficulty : {1}", statusId, difficulty.ToString())); return Vector2.zero; } return RandomRanges[statusId]; } public float GetRawProbability(string statusId) { if (Probabilities.ContainsKey(statusId) == false) { Debug.LogError(string.Format("{0} status not found. Difficulty : {1}", statusId, difficulty.ToString())); return 0f; } return Probabilities[statusId]; } public bool IsRandomActivated(string statusId) { if(Probabilities.ContainsKey(statusId) == false) { Debug.LogError(string.Format("{0} status not found. Difficulty : {1}", statusId, difficulty.ToString())); return false; } return Probabilities[statusId] > Random.Range(0f, 0.9999f); // 1f로 하면 1f도 나올 수 있음 : min [inclusive] and max [inclusive] } public float GetRandomRangeValue(string statusId) { if(RandomRanges.ContainsKey(statusId) == false) { Debug.LogError(string.Format("{0} status not found. Difficulty : {1}", statusId, difficulty.ToString())); return 0f; } return Random.Range(RandomRanges[statusId].x, RandomRanges[statusId].y); } public float GetStatusValue(string statusId) { if(StatusValues.ContainsKey(statusId) == false) { Debug.LogError(string.Format("{0} status not found. Difficulty : {1}", statusId, difficulty.ToString())); return 0f; } return StatusValues[statusId]; } } }
using Checkout.Payment.Processor.Domain.Models.Enums; using Checkout.Payment.Processor.Seedwork.Extensions; using MediatR; using System; namespace Checkout.Payment.Processor.Domain.Commands { public class SendBankPaymentCommand : IRequest<ITryResult<SendBankPaymentCommandResponse>> { public string CardNumber { get; set; } public int CardCVV { get; set; } public DateTime ExpiryDate { get; set; } public decimal Amount { get; set; } public CurrencyType CurrencyType { get; set; } public string BankPaymentId { get; set; } public Guid PaymentId { get; set; } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// A Milestone can have many Challenges. Challenges are just extra Objectives that provide a fun way to mix-up play and provide extra rewards. /// </summary> [DataContract] public partial class DestinyMilestonesDestinyPublicMilestoneChallenge : IEquatable<DestinyMilestonesDestinyPublicMilestoneChallenge>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyMilestonesDestinyPublicMilestoneChallenge" /> class. /// </summary> /// <param name="ObjectiveHash">The objective for the Challenge, which should have human-readable data about what needs to be done to accomplish the objective. Use this hash to look up the DestinyObjectiveDefinition..</param> /// <param name="ActivityHash">IF the Objective is related to a specific Activity, this will be that activity&#39;s hash. Use it to look up the DestinyActivityDefinition for additional data to show..</param> public DestinyMilestonesDestinyPublicMilestoneChallenge(uint? ObjectiveHash = default(uint?), uint? ActivityHash = default(uint?)) { this.ObjectiveHash = ObjectiveHash; this.ActivityHash = ActivityHash; } /// <summary> /// The objective for the Challenge, which should have human-readable data about what needs to be done to accomplish the objective. Use this hash to look up the DestinyObjectiveDefinition. /// </summary> /// <value>The objective for the Challenge, which should have human-readable data about what needs to be done to accomplish the objective. Use this hash to look up the DestinyObjectiveDefinition.</value> [DataMember(Name="objectiveHash", EmitDefaultValue=false)] public uint? ObjectiveHash { get; set; } /// <summary> /// IF the Objective is related to a specific Activity, this will be that activity&#39;s hash. Use it to look up the DestinyActivityDefinition for additional data to show. /// </summary> /// <value>IF the Objective is related to a specific Activity, this will be that activity&#39;s hash. Use it to look up the DestinyActivityDefinition for additional data to show.</value> [DataMember(Name="activityHash", EmitDefaultValue=false)] public uint? ActivityHash { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyMilestonesDestinyPublicMilestoneChallenge {\n"); sb.Append(" ObjectiveHash: ").Append(ObjectiveHash).Append("\n"); sb.Append(" ActivityHash: ").Append(ActivityHash).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyMilestonesDestinyPublicMilestoneChallenge); } /// <summary> /// Returns true if DestinyMilestonesDestinyPublicMilestoneChallenge instances are equal /// </summary> /// <param name="input">Instance of DestinyMilestonesDestinyPublicMilestoneChallenge to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyMilestonesDestinyPublicMilestoneChallenge input) { if (input == null) return false; return ( this.ObjectiveHash == input.ObjectiveHash || (this.ObjectiveHash != null && this.ObjectiveHash.Equals(input.ObjectiveHash)) ) && ( this.ActivityHash == input.ActivityHash || (this.ActivityHash != null && this.ActivityHash.Equals(input.ActivityHash)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ObjectiveHash != null) hashCode = hashCode * 59 + this.ObjectiveHash.GetHashCode(); if (this.ActivityHash != null) hashCode = hashCode * 59 + this.ActivityHash.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using workshopWithPOM.Tests; using Xunit; namespace workshopWithPOM { public class CareerTests: BaseTest { private CareerPage page; public CareerTests():base("https://careers.hexacta.com/") { page = new CareerPage(); } [Fact] public void testOpenPageAndClickOnPlanCarreraLink() { page.Link.Click(); //a la pagina le digo dame el objeto Link, y el objeto Link hace el click } } }
using BPiaoBao.AppServices.DataContracts.DomesticTicket.DataObject; using BPiaoBao.AppServices.StationContracts.StationMap; using BPiaoBao.Common; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; namespace BPiaoBao.AppServices.StationContracts.DomesticTicket { /// <summary> /// 内存信息读取-航空公司、平台接口 /// </summary> [ServiceContract] public interface IMemoryService { /// <summary> /// 航空公司-列表读取 /// </summary> /// <returns></returns> [OperationContract] PagedList<BPiaoBao.Common.AirSystem> GetMemoryAirList(int page, int rows); /// <summary> /// 平台接口管理-列表读取 /// </summary> /// <returns></returns> [OperationContract] PagedList<BPiaoBao.Common.PlatSystem> GetMemoryPlatList(int page, int rows); /// <summary> /// 初始化系统全局开关 /// </summary> [OperationContract] void InitSystemSwitchInfo(); /// <summary> /// 航空公司新增 /// </summary> /// <param name="vm"></param> [OperationContract] string AriLineSave(AirLine vm); /// <summary> /// 删除航空公司 /// </summary> /// <param name="CarrayCode"></param> [OperationContract] void DeleteAriLine(int Id); /// <summary> /// 修改航空公司 /// </summary> /// <param name="vm"></param> [OperationContract] string ModiflyAriLine(AirLine vm); /// <summary> /// 获取航空公司信息 /// </summary> /// <param name="Id"></param> /// <returns></returns> [OperationContract] AirLine GetAirLineInfo(int Id); /// <summary> /// 查询航空公司列表 /// </summary> /// <param name="model"></param> /// <param name="page"></param> /// <param name="rows"></param> /// <returns></returns> [OperationContract] PagedList<AirLine> GetAriLineList(AirLine model, int page, int rows); /// <summary> /// 修改航变设置信息 /// </summary> /// <param name="MD"></param> [OperationContract] void SetAirChangTimeOutInfo(string QTStartTime, string QTEndTime, string TimeOut, bool? IsOpen); /// <summary> /// 获取设置航变时间间隔 /// </summary> /// <returns></returns> [OperationContract] QTSetting GetAirChangeTimeOutInfo(); } }
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Project_NotesDeFrais.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Project_NotesDeFrais.Controllers { public class HomeController : Controller { public ActionResult Index() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Here we create a Admin super user who will maintain the website var user = new ApplicationUser(); user.UserName = "admin@admin.com"; user.Email = "admin@admin.com"; string userPWD = "@AZERTY12"; var chkUser = UserManager.Create(user, userPWD); //Add default User to Role Admin if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } if (!roleManager.RoleExists("Comptable")) { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Comptable"; roleManager.Create(role); //Here we create a Admin super user who will maintain the website var user = new ApplicationUser(); user.UserName = "comptable@comptable.com"; user.Email = "comptable@comptable.com"; string userPWD = "@COMPTABLE12"; var chkUser = UserManager.Create(user, userPWD); //Add default User to Role Admin if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Comptable"); } } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data; using ENTITY; using OpenMiracle.DAL; namespace OpenMiracle.BLL { public class StockJournalBll { StockJournalDetailsSP spStockJournalDetails = new StockJournalDetailsSP(); StockJournalMasterSP spStockJournalMaster = new StockJournalMasterSP(); /// <summary> /// Function to delete particular details based on the parameter /// </summary> /// <param name="StockJournalDetailsId"></param> public void StockJournalDetailsDelete(decimal StockJournalDetailsId) { try { spStockJournalDetails.StockJournalDetailsDelete(StockJournalDetailsId); } catch (Exception ex) { MessageBox.Show("AL3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Function to get values based on parameter /// </summary> /// <param name="decVoucherTypeId"></param> /// <param name="strProductCode"></param> /// <returns></returns> public List<DataTable> StockJournalDetailsByProductCode(decimal decVoucherTypeId, string strProductCode) { List<DataTable> listObj = new List<DataTable>(); try { listObj = spStockJournalDetails.StockJournalDetailsByProductCode(decVoucherTypeId, strProductCode); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listObj; } /// <summary> /// Function to get values based on parameter /// </summary> /// <param name="decVoucherTypeId"></param> /// <param name="strProductName"></param> /// <returns></returns> public List<DataTable> StockJournalDetailsByProductName(decimal decVoucherTypeId, string strProductName) { List<DataTable> listObj = new List<DataTable>(); try { listObj = spStockJournalDetails.StockJournalDetailsByProductName(decVoucherTypeId, strProductName); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listObj; } /// <summary> /// Function to get values based on parameter /// </summary> /// <param name="decVoucherTypeId"></param> /// <param name="strBarcode"></param> /// <returns></returns> public List<DataTable> StockJournalDetailsViewByBarcode(decimal decVoucherTypeId, string strBarcode) { List<DataTable> listObj = new List<DataTable>(); try { listObj = spStockJournalDetails.StockJournalDetailsViewByBarcode(decVoucherTypeId, strBarcode); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listObj; } /// <summary> /// Function to insert values to StockJournal Table /// </summary> /// <param name="stockjournaldetailsinfo"></param> public void StockJournalDetailsAdd(StockJournalDetailsInfo stockjournaldetailsinfo) { try { spStockJournalDetails.StockJournalDetailsAdd(stockjournaldetailsinfo); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Function to Update values in StockJournal Table /// </summary> /// <param name="stockjournaldetailsinfo"></param> public void StockJournalDetailsEdit(StockJournalDetailsInfo stockjournaldetailsinfo) { try { spStockJournalDetails.StockJournalDetailsEdit(stockjournaldetailsinfo); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Function to get values based on parameter /// </summary> /// <param name="decMasterId"></param> /// <returns></returns> public DataSet StockJournalDetailsForRegisterOrReport(decimal decMasterId) { DataSet dsData = new DataSet(); try { dsData = spStockJournalDetails.StockJournalDetailsForRegisterOrReport(decMasterId); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return dsData; } /// <summary> /// Function to get values from StockJournal Table based on parameter for register /// </summary> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="voucherNo"></param> /// <returns></returns> public List<DataTable> StockJournalRegisterGrideFill(DateTime fromDate, DateTime toDate, string invoiceNo) { List<DataTable> listObj = new List<DataTable>(); try { listObj = spStockJournalMaster.StockJournalRegisterGrideFill(fromDate, toDate, invoiceNo); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listObj; } /// <summary> /// Function to get values from StockJournal Table based on parameter for Report /// </summary> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="decVoucherTypeId"></param> /// <param name="strVoucherNo"></param> /// <param name="strProductCode"></param> /// <param name="strProductName"></param> /// <returns></returns> public List<DataTable> StockJournalReportGrideFill(DateTime fromDate, DateTime toDate, decimal decVoucherTypeId, string strinvoiceNo, string strProductCode, string strProductName) { List<DataTable> listObj = new List<DataTable>(); try { listObj = spStockJournalMaster.StockJournalReportGrideFill(fromDate, toDate, decVoucherTypeId, strinvoiceNo, strProductCode, strProductName); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listObj; } /// <summary> /// Function for VoucherType ComboFill For StockJournal Report /// </summary> /// <param name="cmbVoucherType"></param> /// <param name="strVoucherType"></param> /// <param name="isAll"></param> public void VoucherTypeComboFillForStockJournalReport(ComboBox cmbVoucherType, string strVoucherType, bool isAll) { try { spStockJournalMaster.VoucherTypeComboFillForStockJournalReport(cmbVoucherType, strVoucherType, isAll); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Function to get the next id from StockJournal Table based on parameter /// </summary> /// <param name="decVoucherTypeId"></param> /// <returns></returns> public decimal StockJournalMasterMaxPlusOne(decimal decVoucherTypeId) { decimal max = 0; try { max = spStockJournalMaster.StockJournalMasterMaxPlusOne(decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return max; } /// <summary> /// Function to get the next id from StockJournal Table based on parameter /// </summary> /// <param name="decVoucherTypeId"></param> /// <returns></returns> public decimal StockJournalMasterMax(decimal decVoucherTypeId) { decimal max = 0; try { max = spStockJournalMaster.StockJournalMasterMax(decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return max; } /// <summary> /// Function for delete stockjournal table values based on parameter /// </summary> /// <param name="decStockJournalMasterId"></param> /// <param name="decVoucherTypeId"></param> /// <param name="strVoucherNo"></param> public void StockJournalDeleteAllTables(decimal decStockJournalMasterId, decimal decVoucherTypeId, string strVoucherNo) { try { spStockJournalMaster.StockJournalDeleteAllTables(decStockJournalMasterId, decVoucherTypeId, strVoucherNo); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Function to insert values to StockJournal Table /// </summary> /// <param name="stockjournalmasterinfo"></param> /// <returns></returns> public decimal StockJournalMasterAdd(StockJournalMasterInfo stockjournalmasterinfo) { decimal decStockJournalMasterId = 0; try { decStockJournalMasterId = spStockJournalMaster.StockJournalMasterAdd(stockjournalmasterinfo); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decStockJournalMasterId; } /// <summary> /// Function to Update values in StockJournal Table /// </summary> /// <param name="stockjournalmasterinfo"></param> public void StockJournalMasterEdit(StockJournalMasterInfo stockjournalmasterinfo) { try { spStockJournalMaster.StockJournalMasterEdit(stockjournalmasterinfo); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Function to check existence of StockJournal InvoiceNumber based on parameters /// </summary> /// <param name="strvoucherNo"></param> /// <param name="decStockMasterId"></param> /// <param name="decVoucherTypeId"></param> /// <returns></returns> public bool StockJournalInvoiceNumberCheckExistence(string strinvoiceNo, decimal decStockMasterId, decimal decVoucherTypeId) { bool isEdit = false; try { isEdit = spStockJournalMaster.StockJournalInvoiceNumberCheckExistence(strinvoiceNo, decStockMasterId, decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return isEdit; } /// <summary> /// Function to fill StockJournalMaster details For Register Or Report based on parameters /// </summary> /// <param name="decMasterId"></param> /// <returns></returns> public List<DataTable> StockJournalMasterFillForRegisterOrReport(decimal decMasterId) { List<DataTable> listObj = new List<DataTable>(); try { listObj = spStockJournalMaster.StockJournalMasterFillForRegisterOrReport(decMasterId); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listObj; } /// <summary> /// Function for StockJournal Printing based on parameter /// </summary> /// <param name="decMasterId"></param> /// <returns></returns> public DataSet StockJournalPrinting(decimal decMasterId) { DataSet dsData = new DataSet(); try { dsData = spStockJournalMaster.StockJournalPrinting(decMasterId); } catch (Exception ex) { MessageBox.Show("AL6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return dsData; } } }
using System; using System.Collections; namespace QuitSmokeWebAPI.Controllers.Entity { public class AuthUser { public string email { get; set; } public string password { get; set; } public bool returnSecureToken { get; set; } } }
using BPiaoBao.SystemSetting.Domain.Services.Auth; using JoveZhao.Framework.Auth; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; namespace BPiaoBao.AppServices { public class AuthManager { private const string key = "fafagjalgjagahgdh"; private const string tokenKey = "aaaaavvvvvcccc"; public static CurrentUserInfo GetCurrentUser() { return CallContext.GetData(key) as CurrentUserInfo; } public static void SaveUser(CurrentUserInfo user) { CallContext.SetData(key, user); } public static List<CurrentUserInfo> GetOnLineUserInfo() { return UserAuthResult<CurrentUserInfo>.FindAll().Select(p => p.UserInfo).ToList(); } public static void SaveToken(string token) { CallContext.SetData(tokenKey, token); } public static string GetToken() { var temp = CallContext.GetData(tokenKey); if (temp == null) return null; return temp.ToString(); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; namespace Pong { class PongGame : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public static Vector2 GameDimensions; public static InputHelper InputHelper; public static GameWorld GameWorld; public static Random Random; static void Main() { PongGame game = new PongGame(); game.Run(); } public PongGame() { Content.RootDirectory = "Content"; graphics = new GraphicsDeviceManager(this); InputHelper = new InputHelper(); Random = new Random(); GameDimensions = new Vector2(graphics.PreferredBackBufferWidth,graphics.PreferredBackBufferHeight); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); GameWorld = new GameWorld(Content); } protected override void Update(GameTime gameTime) { GameWorld.Update(gameTime); InputHelper.Update(); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); GameWorld.Draw(gameTime, spriteBatch); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; public class CNPUBLIC { private static Regex RegNumber = new Regex("^[0-9.]+$"); /// <summary> /// 判断是否为数字 /// </summary> /// <param name="str">传入的字符串</param> /// <returns>返回真假</returns> public static bool IsNumeric(string inputData) { if (inputData == null || inputData.Equals("0")) return false; Match m = RegNumber.Match(inputData); return m.Success; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace AdventOfCode2020 { public class Day05 : IDay { private const string InputFile = "Inputs/input_05.txt"; private const string RowPattern = "^(F|B){7}"; private const string ColPattern = "(L|R){3}$"; private static IEnumerable<int> GetSeatIDs() { return from line in File.ReadLines(InputFile) let rowChars = Regex.Match(line, RowPattern).Value let colChars = Regex.Match(line, ColPattern).Value let row = EvaluateSequence(rowChars, 'F') let col = EvaluateSequence(colChars, 'L') select row * 8 + col; } private static int EvaluateSequence(string sequence, char lower) { int min = 0, max = (int) Math.Pow(2, sequence.Length); foreach (char element in sequence) { int newBound = min + (max - min) / 2; if (element == lower) max = newBound; else min = newBound; } return min; } private static int FindHighestSeatID() => GetSeatIDs().Max(); private static int FindEmptySeatID() { List<int> sortedIDs = GetSeatIDs().ToList(); sortedIDs.Sort(); int previousID = sortedIDs[0]; foreach (int seatID in sortedIDs) { if (previousID < seatID - 1) return seatID - 1; previousID = seatID; } return -1; } public (string resultOne, string resultTwo) GetResults() { int highestSeatID = FindHighestSeatID(); var resultOne = $"The highest seat ID is {highestSeatID}."; int emptySeatID = FindEmptySeatID(); var resultTwo = $"The empty seat ID is {emptySeatID}."; return (resultOne, resultTwo); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Indexer { public static class Bootstrap { private static void Main(string[] args) { Console.ReadLine(); } } }
using LogUrFace.FaceRec.Interfaces; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using LogUrFace.FaceRec.Models; using Luxand; namespace LogUrFace.FaceRec.Services { public class FaceRecRecognizer : IRecognizer { private ILookup<string, FaceTemplate> _faceTemplates; private IFaceRecRepository _faceRepo; const float FARValue = 0.01F; private float _threshold; public FaceRecRecognizer(IFaceRecRepository repo) { _faceRepo = repo; _faceTemplates = _faceRepo.FaceTemplates; FSDK.GetMatchingThresholdAtFAR(FARValue, ref _threshold); } public bool ValidateImage(Image img, string label) { var cimg = new FSDK.CImage(img); var facepos = cimg.DetectFace(); if (facepos.w <= 0) return false; var thisFaceTemplate = cimg.GetFaceTemplateInRegion(ref facepos); if (_faceTemplates.Contains(label) == false) return false; var faceTemplates = _faceTemplates[label]; foreach (var item in faceTemplates) { var faceData = item.Template; float similarity = 0; FSDK.MatchFaces(ref faceData, ref thisFaceTemplate, ref similarity); if (similarity >= _threshold) { return true; } } return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Mono.Data.Sqlite; namespace SQLite { public abstract class AbstractDatabase : IDisposable { const string _COLUMN_ID = "_id"; SqLiteHelper _sqLiteHelper; readonly Dictionary<string, SqlField> _allFields=new Dictionary<string, SqlField>(); protected internal string TableName; public abstract string GetTableName(); public abstract List<SqlField> GetAllFields(); public abstract string GetDatabaseName(); public abstract string GetDatabasePath(); private protected abstract SqlDatabase InitiateSqlDatabase(); private protected abstract List<SqlTable> InitiateSqlTable(); void OpenOrCreate() { if (_sqLiteHelper == null) { _sqLiteHelper=new SqLiteHelper(GetDatabasePath(),GetDatabaseName()); TableName = GetTableName(); List<SqlField> fields = GetAllFields(); bool isExistIdField = false; foreach (var t in fields) { if (string.Equals(t.Name, _COLUMN_ID)) { isExistIdField = true; } _allFields.Add(t.Name,t); } if (!isExistIdField) { //default set integer _id as primary key _allFields.Add(_COLUMN_ID, new SqlField(_COLUMN_ID).SetType(SqlFieldType.Int).SetPrimaryKey(true)); } } if (_sqLiteHelper.IsTableExist(TableName)) return; { SqlStatement sqlStatement=new SqlStatement(TableName); foreach (var t in _allFields) { sqlStatement.CreateFields(t.Value); } SqliteDataReader reader = _sqLiteHelper.CreateTable(sqlStatement); _sqLiteHelper.CloseReader(reader); } } public void Dispose() { if (_sqLiteHelper == null) return; _sqLiteHelper.CloseDatabaseConnection(); _sqLiteHelper = null; } #region insert public void Insert(params SqlField[] fields) { if (IsEmpty(fields)) { return; } OpenOrCreate(); SqliteDataReader reader = _sqLiteHelper.InsertData(TableName, fields); _sqLiteHelper.CloseReader(reader); } #endregion #region delete public void DeleteTable(bool isDrop = false) { OpenOrCreate(); SqliteDataReader reader = _sqLiteHelper.DeleteTable(TableName, isDrop); _sqLiteHelper.CloseReader(reader); } public void Delete(SqlStatement sqlStatement) { if (sqlStatement == null) return; OpenOrCreate(); SqliteDataReader reader = _sqLiteHelper.DeleteData(sqlStatement); _sqLiteHelper.CloseReader(reader); } /// <summary> /// select the field which to drop /// </summary> /// <param name="field"></param> /// <param name="operation"></param> public void Delete(SqlField field, SqlOperation operation = SqlOperation.Equal) { if (field == null) { return; } SqlStatement sqlStatement=new SqlStatement(GetTableName()); sqlStatement.AddConditions(operation, SqlUnion.None, field); Delete(sqlStatement); } public void Delete(SqlField[] fields, SqlUnion union, SqlOperation operation = SqlOperation.Equal) { if (fields == null) return; SqlStatement sqlStatement=new SqlStatement(GetTableName()); sqlStatement.AddConditions(operation, union, fields); Delete(sqlStatement); } #endregion #region update public void Update(SqlStatement sqlStatement) { if (sqlStatement == null) return; OpenOrCreate(); SqliteDataReader reader = _sqLiteHelper.UpdateData(sqlStatement); _sqLiteHelper.CloseReader(reader); } public void Update(SqlField[] fields, SqlUnion union, SqlOperation operation, params SqlField[] conditionFields) { if ((fields == null || fields.Length <= 0) || IsEmpty(conditionFields)) { return; } SqlStatement sqlStatement=new SqlStatement(GetTableName()); sqlStatement.UpdateFields(fields).AddConditions(operation, union, conditionFields); Update(sqlStatement); } public void Update(SqlField[] fields, SqlUnion union, params SqlField[] conditionFields) { Update(fields,union,SqlOperation.Equal,conditionFields); } public void Update(SqlField[] fields, SqlField conditionField) { Update(fields,SqlUnion.None,SqlOperation.Equal,conditionField); } public void Update(SqlField field, SqlUnion union, SqlOperation operation, params SqlField[] conditionFields) { Update(new SqlField[]{field},union,operation,conditionFields); } public void Update(SqlField field, SqlField conditionField) { Update(field,SqlUnion.None,SqlOperation.Equal,conditionField); } #endregion #region select public List<SqlField[]> Select(SqlStatement sqlStatement) { String[] fieldNames = sqlStatement?.GetSelectFieldArray(); if (fieldNames == null || fieldNames.Length <= 0) return null; OpenOrCreate(); List<SqlField[]> result=new List<SqlField[]>(); SqliteDataReader reader = _sqLiteHelper.SelectData(sqlStatement); if (reader.HasRows) { while (reader.Read()) { SqlField[] resultFields=new SqlField[fieldNames.Length]; for(int i=0;i<fieldNames.Length;i++) { string fieldName = fieldNames[i].Trim(); int ordinal = reader.GetOrdinal(fieldName); if (reader.IsDBNull(ordinal)) { resultFields[i]=new SqlField(fieldName); } else { SqlFieldType fieldType = _allFields[fieldName].Type; switch (fieldType) { case SqlFieldType.Binary: resultFields[i]=new SqlField(fieldName).SetValue(BinaryTools.BytesToString( (byte[])reader.GetValue(ordinal) )); break; case SqlFieldType.Float: resultFields[i]=new SqlField(fieldName).SetValue(Convert.ToString(reader.GetFloat(ordinal), CultureInfo.CurrentCulture)); break; case SqlFieldType.Int: resultFields[i]=new SqlField(fieldName).SetValue(Convert.ToString(reader.GetInt32(ordinal))); break; case SqlFieldType.Long: resultFields[i]=new SqlField(fieldName).SetValue(Convert.ToString(reader.GetInt64(ordinal))); break; case SqlFieldType.Text: resultFields[i]=new SqlField(fieldName).SetValue(reader.GetString(ordinal)); break; default: resultFields[i]=new SqlField(fieldName); break; } resultFields[i].SetType(fieldType); } } result.Add(resultFields); } } _sqLiteHelper.CloseReader(reader); return result; } public List<SqlField[]> Select(string[] fieldNames, SqlUnion union, SqlOperation operation, params SqlField[] conditionFields) { if (fieldNames == null || fieldNames.Length <= 0) { return null; } SqlStatement sqlStatement=new SqlStatement(GetTableName()); sqlStatement.SelectFields(fieldNames); if (!IsEmpty(conditionFields)) { sqlStatement.AddConditions(operation, union, conditionFields); } return Select(sqlStatement); } public List<SqlField[]> Select(string[] fieldNames,SqlUnion union,params SqlField[] conditionFields) { return Select(fieldNames, union, SqlOperation.Equal, conditionFields); } public List<SqlField[]> Select(string[] fieldNames, SqlField conditionField) { return Select(fieldNames,SqlUnion.None,SqlOperation.Equal,conditionField); } public List<SqlField[]> Select(string fieldName, SqlUnion union, SqlOperation operation, params SqlField[] conditionFields) { return Select(new string[]{ fieldName },union,operation,conditionFields); } public List<SqlField[]> Select(string fieldName, SqlUnion union, params SqlField[] conditionFields) { return Select(fieldName, union, SqlOperation.Equal, conditionFields); } public List<SqlField[]> Select(string fieldName, SqlField conditionField) { return Select(fieldName, SqlUnion.None, SqlOperation.Equal, conditionField); } public bool Select(SqlField field) { if (field == null) return false; OpenOrCreate(); return _sqLiteHelper.SelectData(TableName, field); } #endregion public bool IsTableExist() { OpenOrCreate(); return _sqLiteHelper.IsTableExist(TableName); } public bool IsFieldExist(string fieldName) { if (string.IsNullOrEmpty(fieldName)) { return false; } OpenOrCreate(); return _sqLiteHelper.IsFieldExist(TableName, fieldName); } static bool IsEmpty(ICollection collection) { if (collection == null || collection.Count <= 0) return true; IEnumerator e = collection.GetEnumerator(); while (e.MoveNext()) { var obj = e.Current; if (obj != null) { return false; } } return true; } } }
using System; using System.Linq; using System.Text; using System.Windows; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using VMS.TPS.Common.Model.API; using VMS.TPS.Common.Model.Types; // TODO: Replace the following version attributes by creating AssemblyInfo.cs. You can do this in the properties of the Visual Studio project. [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")] [assembly: AssemblyInformationalVersion("1.0")] // TODO: Uncomment the following line if the script requires write access. [assembly: ESAPIScript(IsWriteable = true)] namespace VMS.TPS { public class Script { const string SCRIPT_NAME = "convertIsodosesToStructures"; public Script() { } [MethodImpl(MethodImplOptions.NoInlining)] public void Execute(ScriptContext context /*, System.Windows.Window window, ScriptEnvironment environment*/) { // TODO : Add here the code that is called when the script is launched from Eclipse. if (context.PlanSetup == null) { MessageBox.Show("Please load a plan before running this script.", SCRIPT_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } if (context.PlanSetup.Dose == null) { MessageBox.Show("Please complete dose calculation before running this script.", SCRIPT_NAME, MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } StructureSet ss = context.StructureSet; Dose dose = context.PlanSetup.Dose; string logtext = ""; // enable writing with this script. context.Patient.BeginModifications(); foreach (Isodose isodose in context.PlanSetup.Dose.Isodoses) { string isoStructureName = ""; isoStructureName = context.PlanSetup.Id + "_" + string.Format("{0:f3}", Math.Round(context.PlanSetup.TotalDose.Dose * isodose.Level.Dose / 100.0, 3)) + "Gy"; //isoStructureName = context.PlanSetup.Id + "_" + isodose.Level.ValueAsString + isodose.Level.UnitAsString; int nameLength = isoStructureName.Length; string isoStructureId = ""; if (isoStructureName.Length > 16) { isoStructureId = isoStructureName.Substring(0, 16); } else { isoStructureId = isoStructureName; } if (ss.CanAddStructure("DOSE_REGION", isoStructureId) == true) { Structure newIsoStructure = ss.Structures.FirstOrDefault(x => x.Id == isoStructureId); if (newIsoStructure == null) { newIsoStructure = ss.AddStructure("DOSE_REGION", isoStructureId); } newIsoStructure.ConvertDoseLevelToStructure(dose, isodose.Level); logtext += isoStructureName + "\n"; } } MessageBox.Show(logtext + "\nDone.", SCRIPT_NAME); } } }
using System; using System.Collections.Generic; using System.Text; namespace Prb.Boekenkast.Core { public class Auteur { public string Auteur_ID { get; set; } public string Naam { get; set; } public string Land { get; set; } public Auteur(string naam, string land) { Auteur_ID = Guid.NewGuid().ToString(); Naam = naam; Land = land; } public override string ToString() { return Naam; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BuildingDoor : MonoBehaviour { [SerializeField] private GameObject door_lock; private bool is_locked; private void Start() { door_lock.SetActive(false); } public void LockDoor() { door_lock.GetComponent<SpriteRenderer>().flipX = true; door_lock.SetActive(true); is_locked = true; } public void UnlockDoor() { door_lock.SetActive(false); is_locked = false; } public bool IsDoorLocked() { return is_locked; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; using Blo; namespace Blo.Seguridad { public interface ISucursalBlo : IGenericBlo<Sucursal> { /// <summary> /// Metodo que permite obtener todas las agencias por empresa /// </summary> /// <param name="idEmpresa">Código de empresa</param> /// <returns>Lista de sucursales</returns> List<Sucursal> GetSucursalxEmpresa(long idEmpresa); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BlockManager : MonoBehaviour { public int BlockLife; [SerializeField] private TextMesh CurrentLives; //Triangle Control [SerializeField] private Sprite[] Colors; [SerializeField] private bool istriangle; [SerializeField] private bool isGolded; [SerializeField] private float[] RotateDegrees; void Start() { BlockLife = GameObject.Find("GameLeader").GetComponent<LevelManager>().GameRound; this.GetComponentInChildren<TextMesh>().text = "" + BlockLife; this.GetComponent<SpriteRenderer>().sprite = Colors[Random.Range(0, 3)]; } void Update () { if(BlockLife < 1) { Death(); } if(this.gameObject.transform.position.y < -4.669) { GameObject.Find("GameLeader").GetComponent<LevelManager>().GameOver(); } } public void DecreaseLife() { BlockLife -= 1; this.gameObject.GetComponentInChildren<TextMesh>().text = "" + BlockLife; } void Death() { if (isGolded) { GameObject.Find("GoldenAmount").GetComponent<Text>().text = "" + 1; } Destroy(this.gameObject); } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using RealEstate.BusinessObjects; using RealEstate.DataAccess; namespace RealEstate.BusinessLogic { public class MenusBL { #region ***** Init Methods ***** MenusDA objMenusDA; public MenusBL() { objMenusDA = new MenusDA(); } #endregion #region ***** Get Methods ***** /// <summary> /// Get Menus by menuid /// </summary> /// <param name="menuid">MenuID</param> /// <returns>Menus</returns> public Menus GetByMenuID(int menuid) { return objMenusDA.GetByMenuID(menuid); } /// <summary> /// Get all of Menus /// </summary> /// <returns>List<<Menus>></returns> public List<Menus> GetList() { string cacheName = "lstMenus"; if( ServerCache.Get(cacheName) == null ) { ServerCache.Insert(cacheName, objMenusDA.GetList(), "Menus"); } return (List<Menus>) ServerCache.Get(cacheName); } /// <summary> /// Get DataSet of Menus /// </summary> /// <returns>DataSet</returns> public DataSet GetDataSet() { string cacheName = "dsMenus"; if( ServerCache.Get(cacheName) == null ) { ServerCache.Insert(cacheName, objMenusDA.GetDataSet(), "Menus"); } return (DataSet) ServerCache.Get(cacheName); } /// <summary> /// Get all of Menus paged /// </summary> /// <param name="recperpage">recperpage</param> /// <param name="pageindex">pageindex</param> /// <returns>List<<Menus>></returns> public List<Menus> GetListPaged(int recperpage, int pageindex) { return objMenusDA.GetListPaged(recperpage, pageindex); } /// <summary> /// Get DataSet of Menus paged /// </summary> /// <param name="recperpage">recperpage</param> /// <param name="pageindex">pageindex</param> /// <returns>DataSet</returns> public DataSet GetDataSetPaged(int recperpage, int pageindex) { return objMenusDA.GetDataSetPaged(recperpage, pageindex); } #endregion #region ***** Add Update Delete Methods ***** /// <summary> /// Add a new Menus within Menus database table /// </summary> /// <param name="obj_menus">Menus</param> /// <returns>key of table</returns> public int Add(Menus obj_menus) { ServerCache.Remove("Menus", true); return objMenusDA.Add(obj_menus); } /// <summary> /// updates the specified Menus /// </summary> /// <param name="obj_menus">Menus</param> /// <returns></returns> public void Update(Menus obj_menus) { ServerCache.Remove("Menus", true); objMenusDA.Update(obj_menus); } /// <summary> /// Delete the specified Menus /// </summary> /// <param name="menuid">MenuID</param> /// <returns></returns> public void Delete(int menuid) { ServerCache.Remove("Menus", true); objMenusDA.Delete(menuid); } #endregion } }
using PyFarmaceutica.acceso_a_datos.interfaces; using PyFarmaceutica.dominio; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PyFarmaceutica.acceso_a_datos.implementaciones { class FacturaDao : IFacturaDao { public bool Alta(Factura oFactura) { SqlTransaction t=null; bool resultado = true; SqlConnection cnn = new SqlConnection(); try { cnn.ConnectionString = @"Data Source=DESKTOP-AOE3FOR\SQLEXPRESS;Initial Catalog = db_farmaceutica2;Integrated Security=True"; cnn.Open(); t = cnn.BeginTransaction(); SqlCommand cmdM = new SqlCommand("PA_INSERTAR_FACTURA", cnn,t); cmdM.CommandType = CommandType.StoredProcedure; cmdM.Parameters.AddWithValue("@nro", oFactura.NroFactura); cmdM.Parameters.AddWithValue("@fecha_emision", oFactura.FechaEmision); cmdM.Parameters.AddWithValue("@formaPago", oFactura.MedioPago); cmdM.Parameters.AddWithValue("@cliente", oFactura.Cliente); cmdM.Parameters.AddWithValue("@obraSocial", oFactura.ObraSocial); cmdM.Parameters.AddWithValue("@sucursal", oFactura.Sucursal); cmdM.ExecuteNonQuery(); int nro =oFactura.NroFactura; int cDetalles = 0; foreach (DetalleFactura det in oFactura.Detalles) { SqlCommand cmdDet = new SqlCommand("PA_INSERTAR_DETALLES_FACTURA", cnn,t); cmdDet.CommandType = CommandType.StoredProcedure; cmdDet.Parameters.AddWithValue("@nro", nro); cmdDet.Parameters.AddWithValue("@detalle", cDetalles); cmdDet.Parameters.AddWithValue("@idSuministro", det.Suministro.IdSuministro); cmdDet.Parameters.AddWithValue("@cobertura", det.Cobertura); cmdDet.Parameters.AddWithValue("@precio", det.Suministro.Precio); cmdDet.Parameters.AddWithValue("@cantidad", det.Cantidad); cmdDet.ExecuteNonQuery(); cDetalles++; } t.Commit(); } catch (Exception) { t.Rollback(); resultado = false; } finally { if (cnn != null && cnn.State == ConnectionState.Open) { cnn.Close(); } } return resultado; } public Factura ObtenerFtxId(int nro) { throw new NotImplementedException(); } public DataTable ObtenerMediosPago() { DataTable table; try { SqlConnection cnn = new SqlConnection(); cnn.ConnectionString = @"Data Source=DESKTOP-AOE3FOR\SQLEXPRESS;Initial Catalog = db_farmaceutica2;Integrated Security=True"; cnn.Open(); SqlCommand cmd = new SqlCommand("PA_CONSULTAR_MEDIOS_DE_PAGO", cnn); cmd.CommandType = CommandType.StoredProcedure; table = new DataTable(); table.Load(cmd.ExecuteReader()); cnn.Close(); } catch (Exception) { table = null; } return table; } public DataTable ObtenerObrasSociales() { DataTable table; try { SqlConnection cnn = new SqlConnection(); cnn.ConnectionString = @"Data Source=DESKTOP-AOE3FOR\SQLEXPRESS;Initial Catalog = db_farmaceutica2;Integrated Security=True"; cnn.Open(); SqlCommand cmd = new SqlCommand("PA_CONSULTAR_OBRA_SOCIAL", cnn); cmd.CommandType = CommandType.StoredProcedure; table = new DataTable(); table.Load(cmd.ExecuteReader()); cnn.Close(); } catch (Exception) { table = null; } return table; } public DataTable ObtenerSucursales() { DataTable table; try { SqlConnection cnn = new SqlConnection(); cnn.ConnectionString = @"Data Source=DESKTOP-AOE3FOR\SQLEXPRESS;Initial Catalog = db_farmaceutica2;Integrated Security=True"; cnn.Open(); SqlCommand cmd = new SqlCommand("PA_CONSULTAR_SUCURSAL", cnn); cmd.CommandType = CommandType.StoredProcedure; table = new DataTable(); table.Load(cmd.ExecuteReader()); cnn.Close(); } catch (Exception) { table = null; } return table; } public DataTable ObtenerSuministros() { DataTable table; try { SqlConnection cnn = new SqlConnection(); cnn.ConnectionString = @"Data Source=DESKTOP-AOE3FOR\SQLEXPRESS;Initial Catalog = db_farmaceutica2;Integrated Security=True"; cnn.Open(); SqlCommand cmd = new SqlCommand("PA_CONSULTAR_SUMINISTROS", cnn); cmd.CommandType = CommandType.StoredProcedure; table = new DataTable(); table.Load(cmd.ExecuteReader()); cnn.Close(); } catch (Exception) { table = null; } return table; } public int ProximaFactura() { int nro = 0; try { SqlConnection cnn = new SqlConnection(); cnn.ConnectionString = @"Data Source=DESKTOP-AOE3FOR\SQLEXPRESS;Initial Catalog = db_farmaceutica2;Integrated Security=True"; cnn.Open(); SqlCommand cmd = new SqlCommand("PA_PROXIMA_FACTURA", cnn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = new SqlParameter("@next", SqlDbType.Int); param.Direction = ParameterDirection.Output; cmd.Parameters.Add(param); cmd.ExecuteNonQuery(); nro = Convert.ToInt32(param.Value); cnn.Close(); } catch (Exception) { MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return nro; } } }
// Copyright (c) 2007 - Dave Kerr // http://www.dopecode.co.uk // // // This file is part of SharpGL. // // SharpGL is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // SharpGL is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // // If you are using this code for commerical purposes then you MUST // purchase a license. See http://www.dopecode.co.uk for details. // This is fairly new code and is immature. The new revision will have custom particles // such as water drops and sparks, and more developed systems, and the system will // be able to generate particles of different types. // A few words are needed to correctly describe this class. In a particle system, // a set of particles will be made. Each particle will be initialised with a call // to Initialise(). Use this function to make each particle random. When the particle // needs to move on a step, Tick() is called. Make sure the code is random, otherwise // all particles will have the same behaviour. using System; using System.Collections; using SharpGL.SceneGraph.Collections; namespace SharpGL.SceneGraph.ParticleSystems { /// <summary> /// A particle system is, you guessed it, just a collection of particles. /// </summary> [Serializable()] public class ParticleSystem : SceneObject { /// <summary> /// This function should create and initialise 'count' particles of the correct /// type. This is done automatically by default, only override if you want /// to change the standard behaviour. /// </summary> /// <param name="count"></param> public virtual void Initialise(int count) { // Get rid of any old particles. particles.Clear(); // Add the particles. for(int i=0; i<count; i++) { // Create a particle. Particle particle = new BasicParticle(); // Initialise it. particle.Intialise(rand); // Add it. particles.Add(particle); } } /// <summary> /// This function draws the particle system. Override from it if you want /// to add custom drawing for particles. /// </summary> /// <param name="gl"></param> public override void Draw(OpenGL gl) { if(DoPreDraw(gl)) { // Disable lighting. SharpGL.SceneGraph.Attributes.Lighting light = new SharpGL.SceneGraph.Attributes.Lighting(); light.Enable = false; light.Set(gl); foreach(Particle p in particles) p.Draw(gl); light.Restore(gl); DoPostDraw(gl); } } /// <summary> /// This function ticks the particle system. /// </summary> public virtual void Tick() { foreach(Particle p in particles) { // Tick the particle. p.Tick(rand); } } protected Random rand = new Random(); public ParticleCollection particles = new ParticleCollection(); protected Type particleType = typeof(ParticleSystems.BasicParticle); } }
using System; using System.Collections.Generic; using System.Text; namespace NullableTypes { public class Major { public int Id { get; set; } public string Description { get; set; } public int MinSAT { get; set; } //Constructor public Major(int id, string description, int minsat) { Description = description; Id = id; MinSAT = minsat; } //Method public void Print() { Console.WriteLine($" Id={Id},Desc = {Description}, Min= {MinSAT}"); } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace NetFabric.Hyperlinq { public static partial class ReadOnlyListExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TList, TSource>(this TList source) where TList : IReadOnlyList<TSource> => source.Count is not 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool Any<TList, TSource>(this TList source, int offset, int count) where TList : IReadOnlyList<TSource> { var (_, take) = Utils.SkipTake(source.Count, offset, count); return take is not 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TList, TSource>(this TList source, Func<TSource, bool> predicate) where TList : IReadOnlyList<TSource> => source.Any<TList, TSource, FunctionWrapper<TSource, bool>>(new FunctionWrapper<TSource, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TList, TSource, TPredicate>(this TList source, TPredicate predicate = default) where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, bool> => source.Any<TList, TSource, TPredicate>(predicate, 0, source.Count); static bool Any<TList, TSource, TPredicate>(this TList source, TPredicate predicate, int offset, int count) where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, bool> { var end = offset + count; for (var index = offset; index < end; index++) { var item = source[index]; if (predicate.Invoke(item)) return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Any<TList, TSource>(this TList source, Func<TSource, int, bool> predicate) where TList : IReadOnlyList<TSource> => source.AnyAt<TList, TSource, FunctionWrapper<TSource, int, bool>>(new FunctionWrapper<TSource, int, bool>(predicate)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AnyAt<TList, TSource, TPredicate>(this TList source, TPredicate predicate = default) where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, int, bool> => source.AnyAt<TList, TSource, TPredicate>(predicate, 0, source.Count); static bool AnyAt<TList, TSource, TPredicate>(this TList source, TPredicate predicate, int offset, int count) where TList : IReadOnlyList<TSource> where TPredicate : struct, IFunction<TSource, int, bool> { var end = count; if (offset is 0) { for (var index = 0; index < end; index++) { var item = source[index]; if (predicate.Invoke(item, index)) return true; } } else { for (var index = 0; index < end; index++) { var item = source[index + offset]; if (predicate.Invoke(item, index)) return true; } } return false; } } }
using PlatformRacing3.Common.Customization; namespace PlatformRacing3.Common.Extensions; public static class HatExtensions { public static bool IsStaffOnly(this Hat hat) { return hat switch { Hat.Cowboy or Hat.Crown or Hat.Extraterrestrial or Hat.Alien => true, _ => false, }; } }
using Plossum.CommandLine; namespace SourceCopyrightEnforcer { [CommandLineManager( ApplicationName = "copyright", Copyright = "Copyright 2013 EventBooking.com, LLC" )] internal class Options { [CommandLineOption( Description = "Displays this help text" )] public bool Help; [CommandLineOption( Description = "Root path of the project" )] public string Path; } }
using QLTTHT.DAO; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QLTTHT { public partial class fMain : Form { public fMain() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if(TaiKhoanDAO.Instance.MaQuyen == 2) { fTeacher f = new fTeacher(); this.Hide(); f.ShowDialog(); this.Show(); } else { MessageBox.Show("Bạn không có quyền truy cập chức năng này!"); } } private void button2_Click(object sender, EventArgs e) { fClass f = new fClass(); this.Hide(); f.ShowDialog(); this.Show(); } private void button3_Click(object sender, EventArgs e) { if (TaiKhoanDAO.Instance.MaQuyen == 2) { fStudent f = new fStudent(); this.Hide(); f.ShowDialog(); this.Show(); } else { MessageBox.Show("Bạn không có quyền truy cập chức năng này!"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MarketManger : MonoBehaviour { public static MarketManger I; void Awake() { I = this; } [SerializeField] GameObject GroundEleBtn; [SerializeField] Transform Content; void Start() { //gen market for (int i = 0; i <= World.EduLev; i++) { var eles = Resources.LoadAll<GameObject>("Prefs/GroundEles/0"); for (int e = 0; e < eles.Length; e++) { var newBtn = Instantiate(GroundEleBtn, Content).GetComponent<GroundEleBtn>(); var building = eles[e].GetComponent<Building>(); newBtn.Go = eles[e]; newBtn.NameText.text = eles[e].name; for (int t = 0; t < building.RequirdMats.Length; t++) { newBtn.RequiredMatsText.text += building.RequirdMats[t].Kind.ToString() + " " + building.RequirdMats[t].Count.ToString() + '\n'; } newBtn.RequiredMatsText.text += "required humans: " + building.RequirdHumans; building.EduLev = 0; } } } void OnNewEduLevel() { } static GameObject ChoosenObj, HeldObj; //the pref //the actual instance static Coroutine CurrentPutCor; public static IEnumerator PutBuilding() { if (HeldObj != null) Destroy(HeldObj); var newBuilding = Instantiate(ChoosenObj); HeldObj = newBuilding; Transform lastSurface = null; while (true) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (World.IsMouseNotOverUI() && Physics.Raycast(ray, out hit, 999, World.TerLayers)) { if (hit.transform.parent != lastSurface) { lastSurface = hit.transform.parent; newBuilding.transform.SetParent(hit.transform.parent); }//if parent changed newBuilding.transform.localEulerAngles = Vector3.zero; newBuilding.transform.position = hit.point + (hit.transform.up * .05f); if (newBuilding.GetComponent<Building>().CollidersCount == 0) { var extends = newBuilding.GetComponent<MeshFilter>().mesh.bounds.extents; var poz = newBuilding.transform.position; var buttomPoints = new Vector3[] { (newBuilding.transform.right * -extends.x)+(newBuilding.transform.forward * -extends.z) + poz, (newBuilding.transform.right * -extends.x)+(newBuilding.transform.forward * extends.z) + poz, (newBuilding.transform.right * extends.x)+(newBuilding.transform.forward * -extends.z) + poz, (newBuilding.transform.right * extends.x)+(newBuilding.transform.forward * extends.z) + poz, }; var grounded = true; for (int i = 0; i < 4; i++) { if (Physics.Raycast(buttomPoints[i], -newBuilding.transform.up, .1f) == false) { grounded = false; break; } } //check if mesh is fully grounded if (grounded) { newBuilding.GetComponent<Renderer>().material.color = Color.white; if (Input.GetMouseButtonDown(0)) { if (newBuilding.GetComponent<Building>().ConstructIfPossible()) HeldObj = null; yield break; } } else { newBuilding.GetComponent<Renderer>().material.color = Color.blue; } } else { newBuilding.GetComponent<Renderer>().material.color = Color.blue; } } yield return new WaitForFixedUpdate(); } } public static void SelectBuilding(GameObject choosen) { ChoosenObj = choosen; if (CurrentPutCor != null) I.StopCoroutine(CurrentPutCor); CurrentPutCor = I.StartCoroutine(PutBuilding()); } public void DestroyHeld() { Destroy(HeldObj); } }
using System; using System.Collections.Generic; using System.Text; using TanoApp.Data.Entities; using TanoApp.Infrastructure.Interfaces; namespace TanoApp.Data.IRepositories { public interface ITagRepository: IRepository<Tag, string> { } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.IO; using System.Reflection; using System.Diagnostics; using System.Runtime.Serialization; namespace ArchsimLib { /// <summary> /// Library that holds all materials, constructions and schedules during runtime. /// </summary> [DataContract] public class Library { #region Add Low Level Objects public OpaqueConstruction Add(OpaqueConstruction obj) { if (obj == null) return null; if (!OpaqueConstructions.Any(i => i.Name == obj.Name)) { //try //{ // foreach (var o in obj.Layers.Select(a => a.Material)) this.Add(o); //} //catch (Exception ex) { } OpaqueConstructions.Add(obj); return obj; } else { var oc = OpaqueConstructions.Single(o => o.Name == obj.Name); //try //{ // if (oc != null) // { // foreach (var o in obj.Layers.Select(a => a.Material)) this.Add(o); // } //} //catch (Exception ex) { } CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public GlazingConstruction Add(GlazingConstruction obj) { if (obj == null) return null; if (!GlazingConstructions.Any(i => i.Name == obj.Name)) { //try //{ // foreach (var o in obj.Layers.Select(a => a.GlassMaterial)) this.Add(o); //} //catch (Exception ex) { } GlazingConstructions.Add(obj); return obj; } else { var oc = GlazingConstructions.Single(o => o.Name == obj.Name); //try //{ // if (oc != null) // { // foreach (var o in obj.Layers.Select(a => a.GlassMaterial)) this.Add(o); // } //} //catch (Exception ex) { } CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); //foreach (var l in obj.Layers.Select(o => o.GlassMaterial)) Add(l); return oc; } } public OpaqueMaterial Add(OpaqueMaterial obj) { if (obj == null) return null; if (!OpaqueMaterials.Any(i => i.Name == obj.Name)) { OpaqueMaterials.Add(obj); return obj; } else { var oc = OpaqueMaterials.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public GlazingMaterial Add(GlazingMaterial obj) { if (obj == null) return null; if (!GlazingMaterials.Any(i => i.Name == obj.Name)) { GlazingMaterials.Add(obj); return obj; } else { var oc = GlazingMaterials.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public GlazingConstructionSimple Add(GlazingConstructionSimple obj) { if (obj == null) return null; if (!GlazingConstructionsSimple.Any(i => i.Name == obj.Name)) { GlazingConstructionsSimple.Add(obj); return obj; } else { var oc = GlazingConstructionsSimple.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public GasMaterial Add(GasMaterial obj) { if (obj == null) return null; if (!GasMaterials.Any(i => i.Name == obj.Name)) { GasMaterials.Add(obj); return obj; } else { var oc = GasMaterials.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public DaySchedule Add(DaySchedule obj) { if (obj == null) return null; if (!DaySchedules.Any(i => i.Name == obj.Name)) { DaySchedules.Add(obj); return obj; } else { var oc = DaySchedules.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public WeekSchedule Add(WeekSchedule obj) { if (obj == null) return null; if (!WeekSchedules.Any(i => i.Name == obj.Name)) { //try //{ // foreach (var o in obj.Days.Select(a => a)) this.Add(o); //} //catch (Exception ex) { } WeekSchedules.Add(obj); //foreach (var dsched in obj.Days) Add(dsched); return obj; } else { var oc = WeekSchedules.Single(o => o.Name == obj.Name); //try //{ // if (oc != null) // { // foreach (var o in obj.Days.Select(a => a)) this.Add(o); // } //} //catch (Exception ex) { } CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); //foreach (var dsched in obj.Days) Add(dsched); return oc; } } public YearSchedule Add(YearSchedule obj) { if (obj == null) return null; if (!YearSchedules.Any(i => i.Name == obj.Name)) { //try //{ // foreach (var o in obj.WeekSchedules.Select(a => a)) this.Add(o); //} //catch (Exception ex) { } YearSchedules.Add(obj); //foreach (var ws in obj.WeekSchedules) Add(ws); return obj; } else { var oc = YearSchedules.Single(o => o.Name == obj.Name); //try //{ // if (oc != null) // { // foreach (var o in obj.WeekSchedules.Select(a => a)) this.Add(o); // } //} //catch (Exception ex) { } CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); //foreach (var ws in obj.WeekSchedules) Add(ws); return oc; } } public ScheduleArray Add(ScheduleArray obj) { if (obj == null) return null; if (!ArraySchedules.Any(i => i.Name == obj.Name)) { ArraySchedules.Add(obj); return obj; } else { var oc = ArraySchedules.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } #endregion #region Add High Level Objects public ZoneLoad Add(ZoneLoad obj) { if (obj == null) return null; if (!ZoneLoads.Any(i => i.Name == obj.Name)) { ZoneLoads.Add(obj); return obj; } else { var oc = ZoneLoads.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public ZoneVentilation Add(ZoneVentilation obj) { if (obj == null) return null; if (!ZoneVentilations.Any(i => i.Name == obj.Name)) { ZoneVentilations.Add(obj); return obj; } else { var oc = ZoneVentilations.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public ZoneConstruction Add(ZoneConstruction obj) { if (obj == null) return null; if (!ZoneConstructions.Any(i => i.Name == obj.Name)) { ZoneConstructions.Add(obj); return obj; } else { var oc = ZoneConstructions.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public ZoneConditioning Add(ZoneConditioning obj) { if (obj == null) return null; if (!ZoneConditionings.Any(i => i.Name == obj.Name)) { ZoneConditionings.Add(obj); return obj; } else { var oc = ZoneConditionings.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public DomHotWater Add(DomHotWater obj) { if (obj == null) return null; if (!DomHotWaters.Any(i => i.Name == obj.Name)) { DomHotWaters.Add(obj); return obj; } else { var oc = DomHotWaters.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public ZoneDefinition Add(ZoneDefinition obj) { if (obj == null) return null; if (!ZoneDefinitions.Any(i => i.Name == obj.Name)) { ZoneDefinitions.Add(obj); return obj; } else { var oc = ZoneDefinitions.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } public WindowSettings Add(WindowSettings obj) { if (obj == null) return null; if (!WindowSettings.Any(i => i.Name == obj.Name)) { WindowSettings.Add(obj); return obj; } else { var oc = WindowSettings.Single(o => o.Name == obj.Name); CopyObjectData(obj, oc, "", BindingFlags.Public | BindingFlags.Instance); return oc; } } #endregion public T getElementByName<T>(string name) { // materials and constructions if (typeof(T) == typeof(OpaqueConstruction)) { return (T)Convert.ChangeType(OpaqueConstructions.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(GlazingConstruction)) { return (T)Convert.ChangeType(GlazingConstructions.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(OpaqueMaterial)) { return (T)Convert.ChangeType(OpaqueMaterials.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(GlazingMaterial)) { return (T)Convert.ChangeType(GlazingMaterials.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(GasMaterial)) { return (T)Convert.ChangeType(GasMaterials.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(GlazingConstructionSimple)) { return (T)Convert.ChangeType(GlazingConstructionsSimple.Single(o => o.Name == name), typeof(T)); } // schedules else if (typeof(T) == typeof(DaySchedule)) { return (T)Convert.ChangeType(DaySchedules.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(WeekSchedule)) { return (T)Convert.ChangeType(WeekSchedules.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(YearSchedule)) { return (T)Convert.ChangeType(YearSchedules.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(ScheduleArray)) { return (T)Convert.ChangeType(ArraySchedules.Single(o => o.Name == name), typeof(T)); } // zone def else if (typeof(T) == typeof(ZoneLoad)) { return (T)Convert.ChangeType(ZoneLoads.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(ZoneVentilation)) { return (T)Convert.ChangeType(ZoneVentilations.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(ZoneConstruction)) { return (T)Convert.ChangeType(ZoneConstructions.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(ZoneConditioning)) { return (T)Convert.ChangeType(ZoneConditionings.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(DomHotWater)) { return (T)Convert.ChangeType(DomHotWaters.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(ZoneDefinition)) { return (T)Convert.ChangeType(ZoneDefinitions.Single(o => o.Name == name), typeof(T)); } else if (typeof(T) == typeof(WindowSettings)) { return (T)Convert.ChangeType(WindowSettings.Single(o => o.Name == name), typeof(T)); } // dont know what this is??? else return (T)Convert.ChangeType(null, typeof(T)); } [DataMember(Order = 1)] public string Version; [DataMember(Order = 1)] public DateTime TimeStamp; //low level objects [DataMember(Order = 1)] public IList<OpaqueMaterial> OpaqueMaterials; [DataMember(Order = 1)] public IList<GlazingMaterial> GlazingMaterials; [DataMember(Order = 1)] public IList<GasMaterial> GasMaterials; [DataMember(Order = 1)] public IList<GlazingConstructionSimple> GlazingConstructionsSimple; [DataMember(Order = 2)] public IList<OpaqueConstruction> OpaqueConstructions; [DataMember(Order = 2)] public IList<GlazingConstruction> GlazingConstructions; [DataMember(Order = 10)] public IList<DaySchedule> DaySchedules; [DataMember(Order = 11)] public IList<WeekSchedule> WeekSchedules; [DataMember(Order = 12)] public IList<YearSchedule> YearSchedules; [DataMember(Order = 13)] public IList<ScheduleArray> ArraySchedules; //zone definitions [DataMember(Order = 20)] public IList<ZoneLoad> ZoneLoads; [DataMember(Order = 20)] public IList<ZoneVentilation> ZoneVentilations; [DataMember(Order = 20)] public IList<ZoneConstruction> ZoneConstructions; [DataMember(Order = 20)] public IList<ZoneConditioning> ZoneConditionings; [DataMember(Order = 20)] public IList<DomHotWater> DomHotWaters; [DataMember(Order = 30)] public IList<ZoneDefinition> ZoneDefinitions; [DataMember(Order = 30)] public IList<WindowSettings> WindowSettings; public Library() { Version = Utilities.AssemblyVersion; TimeStamp = DateTime.Now; OpaqueMaterials = new List<OpaqueMaterial>(); GlazingMaterials = new List<GlazingMaterial>(); GasMaterials = new List<GasMaterial>(); OpaqueConstructions = new List<OpaqueConstruction>(); GlazingConstructions = new List<GlazingConstruction>(); GlazingConstructionsSimple = new List<GlazingConstructionSimple>(); DaySchedules = new List<DaySchedule>(); WeekSchedules = new List<WeekSchedule>(); YearSchedules = new List<YearSchedule>(); ArraySchedules = new List<ScheduleArray>(); ZoneLoads = new List<ZoneLoad>(); ZoneVentilations = new List<ZoneVentilation>(); ZoneConstructions = new List<ZoneConstruction>(); ZoneConditionings = new List<ZoneConditioning>(); DomHotWaters = new List<DomHotWater>(); ZoneDefinitions = new List<ZoneDefinition>(); WindowSettings = new List<WindowSettings>(); } public static Library fromJSON(string json) { return Serialization.Deserialize<Library>(json); } public string toJSON() { return Serialization.Serialize<Library>(this); } public void Import(string path) { try { if (File.Exists(path)) { Library ImportedLibrary = null; string errPath = Path.GetDirectoryName(path); string json = File.ReadAllText(path); ImportedLibrary = Library.fromJSON(json); string s = ""; if (ImportedLibrary.Correct(out s)) { File.WriteAllText(errPath + "/ImportErrors.txt", s); } Import(ImportedLibrary); Debug.WriteLine("Library loaded from " + path); } } catch (Exception ex) { Debug.WriteLine("eplusIDF.Library import error " + ex.Message); } } public void Import(Library ImportedLibrary) { TimeStamp = ImportedLibrary.TimeStamp; Version = ImportedLibrary.Version; OpaqueMaterials = ImportedLibrary.OpaqueMaterials; GlazingMaterials = ImportedLibrary.GlazingMaterials; GasMaterials = ImportedLibrary.GasMaterials; OpaqueConstructions = ImportedLibrary.OpaqueConstructions; GlazingConstructions = ImportedLibrary.GlazingConstructions; GlazingConstructionsSimple = ImportedLibrary.GlazingConstructionsSimple; DaySchedules = ImportedLibrary.DaySchedules; WeekSchedules = ImportedLibrary.WeekSchedules; YearSchedules = ImportedLibrary.YearSchedules; ArraySchedules = ImportedLibrary.ArraySchedules; ZoneLoads = ImportedLibrary.ZoneLoads; ZoneVentilations = ImportedLibrary.ZoneVentilations; ZoneConstructions = ImportedLibrary.ZoneConstructions; ZoneConditionings = ImportedLibrary.ZoneConditionings; DomHotWaters = ImportedLibrary.DomHotWaters; ZoneDefinitions = ImportedLibrary.ZoneDefinitions; WindowSettings = ImportedLibrary.WindowSettings; } /// <summary> /// Copies the data of one object to another. The target object 'pulls' properties of the first. /// This any matching properties are written to the target. /// /// The object copy is a shallow copy only. Any nested types will be copied as /// whole values rather than individual property assignments (ie. via assignment) /// </summary> /// <param name="source">The source object to copy from</param> /// <param name="target">The object to copy to</param> /// <param name="excludedProperties">A comma delimited list of properties that should not be copied</param> /// <param name="memberAccess">Reflection binding access</param> public static void CopyObjectData(object source, object target, string excludedProperties, BindingFlags memberAccess) { string[] excluded = null; if (!string.IsNullOrEmpty(excludedProperties)) excluded = excludedProperties.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); MemberInfo[] miT = target.GetType().GetMembers(memberAccess); foreach (MemberInfo Field in miT) { string name = Field.Name; // Skip over any property exceptions if (!string.IsNullOrEmpty(excludedProperties) && excluded.Contains(name)) continue; if (Field.MemberType == MemberTypes.Field) { FieldInfo SourceField = source.GetType().GetField(name); if (SourceField == null) continue; object SourceValue = SourceField.GetValue(source); ((FieldInfo)Field).SetValue(target, SourceValue); } else if (Field.MemberType == MemberTypes.Property) { PropertyInfo piTarget = Field as PropertyInfo; PropertyInfo SourceField = source.GetType().GetProperty(name, memberAccess); if (SourceField == null) continue; if (piTarget.CanWrite && SourceField.CanRead) { object SourceValue = SourceField.GetValue(source, null); piTarget.SetValue(target, SourceValue, null); } } } } public void Clear() { try { TimeStamp = DateTime.Now; OpaqueMaterials.Clear(); GlazingMaterials.Clear(); GasMaterials.Clear(); OpaqueConstructions.Clear(); GlazingConstructions.Clear(); GlazingConstructionsSimple.Clear(); DaySchedules.Clear(); WeekSchedules.Clear(); YearSchedules.Clear(); ArraySchedules.Clear(); ZoneLoads.Clear(); ZoneVentilations.Clear(); ZoneConstructions.Clear(); ZoneConditionings.Clear(); DomHotWaters.Clear(); ZoneDefinitions.Clear(); WindowSettings.Clear(); } catch { } } #region CheckForInvalidObjs private void reportInvalidOpaqueMaterials(ref string errorReport) { //Dictionary<string, string> invalidNames = new Dictionary<string, string>(); try { foreach (OpaqueMaterial op in this.OpaqueMaterials) { // find strange names string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (op.Name != cleanName) { errorReport += op.Name + " --> " + cleanName + " invalid characters have been removed" + "\r\n"; op.Name = cleanName; } // autocorrect values out of range // extract as method if (op.Correct()) { errorReport += "Material " + op.Name + " contained invalid entries that have been auto corrected \r\n"; } } } catch (Exception ex) { errorReport += ("reportInvalidOpaqueMaterials failed: " + ex.Message);// + " " + ex.InnerException.Message); } } } private void reportInvalidGlazingMaterials(ref string errorReport) { try { foreach (GlazingMaterial op in this.GlazingMaterials) { // find strange names string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (op.Name != cleanName) { errorReport += op.Name + " --> " + cleanName + " invalid characters have been removed" + "\r\n"; op.Name = cleanName; } // autocorrect values out of range // extract as method if (op.Correct()) { errorReport += "Material " + op.Name + " contained invalid entries that have been auto corrected \r\n"; } } } catch (Exception ex) { errorReport += ("reportInvalidGlazingMaterials failed: " + ex.Message);// + " " + ex.InnerException.Message); } } } private void reportInvalidOCons(ref string errorReport) { foreach (OpaqueConstruction op in this.OpaqueConstructions) { string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (cleanName != op.Name) { //op.Name = HelperFunctions.RemoveSpecialCharacters(op.Name); errorReport += "Construction " + op.Name + " name contained invalid characters and has been auto corrected to " + cleanName + "\r\n"; op.Name = cleanName; } foreach (var ol in op.Layers) { ol.Material.Name = HelperFunctions.RemoveSpecialCharacters(ol.Material.Name);// fix as in materials if (ol.Correct()) { errorReport += "Layer in " + op.Name + " contained invalid thickness \r\n"; } } } } private void reportInvalidGCons(ref string errorReport) { foreach (GlazingConstruction op in this.GlazingConstructions) { string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (cleanName != op.Name) { //op.Name = HelperFunctions.RemoveSpecialCharacters(op.Name); errorReport += "Construction " + op.Name + " name contained invalid characters and has been auto corrected to " + cleanName + "\r\n"; op.Name = cleanName; } foreach (var ol in op.Layers) { ol.SetMaterialName(HelperFunctions.RemoveSpecialCharacters(ol.GetMaterialName()));// fix as in materials if (ol.Correct()) { errorReport += "Layer in " + op.Name + " contained invalid thickness \r\n"; } } } } private void reportInvalidDaySchedules(ref string errorReport) { Dictionary<string, string> invalidNames = new Dictionary<string, string>(); try { foreach (DaySchedule op in this.DaySchedules) { // find strange names string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (op.Name != cleanName) { errorReport += op.Name + " --> " + cleanName + " invalid characters have been removed" + "\r\n"; op.Name = cleanName; } // autocorrect values out of range // extract as method if (op.Correct()) { errorReport += "Schedule " + op.Name + " contained invalid entries that have been auto corrected \r\n"; } } } catch (Exception ex) { errorReport += ("reportInvalidDaySchedules failed: " + ex.Message);// + " " + ex.InnerException.Message); } } } private void reportInvalidWeekSchedules(ref string errorReport) { try { foreach (WeekSchedule op in this.WeekSchedules) { // find strange names string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (op.Name != cleanName) { errorReport += op.Name + " --> " + cleanName + " invalid characters have been removed" + "\r\n"; op.Name = cleanName; } // autocorrect values out of range // extract as method if (op.Correct()) { errorReport += "Schedule " + op.Name + " contained invalid entries that have been auto corrected \r\n"; } } } catch (Exception ex) { errorReport += ("reportInvalidWeekSchedules failed: " + ex.Message);// + " " + ex.InnerException.Message); } } } private void reportInvalidYearSchedules(ref string errorReport) { try { foreach (YearSchedule op in this.YearSchedules) { // find strange names string cleanName = HelperFunctions.RemoveSpecialCharacters(op.Name); if (op.Name != cleanName) { errorReport += op.Name + " --> " + cleanName + " invalid characters have been removed" + "\r\n"; op.Name = cleanName; } // autocorrect values out of range // extract as method if (op.Correct()) { errorReport += "Schedule " + op.Name + " contained invalid entries that have been auto corrected \r\n"; } } } catch (Exception ex) { errorReport += ("reportInvalidYearSchedules failed: " + ex.Message);// + " " + ex.InnerException.Message); } } } public bool Correct(out string err) { string a = ""; reportInvalidOpaqueMaterials(ref a); reportInvalidGlazingMaterials(ref a); reportInvalidOCons(ref a); reportInvalidGCons(ref a); reportInvalidDaySchedules(ref a); reportInvalidWeekSchedules(ref a); reportInvalidYearSchedules(ref a); err = "======= Error report =======\r\n\r\n" + a + "\r\n======= Report End ======="; if (a == "") return false; else return true; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace NaturalDisasterDatabaseWebsite.Models { public class GeologyDetailsViewModel { [Key] public int ID { get; set; } [Display(Name = "发生时间"), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd hh:mm:ss}", ApplyFormatInEditMode = true)] [DataType(DataType.DateTime)] public DateTime geologytime { get; set; } [Display(Name ="参考位置")] public string geologyplace { get;set;} [Display(Name ="经度")] public string geologylogitude { get;set;} [Display(Name ="纬度")] public string geologydimension { get;set;} [Display(Name ="伤亡人数")] public string geologycasualty { get;set;} [Display(Name ="级别")] public string geologylevel { get;set;} [Display(Name ="类型")] public string geologystyle { get;set;} [Display(Name ="经济损失")] public string geologyloss { get;set;} [Display(Name ="受灾面积")] public string geologyarea { get;set;} [Display(Name ="详情")] public string geologydetails { get;set;} public int userID { get;set;} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { [SerializeField] EnemyBullet bulletPrefab; [SerializeField] Transform target; [SerializeField] float trackingSpeed; [SerializeField] float maxSpeed; [SerializeField] float shootInterval; public int hitPoints = 5; private Rigidbody2D _rigidBody; EnemySpawner instance; private void Awake() { _rigidBody = GetComponent<Rigidbody2D>(); target = FindObjectOfType<Player>().transform; instance = FindObjectOfType<EnemySpawner>(); } private void Start() { StartCoroutine(EnemyShoot()); } private void FixedUpdate() { EnemyMovement(); EnemyDead(); } private IEnumerator EnemyShoot() { while (true) { var bullet = Instantiate(bulletPrefab, transform.position, transform.rotation); //bullet.Project(transform.up); bullet.Project(target.transform.position); yield return new WaitForSeconds(5.0f); } } private void EnemyMovement() { if (target) { float step = trackingSpeed * Time.fixedDeltaTime; var toward = Vector3.MoveTowards(_rigidBody.position, target.position, step); _rigidBody.AddForce(target.transform.position - _rigidBody.transform.position); _rigidBody.velocity = Vector3.ClampMagnitude(_rigidBody.velocity, maxSpeed); Debug.DrawLine(_rigidBody.position, toward); } } private void EnemyDead() { if (hitPoints <= 0) { Destroy(gameObject); var gameManager = FindObjectOfType<GameManager>(); gameManager.OnKillEnemy(this); instance.SpawnEnemy(); } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Player") { _rigidBody.velocity = Vector3.zero; _rigidBody.angularVelocity = 0; collision.gameObject.SetActive(false); FindObjectOfType<GameManager>().PlayerDead(); } if (collision.gameObject.tag == "Bullet") { hitPoints--; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; namespace transGraph { public partial class Bills : Form { dbFacade db = new dbFacade(); Global g; public Bills(Global g) { this.g = g; InitializeComponent(); SetDoubleBuffered(dataG, true); #region main table dataG.ColumnCount = 1; dataG.RowsDefaultCellStyle.WrapMode = DataGridViewTriState.True; dataG.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; dataG.Columns[0].HeaderText = "ID листа"; dataG.Columns[0].Width = 80; dataG.Columns[0].ReadOnly = true; dataG.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable; DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn(); cmb.HeaderText = "Статус"; cmb.Name = "cmb"; cmb.Width = 100; foreach (string rr in g.status.Values) cmb.Items.Add(rr); dataG.Columns.Add(cmb); dataG.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns.Add("Направление", "Направление"); dataG.Columns[2].Width = 100; dataG.Columns[2].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[2].ReadOnly = true; dataG.Columns.Add("Марщрут", "Марщрут"); dataG.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataG.Columns[3].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[3].ReadOnly = true; dataG.Columns.Add("Км.", "Км."); dataG.Columns[4].Width = 60; dataG.Columns[4].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[4].ReadOnly = true; dataG.Columns.Add("Мест", "Мест"); dataG.Columns[5].Width = 60; dataG.Columns[5].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[5].ReadOnly = true; dataG.Columns.Add("Точек", "Точек"); dataG.Columns[6].Width = 60; dataG.Columns[6].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[6].ReadOnly = true; dataG.Columns.Add("Масса", "Масса"); dataG.Columns[7].Width = 65; dataG.Columns[7].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[7].ReadOnly = true; dataG.Columns.Add("Водитель", "Водитель"); dataG.Columns[8].Width = 120; dataG.Columns[8].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[8].ReadOnly = true; dataG.Columns.Add("Создан", "Создан"); dataG.Columns[9].Width = 85; dataG.Columns[9].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[9].ReadOnly = true; dataG.Columns.Add("Штрих код", "Штрих код"); dataG.Columns[10].Width = 85; dataG.Columns[10].SortMode = DataGridViewColumnSortMode.NotSortable; dataG.Columns[10].ReadOnly = true; #endregion this.loadit(); } void SetDoubleBuffered(Control c, bool value) { PropertyInfo pi = typeof(Control).GetProperty("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic); if (pi != null) { pi.SetValue(c, value, null); } } public void loadit() { dataG.Rows.Clear(); DataTable data = db.FetchAllSql("SELECT uin,status,routeid,r1,time,timelast,barcode,r1 FROM bills ORDER BY id DESC"); foreach (DataRow rr in data.Rows) { string uin = "", status = "", way = "", route = "", km = "", places = "", bills = "", mass = "", driver = "", time = "", barcode = ""; uin = rr[0].ToString(); #region status try { status = g.status[rr[1].ToString()]; } catch (Exception) { } #endregion #region way try { DataTable dataWay = db.FetchAllSql("SELECT title FROM ways WHERE id = (SELECT wayid FROM routes WHERE id = '" + rr[2].ToString() + "')"); way = dataWay.Rows[0][0].ToString(); } catch (Exception) { } #endregion #region route km // get routes notes try { DataTable dataR = db.FetchAllSql("SELECT ways,km FROM routes WHERE id = '" + rr[2].ToString() + "'"); string waysT = dataR.Rows[0][0].ToString(); km = dataR.Rows[0][1].ToString() + " км."; foreach (string id in waysT.Split(';')) { try { DataTable dataB = db.FetchAllSql("SELECT title FROM citys WHERE id = '" + id + "'"); route += dataB.Rows[0][0].ToString() + " "; } catch (Exception) { } } } catch (Exception) { } #endregion #region places // get routes notes try { int cc = 0; DataTable dataRT = db.FetchAllSql("SELECT d6 FROM billdata WHERE billUin = '" + uin + "'"); foreach (DataRow ss in dataRT.Rows) { string d6T = ss[0].ToString(); foreach (string id in d6T.Split(';')) cc += 1; } places = cc.ToString(); } catch (Exception) { } #endregion #region bills try { DataTable dataR = db.FetchAllSql("SELECT COUNT(*) FROM billdata WHERE billUin = '" + uin + "'"); bills = dataR.Rows[0][0].ToString(); } catch (Exception) { } #endregion #region mass try { DataTable dataR = db.FetchAllSql("SELECT SUM(REPLACE(d10, ',', '.')) FROM billdata WHERE billUin = '" + uin + "'"); mass = dataR.Rows[0][0].ToString() + " кг."; } catch (Exception) { } #endregion #region driver try { driver = rr[3].ToString(); if (driver.Length > 18) driver = driver.Substring(0, 16) + "..."; } catch (Exception) { } #endregion time = FromUnixTime(rr[4].ToString()); barcode = rr[6].ToString(); dataG.Rows.Add(uin, status, way, route, km, places, bills, mass, driver, time, barcode); // pick up new rows try { if(this.UnixTimeNow() - Convert.ToInt32(rr[4].ToString()) < 10) dataG.Rows[dataG.RowCount-1].DefaultCellStyle.BackColor = Color.LightGray; } catch(Exception) {} } } public string FromUnixTime(string unixTime) { DateTime ep = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); ep = ep.AddSeconds(Convert.ToInt32(unixTime) + 3 * 3600); return "" + ep.Day + "." + ep.Month + "." + ep.Year; } public int UnixTimeNow() { TimeSpan _TimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)); return (int)_TimeSpan.TotalSeconds; } private void dataG_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex != 1) { string id = ""; try { id = dataG[0, dataG.SelectedRows[0].Index].Value.ToString(); } catch (Exception) { } if (id != "") { viewBill mt = new viewBill(id); mt.ShowDialog(); //loadit(); } } } private void Bills_FormClosing(object sender, FormClosingEventArgs e) { this.g.Bills = false; } void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex == -1 && e.ColumnIndex >= 0) { e.PaintBackground(e.ClipBounds, true); Rectangle rect = this.dataG.GetColumnDisplayRectangle(e.ColumnIndex, true); Size titleSize = TextRenderer.MeasureText(e.Value.ToString(), e.CellStyle.Font); if (this.dataG.ColumnHeadersHeight < titleSize.Width) this.dataG.ColumnHeadersHeight = titleSize.Width; e.Graphics.TranslateTransform(0, titleSize.Width); e.Graphics.RotateTransform(-90.0F); e.Graphics.DrawString(e.Value.ToString(), this.Font, Brushes.Black, new PointF(rect.Y, rect.X)); e.Graphics.RotateTransform(90.0F); e.Graphics.TranslateTransform(0, -titleSize.Width); e.Handled = true; } } private void toolStripTextBox1_TextChanged(object sender, EventArgs e) { if (this.toolStripTextBox1.Text == "") { for (int i = 0; i < this.dataG.RowCount; i++) this.dataG.Rows[i].Visible = true; return; } for (int i = 0; i < this.dataG.RowCount; i++) this.dataG.Rows[i].Visible = false; string[] search = this.toolStripTextBox1.Text.Split(' '); foreach (string ss in search) { if(ss != "") for (int i = 0; i < this.dataG.RowCount; i++) { if (dataG[0, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[2, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[3, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[4, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[5, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; if (dataG[6, i].Value.ToString().IndexOf(ss) != -1) this.dataG.Rows[i].Visible = true; } } } private void toolStripButton1_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Сохранить изменение в статусах Маршрутных Листов?", "Внимание!", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { dataG.EndEdit(); for (int i = 0; i < dataG.RowCount; i++) { try { string id = dataG[0, i].Value.ToString(); string status = g.getStatusId(dataG[1, i].Value.ToString()); db.FetchAllSql("UPDATE bills SET status = '" + status + "' WHERE uin = '"+id+"'"); } catch (Exception) { } } } } } }
using PDV.DAO.DB.Controller; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.CONTROLER.FuncoesRelatorios { public class FuncoesComanda { public static DataTable GetComandas(decimal CodigoInicial, decimal CodigoFinal) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT IDCOMANDA, CODIGO, DESCRICAO FROM COMANDA WHERE CODIGO::NUMERIC(15) >= @CODIGOINICIAL AND CODIGO::NUMERIC(15) <= @CODIGOFINAL"; oSQL.ParamByName["CODIGOINICIAL"] = CodigoInicial; oSQL.ParamByName["CODIGOFINAL"] = CodigoFinal; oSQL.Open(); return oSQL.dtDados; } } } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class VwVorgangstypdetail { public VwVorgangstypdetail() { VwAktivitaet = new HashSet<VwAktivitaet>(); } public int VorgangstypdetailId { get; set; } public string Bezeichnung { get; set; } public string XmlMapping { get; set; } public int? Position { get; set; } public int? VorgangstypId { get; set; } public bool? AllowExport { get; set; } public bool? Ausgewaehlt { get; set; } public virtual VwVorgangstyp Vorgangstyp { get; set; } public virtual ICollection<VwAktivitaet> VwAktivitaet { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace WeatherApp.Models { public class DailyForecast { // List of <see cref="WeatherApp.Models.DayForecast"/>, ordered by time, which together describe the weather conditions at the requested location over time. [JsonProperty(PropertyName = "data")] public List<DayForecast> Data { get; set; } } }
using Microsoft.Owin; using Microsoft.Owin.Security.Jwt; using Microsoft.Owin.Security.OAuth; using Newtonsoft.Json.Serialization; using Owin; using System; using System.Configuration; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Web.Http; [assembly: OwinStartup(typeof(BoardGamedia.API.Startup))] namespace BoardGamedia.API { /// <summary> /// Startup class for OWIN. /// </summary> public class Startup { /// <summary> /// Gets a <see cref="DbConnectionStringBuilder"/> instance that can be used to access the database. /// </summary> public static DbConnectionStringBuilder ConnectionStringBuilder { get; private set; } /// <summary> /// Called when the application is being configured. /// </summary> /// <param name="app">An <see cref="IAppBuilder"/> representing the app to configure.</param> public void Configuration(IAppBuilder app) { // Get configuration settings from the Web.config var clientId = ConfigurationManager.AppSettings["auth0:ClientId"]; var clientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"]; var domain = ConfigurationManager.AppSettings["auth0:Domain"]; // Set up the connection string builder var connectionString = ConfigurationManager.ConnectionStrings["BoardGamedia"]; var providerFactory = DbProviderFactories.GetFactory(connectionString.ProviderName); ConnectionStringBuilder = providerFactory.CreateConnectionStringBuilder(); ConnectionStringBuilder.ConnectionString = connectionString.ConnectionString; // Set up OAuthBearerAuthentication to use Auth0 var securityOptions = new OAuthBearerAuthenticationOptions { AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, AccessTokenFormat = new JwtFormat(clientId, new SymmetricKeyIssuerSecurityTokenProvider( issuer: new UriBuilder() { Scheme = "https", Host = domain, Path = "/" }.ToString(), base64Key: clientSecret.Replace('-', '+').Replace('_', '/') )) }; app.UseOAuthBearerAuthentication(securityOptions); // Configure WebAPI var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(securityOptions.AuthenticationType)); app.UseWebApi(config); // Make JSON the default format and use Camel Case property names var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } }
/* Copyright © 2005 - 2017 Annpoint, s.r.o. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------------- NOTE: Reuse requires the following acknowledgement (see also NOTICE): This product includes DayPilot (http://www.daypilot.org) developed by Annpoint, s.r.o. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DayPilot.Web.Mvc.Data { /// <summary> /// Summary description for Event. /// </summary> internal class Event { /// <summary> /// Event start. /// </summary> internal DateTime Start; /// <summary> /// Event end. /// </summary> internal DateTime End; /// <summary> /// Event text. /// </summary> internal string Text; /// <summary> /// Event primary key. /// </summary> internal string Id; internal object Source; /// <summary> /// Constructor. /// </summary> internal Event() { } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using DSharpPlus; using DSharpPlus.Entities; using Microsoft.Extensions.Logging; using Requestrr.WebApi.RequestrrBot.ChatClients.Discord; using Requestrr.WebApi.RequestrrBot.Locale; using Requestrr.WebApi.RequestrrBot.Movies; namespace Requestrr.WebApi.RequestrrBot.Notifications.Movies { public class PrivateMessageMovieNotifier : IMovieNotifier { private readonly DiscordClient _discordClient; private readonly ILogger _logger; public PrivateMessageMovieNotifier( DiscordClient discordClient, ILogger logger) { _discordClient = discordClient; _logger = logger; } public async Task<HashSet<string>> NotifyAsync(IReadOnlyCollection<string> userIds, Movie movie, CancellationToken token) { var userNotified = new HashSet<string>(); if (_discordClient.Guilds.Any()) { foreach (var userId in userIds) { if (token.IsCancellationRequested) return userNotified; try { DiscordMember user = null; foreach (var guild in _discordClient.Guilds.Values) { try { user = await guild.GetMemberAsync(ulong.Parse(userId)); break; } catch { } } if (user != null) { var channel = await user.CreateDmChannelAsync(); await channel.SendMessageAsync(Language.Current.DiscordNotificationMovieDM.ReplaceTokens(movie), await DiscordMovieUserInterface.GenerateMovieDetailsAsync(movie)); } else { _logger.LogWarning($"Removing movie notification for user with ID {userId} as it could not be found in any of the guilds."); } userNotified.Add(userId); } catch (System.Exception ex) { _logger.LogError(ex, "An error occurred while sending a private message movie notification to a specific user: " + ex.Message); } } } return userNotified; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WindowListPresenter : ViewPresenterBase<WindowListView, WindowListModel> { }
using LubyClocker.Application.BoundedContexts.Developers.ViewModels; using LubyClocker.CrossCuting.Shared.Common; namespace LubyClocker.Application.BoundedContexts.Developers.Queries.FindAll { public class FindDevelopersQuery : PaginatedQuery<DeveloperViewModel> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace KPI.Model.helpers { public class GetterOCs { // Trả về Getter ứng với code. // (Phương thức này có thể trả về null). public static Getter? GetGetterByCode(string code) { // Lấy hết tất cả các phần tử của Enum. Array allGetters = Enum.GetValues(typeof(Getter)); foreach (Getter getter in allGetters) { string c = GetCode(getter); if (c == code) { return getter; } } return null; } public static int GetLevelNumber(Getter getter) { Getter getterAttr = GetAttr(getter); return getterAttr.LevelNumber; } public static string GetCode(Getter getter) { Getter getterAttr = GetAttr(getter); return getterAttr.Code; } private static Getter GetAttr(Getter getter) { MemberInfo memberInfo = GetMemberInfo(getter); return (Getter)Attribute.GetCustomAttribute(memberInfo, typeof(Getter)); } private static MemberInfo GetMemberInfo(Getter getter) { MemberInfo memberInfo = typeof(Getter).GetField(Enum.GetName(typeof(Getter), getter)); return memberInfo; } } }