text
stringlengths
13
6.01M
// ---------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="ISerializable.cs" company="David Eiwen"> // Copyright © 2016 by David Eiwen // </copyright> // <author>David Eiwen</author> // <summary> // This file contains the ISerializable interface. // </summary> // <remarks>All glory and honor to the risen one!</remarks> // ---------------------------------------------------------------------------------------------------------------------------------------- namespace IndiePortable.Formatter { /// <summary> /// Provides an interface for types that provide a custom serialization and deserialization logic. /// </summary> public interface ISerializable { /// <summary> /// Populates a specified <see cref="ObjectDataCollection" /> instance with data from the <see cref="ISerializable" /> instance. /// </summary> /// <param name="data"> /// The <see cref="ObjectDataCollection" /> that shall be populated. /// </param> void GetObjectData(ObjectDataCollection data); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace Nurikabe_Generator_UWP.Model { public class NuriSound { public enum SoundEfxEnum { Click, Dice, Theme, } public class SoundEffects { private Dictionary<SoundEfxEnum, MediaElement> _effects; public SoundEffects() { _effects = new Dictionary<SoundEfxEnum, MediaElement>(); LoadEfx(); } private async void LoadEfx() { _effects.Add(SoundEfxEnum.Theme, await LoopSoundFile("theme.wav")); _effects.Add(SoundEfxEnum.Click, await LoadSoundFile("click.wav")); _effects.Add(SoundEfxEnum.Dice, await LoadSoundFile("dice.wav")); } private async Task<MediaElement> LoadSoundFile(string v) { MediaElement snd = new MediaElement(); snd.AutoPlay = false; // false snd.IsLooping = false; StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("sounds"); StorageFile file = await folder.GetFileAsync(v); var stream = await file.OpenAsync(FileAccessMode.Read); snd.SetSource(stream, file.ContentType); return snd; } private async Task<MediaElement> LoopSoundFile(string v) { MediaElement snd = new MediaElement(); //snd.AutoPlay = true; snd.AutoPlay = false; snd.IsLooping = true; StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("sounds"); StorageFile file = await folder.GetFileAsync(v); var stream = await file.OpenAsync(FileAccessMode.Read); snd.SetSource(stream, file.ContentType); return snd; } public async Task Play(SoundEfxEnum efx) { var mediaElement = _effects[efx]; mediaElement.Play(); } public async Task Stop(SoundEfxEnum efx) { var mediaElement = _effects[efx]; mediaElement.Stop(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Text; using EWF.Data.Repository; using EWF.Entity; using EWF.Util; namespace EWF.IRepository { public interface ITmpavRepository : IDependency { /// <summary> /// 查询单站水温信息-未分页 /// add by Zhao /// Date:2019-05-23 17:00 /// </summary> /// <param name="stcd"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> IEnumerable<dynamic> GetTempComparativeData(string stcd, string startDate, string endDate); #region 历史同期水温气温-对比分析 /// <summary>历史同期蒸发量对比分析-旬月</summary> /// <param name="STCD">站名</param> /// <param name="STTDRCD">类型4表示旬,5表示月</param> /// <param name="sdate">开始日期</param> /// <param name="edate">结束日期</param> /// <param name="year">对比年份</param> /// <param name="type">对比类型 1:旬,2:月</param> /// <returns>时段内旬月均值</returns> dynamic GetData_MMonthEV(string STCD, string STTDRCD, string sdate, string edate, string sdate_history, string edate_history); #endregion } }
// Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // NOTE: This file is a modified version of SymbolResolver.cs from OleViewDotNet // https://github.com/tyranid/oleviewdotnet. It's been relicensed from GPLv3 by // the original author James Forshaw to be used under the Apache License for this // project. using System; namespace NtApiDotNet.Win32.Debugger { [Flags] enum SymOptions : uint { CASE_INSENSITIVE = 0x00000001, UNDNAME = 0x00000002, DEFERRED_LOADS = 0x00000004, NO_CPP = 0x00000008, LOAD_LINES = 0x00000010, OMAP_FIND_NEAREST = 0x00000020, LOAD_ANYTHING = 0x00000040, IGNORE_CVREC = 0x00000080, NO_UNQUALIFIED_LOADS = 0x00000100, FAIL_CRITICAL_ERRORS = 0x00000200, EXACT_SYMBOLS = 0x00000400, ALLOW_ABSOLUTE_SYMBOLS = 0x00000800, IGNORE_NT_SYMPATH = 0x00001000, INCLUDE_32BIT_MODULES = 0x00002000, PUBLICS_ONLY = 0x00004000, NO_PUBLICS = 0x00008000, AUTO_PUBLICS = 0x00010000, NO_IMAGE_SEARCH = 0x00020000, SECURE = 0x00040000, NO_PROMPTS = 0x00080000, OVERWRITE = 0x00100000, IGNORE_IMAGEDIR = 0x00200000, FLAT_DIRECTORY = 0x00400000, FAVOR_COMPRESSED = 0x00800000, ALLOW_ZERO_ADDRESS = 0x01000000, DISABLE_SYMSRV_AUTODETECT = 0x02000000, READONLY_CACHE = 0x04000000, SYMPATH_LAST = 0x08000000, DISABLE_FAST_SYMBOLS = 0x10000000, DISABLE_SYMSRV_TIMEOUT = 0x20000000, DISABLE_SRVSTAR_ON_STARTUP = 0x40000000, DEBUG = 0x80000000, } }
using System.Diagnostics; using System.IO; using Caliburn.Micro; using Frontend.Core.Logging; namespace Frontend.Core.Commands { public class OpenUriCommand : CommandBase { public OpenUriCommand(IEventAggregator eventAggregator) : base(eventAggregator) { } protected override void OnExecute(object parameter) { var path = (string) parameter; if (string.IsNullOrEmpty(path)) { return; } var isFile = File.Exists(path); var isDirectory = Directory.Exists(path); try { if (isDirectory) { Process.Start(path); } else if (isFile && !isDirectory) { var args = string.Format("/Select, {0}", path); var pfi = new ProcessStartInfo("Explorer.exe", args); Process.Start(pfi); } else { var folderWhereFileWasExpectedToExist = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(folderWhereFileWasExpectedToExist)) { Process.Start(folderWhereFileWasExpectedToExist); } } } catch { EventAggregator.PublishOnUIThread( new LogEntry( "Opening the directory (and/or selecting the file failed miserably. Please try manually instead.", LogEntrySeverity.Error, LogEntrySource.UI)); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AllFactories.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CGI.Reflex.Core.Tests.Factories { public class AllFactories { public AllFactories() { Application = new ApplicationFactory(this); AuditInfo = new AuditInfoFactory(this); Contact = new ContactFactory(this); DomainValue = new DomainValueFactory(this); Event = new EventFactory(this); Integration = new IntegrationFactory(this); Role = new RoleFactory(this); Sector = new SectorFactory(this); Technology = new TechnologyFactory(this); User = new UserFactory(this); Server = new ServerFactory(this); Landscape = new LandscapeFactory(this); LogEntry = new LogEntryFactory(this); AppContactLink = new AppContactLinkFactory(this); Question = new QuestionFactory(this); QuestionAnswer = new QuestionAnswerFactory(this); DbInstance = new DbInstanceFactory(this); } public ApplicationFactory Application { get; private set; } public AuditInfoFactory AuditInfo { get; private set; } public ContactFactory Contact { get; private set; } public DomainValueFactory DomainValue { get; private set; } public EventFactory Event { get; private set; } public IntegrationFactory Integration { get; private set; } public RoleFactory Role { get; private set; } public SectorFactory Sector { get; private set; } public TechnologyFactory Technology { get; private set; } public UserFactory User { get; private set; } public ServerFactory Server { get; private set; } public LandscapeFactory Landscape { get; private set; } public LogEntryFactory LogEntry { get; private set; } public AppContactLinkFactory AppContactLink { get; private set; } public QuestionFactory Question { get; private set; } public QuestionAnswerFactory QuestionAnswer { get; private set; } public DbInstanceFactory DbInstance { get; private set; } } }
using Espades.Domain.Contracts.Services.Base; using Espades.Domain.Entities; namespace Espades.Domain.Contracts.Services { public interface IEstoqueService : IService<Estoque> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Threax.AspNetCore.CorsManager { public class CorsManagerOptions { /// <summary> /// Fully remove all CORS protection from this website. Not reccomended for production. /// </summary> public bool UnlimitedAccess { get; set; } public List<String> AllowedOrigins { get; set; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using MortgageCalculator.Model; namespace MortgageCalculator.DAL.Data { public class DataContext: DbContext { public DataContext() : base("DefaultConnection") { } public DbSet<Mortgage> Mortgages { get; set; } public DbSet<User> Users { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using starkdev.spreadrecon.model; using starkdev.utils; using System.IO; using OfficeOpenXml; namespace starkdev.spreadrecon.data { public class PagamentoOperadoraDAL { private readonly _Contexto contexto; public PagamentoOperadoraDAL() { contexto = new _Contexto(); } public List<PagamentoOperadora> ListarTodos() { var retornoLista = new List<PagamentoOperadora>(); var commandText = PagamentoOperadoraSQL.Listar; var linhas = contexto.ExecutaComandoComRetorno(commandText); foreach (var row in linhas) { var retorno = new PagamentoOperadora { id = row["id"].ToLong(), nomeCicloPagamento = row["nomeCicloPagamento"], tipoIncentivo = row["tipoIncentivo"], tipoEvento = row["tipoEvento"], descricao = row["descricao"], categoria = row["categoria"], numeroPDV = row["numeroPDV"], nomePDV = row["nomePDV"], numeroSFIDPDVPagador = row["numeroSFIDPDVPagador"], nomePDVPagador = row["nomePDVPagador"], dataEvento = row["dataEvento"].ToDateTime(), dataAtivacao = row["dataAtivacao"].ToDateTime(), dataDesativacao = row["dataDesativacao"].ToDateTime(), dataDocumento = row["dataDocumento"].ToDateTime(), motivo = row["motivo"], numeroContrato = row["numeroContrato"], numeroMSISDN = row["numeroMSISDN"], numeroIMEI = row["numeroIMEI"], numeroICCID = row["numeroICCID"], nomeAparelho = row["nomeAparelho"], nomeCampanha = row["nomeCampanha"], nomeCampanhaAnterior = row["nomeCampanhaAnterior"], nomeOferta = row["nomeOferta"], numeroIDBundle = row["numeroIDBundle"], nomeBundle = row["nomeBundle"], dataBundle = row["dataBundle"].ToDateTime(), nomeRelacionamento = row["nomeRelacionamento"], nomeRelacionamentoAnterior = row["nomeRelacionamentoAnterior"], tipoOiTV = row["tipoOiTV"], isCliente = row["isCliente"].ToBoolean(), tipoMigracao = row["tipoMigracao"], nomePlanoEvento = row["nomePlanoEvento"], nomePlanoAnterior = row["nomePlanoAnterior"], nomePlanoGrupo = row["nomePlanoGrupo"], nomeGrupoPlanoContabil = row["nomeGrupoPlanoContabil"], nomeServicoEvento = row["nomeServicoEvento"], nomeServicoAnterior = row["nomeServicoAnterior"], nomeServicoGrupo = row["nomeServicoGrupo"], nomeGrupoServicoContabil = row["nomeGrupoServicoContabil"], totalVoiceTerminal = row["totalVoiceTerminal"], totalVoiceDias = row["totalVoiceDias"], nomeCartaoCredito = row["nomeCartaoCredito"], isPortabilidade = row["isPortabilidade"].ToBoolean(), isOCT = row["isOCT"].ToBoolean(), quantidade = row["quantidade"], tipoPex = row["tipoPex"], valor = row["valor"].ToDecimal(), valorAnterior = row["valorAnterior"].ToDecimal(), valorEvento = row["valorEvento"].ToDecimal(), valorCalculado = row["valorCalculado"].ToDecimal(), valorPago = row["valorPago"].ToDecimal(), idImportacaoPlanilha = row["idImportacaoPlanilha"].ToLong() }; retornoLista.Add(retorno); } return retornoLista; } public List<PagamentoOperadora> ListarLinhas(long id) { var retornoLista = new List<PagamentoOperadora>(); var commandText = PagamentoOperadoraSQL.ListarLinhas; var parametros = new Dictionary<string, object> { {"idImportacaoPlanilha", id} }; var linhas = contexto.ExecutaComandoComRetorno(commandText, parametros); foreach (var row in linhas) { var retorno = new PagamentoOperadora { id = row["id"].ToLong(), nomeCicloPagamento = row["nomeCicloPagamento"], tipoIncentivo = row["tipoIncentivo"], tipoEvento = row["tipoEvento"], descricao = row["descricao"], categoria = row["categoria"], numeroPDV = row["numeroPDV"], nomePDV = row["nomePDV"], numeroSFIDPDVPagador = row["numeroSFIDPDVPagador"], nomePDVPagador = row["nomePDVPagador"], dataEvento = row["dataEvento"].ToDateTime(), dataAtivacao = row["dataAtivacao"].ToDateTime(), dataDesativacao = row["dataDesativacao"].ToDateTime(), dataDocumento = row["dataDocumento"].ToDateTime(), motivo = row["motivo"], numeroContrato = row["numeroContrato"], numeroMSISDN = row["numeroMSISDN"], numeroIMEI = row["numeroIMEI"], numeroICCID = row["numeroICCID"], nomeAparelho = row["nomeAparelho"], nomeCampanha = row["nomeCampanha"], nomeCampanhaAnterior = row["nomeCampanhaAnterior"], nomeOferta = row["nomeOferta"], numeroIDBundle = row["numeroIDBundle"], nomeBundle = row["nomeBundle"], dataBundle = row["dataBundle"].ToDateTime(), nomeRelacionamento = row["nomeRelacionamento"], nomeRelacionamentoAnterior = row["nomeRelacionamentoAnterior"], tipoOiTV = row["tipoOiTV"], isCliente = row["isCliente"].ToBoolean(), tipoMigracao = row["tipoMigracao"], nomePlanoEvento = row["nomePlanoEvento"], nomePlanoAnterior = row["nomePlanoAnterior"], nomePlanoGrupo = row["nomePlanoGrupo"], nomeGrupoPlanoContabil = row["nomeGrupoPlanoContabil"], nomeServicoEvento = row["nomeServicoEvento"], nomeServicoAnterior = row["nomeServicoAnterior"], nomeServicoGrupo = row["nomeServicoGrupo"], nomeGrupoServicoContabil = row["nomeGrupoServicoContabil"], totalVoiceTerminal = row["totalVoiceTerminal"], totalVoiceDias = row["totalVoiceDias"], nomeCartaoCredito = row["nomeCartaoCredito"], isPortabilidade = row["isPortabilidade"].ToBoolean(), isOCT = row["isOCT"].ToBoolean(), quantidade = row["quantidade"], tipoPex = row["tipoPex"], valor = row["valor"].ToDecimal(), valorAnterior = row["valorAnterior"].ToDecimal(), valorEvento = row["valorEvento"].ToDecimal(), valorCalculado = row["valorCalculado"].ToDecimal(), valorPago = row["valorPago"].ToDecimal(), idImportacaoPlanilha = row["idImportacaoPlanilha"].ToLong() }; #region Status var retornoStatus = new Status { id = row["idStatus"].ToLong(), nomeStatus = row["nomeStatus"], descricao = row["descricaoStatus"] }; retorno.status = retornoStatus; #endregion retornoLista.Add(retorno); } return retornoLista; } private long Inserir(PagamentoOperadora obj) { var commandText = PagamentoOperadoraSQL.Inserir; var parametros = new Dictionary<string, object> { {"nomeCicloPagamento", obj.nomeCicloPagamento}, {"tipoIncentivo", obj.tipoIncentivo}, {"tipoEvento", obj.tipoEvento}, {"descricao", obj.descricao}, {"categoria", obj.categoria}, {"numeroPDV", obj.numeroPDV}, {"nomePDV", obj.nomePDV}, {"numeroSFIDPDVPagador", obj.numeroSFIDPDVPagador}, {"nomePDVPagador", obj.nomePDVPagador}, {"dataEvento", obj.dataEvento}, {"dataAtivacao", obj.dataAtivacao}, {"dataDesativacao", obj.dataDesativacao}, {"dataDocumento", obj.dataDocumento}, {"motivo", obj.motivo}, {"numeroContrato", obj.numeroContrato}, {"numeroMSISDN", obj.numeroMSISDN}, {"numeroIMEI", obj.numeroIMEI}, {"numeroICCID", obj.numeroICCID}, {"nomeAparelho", obj.nomeAparelho}, {"nomeCampanha", obj.nomeCampanha}, {"nomeCampanhaAnterior", obj.nomeCampanhaAnterior}, {"nomeOferta", obj.nomeOferta}, {"numeroIDBundle", obj.numeroIDBundle}, {"nomeBundle", obj.nomeBundle}, {"dataBundle", obj.dataBundle}, {"nomeRelacionamento", obj.nomeRelacionamento}, {"nomeRelacionamentoAnterior", obj.nomeRelacionamentoAnterior}, {"tipoOiTV", obj.tipoOiTV}, {"isCliente", obj.isCliente}, {"tipoMigracao", obj.tipoMigracao}, {"nomePlanoEvento", obj.nomePlanoEvento}, {"nomePlanoAnterior", obj.nomePlanoAnterior}, {"nomePlanoGrupo", obj.nomePlanoGrupo}, {"nomeGrupoPlanoContabil", obj.nomeGrupoPlanoContabil}, {"nomeServicoEvento", obj.nomeServicoEvento}, {"nomeServicoAnterior", obj.nomeServicoAnterior}, {"nomeServicoGrupo", obj.nomeServicoGrupo}, {"nomeGrupoServicoContabil", obj.nomeGrupoServicoContabil}, {"totalVoiceTerminal", obj.totalVoiceTerminal}, {"totalVoiceDias", obj.totalVoiceDias}, {"nomeCartaoCredito", obj.nomeCartaoCredito}, {"isPortabilidade", obj.isPortabilidade}, {"isOCT", obj.isOCT}, {"quantidade", obj.quantidade}, {"tipoPex", obj.tipoPex}, {"valor", obj.valor}, {"valorAnterior", obj.valorAnterior}, {"valorEvento", obj.valorEvento}, {"valorCalculado", obj.valorCalculado}, {"valorPago", obj.valorPago}, {"idImportacaoPlanilha", obj.idImportacaoPlanilha} }; return contexto.ExecutaComando(commandText, parametros); } private long Alterar(PagamentoOperadora obj) { var commandText = PagamentoOperadoraSQL.Alterar; var parametros = new Dictionary<string, object> { {"id", obj.id}, {"nomeCicloPagamento", obj.nomeCicloPagamento}, {"tipoIncentivo", obj.tipoIncentivo}, {"tipoEvento", obj.tipoEvento}, {"descricao", obj.descricao}, {"categoria", obj.categoria}, {"numeroPDV", obj.numeroPDV}, {"nomePDV", obj.nomePDV}, {"numeroSFIDPDVPagador", obj.numeroSFIDPDVPagador}, {"nomePDVPagador", obj.nomePDVPagador}, {"dataEvento", obj.dataEvento}, {"dataAtivacao", obj.dataAtivacao}, {"dataDesativacao", obj.dataDesativacao}, {"dataDocumento", obj.dataDocumento}, {"motivo", obj.motivo}, {"numeroContrato", obj.numeroContrato}, {"numeroMSISDN", obj.numeroMSISDN}, {"numeroIMEI", obj.numeroIMEI}, {"numeroICCID", obj.numeroICCID}, {"nomeAparelho", obj.nomeAparelho}, {"nomeCampanha", obj.nomeCampanha}, {"nomeCampanhaAnterior", obj.nomeCampanhaAnterior}, {"nomeOferta", obj.nomeOferta}, {"numeroIDBundle", obj.numeroIDBundle}, {"nomeBundle", obj.nomeBundle}, {"dataBundle", obj.dataBundle}, {"nomeRelacionamento", obj.nomeRelacionamento}, {"nomeRelacionamentoAnterior", obj.nomeRelacionamentoAnterior}, {"tipoOiTV", obj.tipoOiTV}, {"isCliente", obj.isCliente}, {"tipoMigracao", obj.tipoMigracao}, {"nomePlanoEvento", obj.nomePlanoEvento}, {"nomePlanoAnterior", obj.nomePlanoAnterior}, {"nomePlanoGrupo", obj.nomePlanoGrupo}, {"nomeGrupoPlanoContabil", obj.nomeGrupoPlanoContabil}, {"nomeServicoEvento", obj.nomeServicoEvento}, {"nomeServicoAnterior", obj.nomeServicoAnterior}, {"nomeServicoGrupo", obj.nomeServicoGrupo}, {"nomeGrupoServicoContabil", obj.nomeGrupoServicoContabil}, {"totalVoiceTerminal", obj.totalVoiceTerminal}, {"totalVoiceDias", obj.totalVoiceDias}, {"nomeCartaoCredito", obj.nomeCartaoCredito}, {"isPortabilidade", obj.isPortabilidade}, {"isOCT", obj.isOCT}, {"quantidade", obj.quantidade}, {"tipoPex", obj.tipoPex}, {"valor", obj.valor}, {"valorAnterior", obj.valorAnterior}, {"valorEvento", obj.valorEvento}, {"valorCalculado", obj.valorCalculado}, {"valorPago", obj.valorPago}, {"idImportacaoPlanilha", obj.idImportacaoPlanilha} }; return contexto.ExecutaComando(commandText, parametros); } public long Salvar(PagamentoOperadora obj) { if (obj.id > 0) Alterar(obj); else obj.id = Inserir(obj); return obj.id; } public long Excluir(int id) { var commandText = PagamentoOperadoraSQL.Excluir; var parametros = new Dictionary<string, object> { {"id", id} }; return contexto.ExecutaComando(commandText, parametros); } public PagamentoOperadora ListarPorId(long id) { var retorno = new List<PagamentoOperadora>(); var commandText = PagamentoOperadoraSQL.ListarPorId; var parametros = new Dictionary<string, object> { {"id", id} }; var linhas = contexto.ExecutaComandoComRetorno(commandText, parametros); foreach (var row in linhas) { var tempPagamentoOperadora = new PagamentoOperadora { id = row["id"].ToLong(), nomeCicloPagamento = row["nomeCicloPagamento"], tipoIncentivo = row["tipoIncentivo"], tipoEvento = row["tipoEvento"], descricao = row["descricao"], categoria = row["categoria"], numeroPDV = row["numeroPDV"], nomePDV = row["nomePDV"], numeroSFIDPDVPagador = row["numeroSFIDPDVPagador"], nomePDVPagador = row["nomePDVPagador"], dataEvento = row["dataEvento"].ToDateTime(), dataAtivacao = row["dataAtivacao"].ToDateTime(), dataDesativacao = row["dataDesativacao"].ToDateTime(), dataDocumento = row["dataDocumento"].ToDateTime(), motivo = row["motivo"], numeroContrato = row["numeroContrato"], numeroMSISDN = row["numeroMSISDN"], numeroIMEI = row["numeroIMEI"], numeroICCID = row["numeroICCID"], nomeAparelho = row["nomeAparelho"], nomeCampanha = row["nomeCampanha"], nomeCampanhaAnterior = row["nomeCampanhaAnterior"], nomeOferta = row["nomeOferta"], numeroIDBundle = row["numeroIDBundle"], nomeBundle = row["nomeBundle"], dataBundle = row["dataBundle"].ToDateTime(), nomeRelacionamento = row["nomeRelacionamento"], nomeRelacionamentoAnterior = row["nomeRelacionamentoAnterior"], tipoOiTV = row["tipoOiTV"], isCliente = row["isCliente"].ToBoolean(), tipoMigracao = row["tipoMigracao"], nomePlanoEvento = row["nomePlanoEvento"], nomePlanoAnterior = row["nomePlanoAnterior"], nomePlanoGrupo = row["nomePlanoGrupo"], nomeGrupoPlanoContabil = row["nomeGrupoPlanoContabil"], nomeServicoEvento = row["nomeServicoEvento"], nomeServicoAnterior = row["nomeServicoAnterior"], nomeServicoGrupo = row["nomeServicoGrupo"], nomeGrupoServicoContabil = row["nomeGrupoServicoContabil"], totalVoiceTerminal = row["totalVoiceTerminal"], totalVoiceDias = row["totalVoiceDias"], nomeCartaoCredito = row["nomeCartaoCredito"], isPortabilidade = row["isPortabilidade"].ToBoolean(), isOCT = row["isOCT"].ToBoolean(), quantidade = row["quantidade"], tipoPex = row["tipoPex"], valor = row["valor"].ToDecimal(), valorAnterior = row["valorAnterior"].ToDecimal(), valorEvento = row["valorEvento"].ToDecimal(), valorCalculado = row["valorCalculado"].ToDecimal(), valorPago = row["valorPago"].ToDecimal(), idImportacaoPlanilha = row["idImportacaoPlanilha"].ToLong() }; retorno.Add(tempPagamentoOperadora); } return retorno.FirstOrDefault(); } public bool Importar(ImportacaoPlanilha importacao) { string sheetName = "importar"; //var connectionString = ""; var pathArquivoPendente = string.Format("{0}{1}", importacao._diretorioPendente, importacao.nomeArquivoProcessado); var pathArquivoProcessado = string.Format("{0}{1}", importacao._diretorioProcessado, importacao.nomeArquivoProcessado); var pathArquivoLog = string.Format("{0}{1}", importacao._diretorioLog, importacao.nomeArquivoErro); try { FileInfo file = new FileInfo(pathArquivoPendente); using (var package = new ExcelPackage(file)) { var currentSheet = package.Workbook.Worksheets; var workSheet = currentSheet.First(p => p.Name.ToLower() == sheetName.ToLower()); //abre a planilha chamada "importar" var totalColuna = workSheet.Dimension.End.Column; var totalLinha = workSheet.Dimension.End.Row; //Importar conteúdo da planilha int totalErros = 0; int totalSucesso = 0; int numeroLinha = 1; //ignora primeira linha cabeçalho for (int rowIterator = 2; rowIterator <= totalLinha; rowIterator++) { //user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString(); numeroLinha++; int columnIterator = 0; try { var numeroMSISDN = string.Empty; var descricao = string.Empty; if (workSheet.Cells[rowIterator, 16].Value != null) numeroMSISDN = workSheet.Cells[rowIterator, 16].Value.ToString(); if (workSheet.Cells[rowIterator, 4].Value != null) { descricao = workSheet.Cells[rowIterator, 4].Value.ToString(); //caso no arquivo nao venha preenchido o MSISDN, pega o numero do telefone da coluna de Descrição if (string.IsNullOrEmpty(numeroMSISDN)) { //Se no campo descrição contem a palavra MSISDN, então captura o numero telefone if (descricao.Contains("MSISDN")) { //Captura as ultimas 11 posicoes, que correspondem ao telefone numeroMSISDN = descricao.Trim().Substring(descricao.Trim().IndexOf("MSISDN") + 7, 11); } } } //Prossegue apenas se existir (coluna P) numero do terminal ou se a (coluna D) Descrição esta preenchida if (!string.IsNullOrEmpty(descricao) || !string.IsNullOrEmpty(numeroMSISDN)) { PagamentoOperadora obj = new PagamentoOperadora(); #region Mapeamento das colunas excel columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeCicloPagamento = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.tipoIncentivo = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.tipoEvento = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; obj.descricao = descricao; //if (workSheet.Cells[rowIterator, columnIterator].Value != null) // obj.descricao = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.categoria = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.numeroPDV = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomePDV = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.numeroSFIDPDVPagador = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomePDVPagador = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.dataEvento = workSheet.Cells[rowIterator, columnIterator].Value.ToDateTime(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.dataAtivacao = workSheet.Cells[rowIterator, columnIterator].Value.ToDateTime(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.dataDesativacao = workSheet.Cells[rowIterator, columnIterator].Value.ToDateTime(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.dataDocumento = workSheet.Cells[rowIterator, columnIterator].Value.ToDateTime(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.motivo = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.numeroContrato = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; obj.numeroMSISDN = numeroMSISDN; //if (workSheet.Cells[rowIterator, columnIterator].Value != null) // obj.numeroMSISDN = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.numeroIMEI = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.numeroICCID = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeAparelho = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeCampanha = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeCampanhaAnterior = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeOferta = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.numeroIDBundle = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeBundle = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.dataBundle = workSheet.Cells[rowIterator, columnIterator].Value.ToDateTime(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeRelacionamento = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeRelacionamentoAnterior = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.tipoOiTV = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.isCliente_string = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.tipoMigracao = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomePlanoEvento = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomePlanoAnterior = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomePlanoGrupo = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeGrupoPlanoContabil = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeServicoEvento = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeServicoAnterior = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeServicoGrupo = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeGrupoServicoContabil = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.totalVoiceTerminal = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.totalVoiceDias = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.nomeCartaoCredito = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.isPortabilidade_string = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.isOCT_string = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.quantidade = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.tipoPex = workSheet.Cells[rowIterator, columnIterator].Value.ToString(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.valor = workSheet.Cells[rowIterator, columnIterator].Value.ToDecimal(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.valorAnterior = workSheet.Cells[rowIterator, columnIterator].Value.ToDecimal(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.valorEvento = workSheet.Cells[rowIterator, columnIterator].Value.ToDecimal(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.valorCalculado = workSheet.Cells[rowIterator, columnIterator].Value.ToDecimal(); columnIterator++; if (workSheet.Cells[rowIterator, columnIterator].Value != null) obj.valorPago = workSheet.Cells[rowIterator, columnIterator].Value.ToDecimal(); #endregion //Atualizar importacao obj.importacaoPlanilha = importacao; obj.idImportacaoPlanilha = importacao.id; //Inserir no banco this.Salvar(obj); totalSucesso++; } else { totalErros++; var log = string.Format("Linha: {0} - {1}", numeroLinha, "Campo 'Descrição' ou 'MSISDN/Terminal' não podem ser vazios"); this.GerarArquivoLogErro(pathArquivoLog, log); } } catch (Exception ex) { totalErros++; var log = string.Format("Linha: {0} - {1}", numeroLinha, ex.Message); this.GerarArquivoLogErro(pathArquivoLog, log); } } importacao.dataFimProcessamento = DateTime.Now; importacao.qtdImportacaoSucesso = totalSucesso; importacao.qtdImportacaoIgnorada = totalErros; importacao.idStatus = 1; ImportacaoPlanilhaDAL _dalImportacaoPlanilhaDAL = new ImportacaoPlanilhaDAL(); _dalImportacaoPlanilhaDAL.Salvar(importacao); //remover os arquivos temporarios if ((File.Exists(pathArquivoPendente))) { File.Move(pathArquivoPendente, pathArquivoProcessado); } } return true; } catch (Exception ex) { var mensagemErro = ex.Message; if (mensagemErro.ToUpper().Contains("SEQUENCE CONTAINS NO MATCHING ELEMENT")) mensagemErro = "Não foi encontrada nenhuma planilha com nome 'importar', favor verificar no EXCEL"; var log = string.Format("Arquivo: {0} - Erro: {1}", pathArquivoPendente, mensagemErro); this.GerarArquivoLogErro(pathArquivoLog, log); //Cancelar processamento importacao.dataFimProcessamento = DateTime.Now; importacao.idStatus = 3; ImportacaoPlanilhaDAL _dalImportacaoPlanilhaDAL = new ImportacaoPlanilhaDAL(); _dalImportacaoPlanilhaDAL.Salvar(importacao); //remover os arquivos temporarios if ((File.Exists(pathArquivoPendente))) { File.Move(pathArquivoPendente, pathArquivoProcessado); } return false; } } private void GerarArquivoLogErro(string filePath, string log) { var line = string.Format("[ERRO]\t{1}\t{0}", log, DateTime.Now.ToString("[dd/MM/yyyy HH:mm:ss]")); using (FileStream aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write)) using (StreamWriter sw = new StreamWriter(aFile)) { sw.WriteLine(line); } } public bool AtualizarStatus(long idStatus, string tipo) { try { var commandText = string.Empty; switch (tipo.ToUpper()) { case "C": commandText = PagamentoOperadoraSQL.AtualizarStatusConciliados; break; case "N": commandText = PagamentoOperadoraSQL.AtualizarStatusNaoConciliados; break; default: break; } var parametros = new Dictionary<string, object> { {"idStatus", idStatus} }; contexto.ExecutaComando(commandText, parametros); return true; } catch (Exception) { return false; } } } }
using System; using System.Data; using System.Text; using System.Configuration; using System.Diagnostics; using System.Xml.Serialization; using System.Collections.Generic; using Karkas.Core.TypeLibrary; using Karkas.Core.Onaylama; using Karkas.Core.Onaylama.ForPonos; using System.ComponentModel.DataAnnotations; namespace Karkas.Ornek.TypeLibrary.Ornekler { [Serializable] [DebuggerDisplay("OrnekTabloKey = {OrnekTabloKey}")] public partial class OrnekTablo: BaseTypeLibrary { private Guid ornekTabloKey; private Nullable<long> kolonBigInt; private byte[] kolonBinary; private Nullable<bool> kolonBit; private string kolonChar; private Nullable<DateTime> kolonDateTime; private Nullable<decimal> kolonDecimal; private Nullable<double> kolonFloat; private byte[] kolonImage; private Nullable<int> kolonInt; private Nullable<decimal> kolonMoney; private string kolonNchar; private string kolonNtext; private Nullable<decimal> kolonNumeric; private string kolonNvarchar; private string kolonNvarcharMax; private Nullable<float> kolonReal; private Nullable<DateTime> kolonSmallDateTime; private Nullable<short> kolonSmallInt; private Nullable<decimal> kolonSmallMoney; private object kolonSqlVariant; private string kolonText; private byte[] kolonTimeStamp; private Nullable<byte> kolonTinyInt; private Nullable<Guid> kolonUniqueIdentifier; private byte[] kolonVarBinary; private byte[] kolonVarBinaryMax; private string kolonVarchar; private string kolonVarcharMax; private string kolonXml; [Key] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Guid OrnekTabloKey { [DebuggerStepThrough] get { return ornekTabloKey; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (ornekTabloKey!= value)) { this.RowState = DataRowState.Modified; } ornekTabloKey = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<long> KolonBigInt { [DebuggerStepThrough] get { return kolonBigInt; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonBigInt!= value)) { this.RowState = DataRowState.Modified; } kolonBigInt = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public byte[] KolonBinary { [DebuggerStepThrough] get { return kolonBinary; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonBinary!= value)) { this.RowState = DataRowState.Modified; } kolonBinary = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<bool> KolonBit { [DebuggerStepThrough] get { return kolonBit; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonBit!= value)) { this.RowState = DataRowState.Modified; } kolonBit = value; } } [StringLength(10)] [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonChar { [DebuggerStepThrough] get { return kolonChar; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonChar!= value)) { this.RowState = DataRowState.Modified; } kolonChar = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<DateTime> KolonDateTime { [DebuggerStepThrough] get { return kolonDateTime; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonDateTime!= value)) { this.RowState = DataRowState.Modified; } kolonDateTime = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<decimal> KolonDecimal { [DebuggerStepThrough] get { return kolonDecimal; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonDecimal!= value)) { this.RowState = DataRowState.Modified; } kolonDecimal = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<double> KolonFloat { [DebuggerStepThrough] get { return kolonFloat; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonFloat!= value)) { this.RowState = DataRowState.Modified; } kolonFloat = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public byte[] KolonImage { [DebuggerStepThrough] get { return kolonImage; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonImage!= value)) { this.RowState = DataRowState.Modified; } kolonImage = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<int> KolonInt { [DebuggerStepThrough] get { return kolonInt; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonInt!= value)) { this.RowState = DataRowState.Modified; } kolonInt = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<decimal> KolonMoney { [DebuggerStepThrough] get { return kolonMoney; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonMoney!= value)) { this.RowState = DataRowState.Modified; } kolonMoney = value; } } [StringLength(10)] [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonNchar { [DebuggerStepThrough] get { return kolonNchar; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonNchar!= value)) { this.RowState = DataRowState.Modified; } kolonNchar = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonNtext { [DebuggerStepThrough] get { return kolonNtext; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonNtext!= value)) { this.RowState = DataRowState.Modified; } kolonNtext = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<decimal> KolonNumeric { [DebuggerStepThrough] get { return kolonNumeric; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonNumeric!= value)) { this.RowState = DataRowState.Modified; } kolonNumeric = value; } } [StringLength(50)] [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonNvarchar { [DebuggerStepThrough] get { return kolonNvarchar; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonNvarchar!= value)) { this.RowState = DataRowState.Modified; } kolonNvarchar = value; } } [StringLength(-1)] [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonNvarcharMax { [DebuggerStepThrough] get { return kolonNvarcharMax; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonNvarcharMax!= value)) { this.RowState = DataRowState.Modified; } kolonNvarcharMax = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<float> KolonReal { [DebuggerStepThrough] get { return kolonReal; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonReal!= value)) { this.RowState = DataRowState.Modified; } kolonReal = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<DateTime> KolonSmallDateTime { [DebuggerStepThrough] get { return kolonSmallDateTime; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonSmallDateTime!= value)) { this.RowState = DataRowState.Modified; } kolonSmallDateTime = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<short> KolonSmallInt { [DebuggerStepThrough] get { return kolonSmallInt; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonSmallInt!= value)) { this.RowState = DataRowState.Modified; } kolonSmallInt = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<decimal> KolonSmallMoney { [DebuggerStepThrough] get { return kolonSmallMoney; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonSmallMoney!= value)) { this.RowState = DataRowState.Modified; } kolonSmallMoney = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object KolonSqlVariant { [DebuggerStepThrough] get { return kolonSqlVariant; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonSqlVariant!= value)) { this.RowState = DataRowState.Modified; } kolonSqlVariant = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonText { [DebuggerStepThrough] get { return kolonText; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonText!= value)) { this.RowState = DataRowState.Modified; } kolonText = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public byte[] KolonTimeStamp { [DebuggerStepThrough] get { return kolonTimeStamp; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonTimeStamp!= value)) { this.RowState = DataRowState.Modified; } kolonTimeStamp = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<byte> KolonTinyInt { [DebuggerStepThrough] get { return kolonTinyInt; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonTinyInt!= value)) { this.RowState = DataRowState.Modified; } kolonTinyInt = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Nullable<Guid> KolonUniqueIdentifier { [DebuggerStepThrough] get { return kolonUniqueIdentifier; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonUniqueIdentifier!= value)) { this.RowState = DataRowState.Modified; } kolonUniqueIdentifier = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public byte[] KolonVarBinary { [DebuggerStepThrough] get { return kolonVarBinary; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonVarBinary!= value)) { this.RowState = DataRowState.Modified; } kolonVarBinary = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public byte[] KolonVarBinaryMax { [DebuggerStepThrough] get { return kolonVarBinaryMax; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonVarBinaryMax!= value)) { this.RowState = DataRowState.Modified; } kolonVarBinaryMax = value; } } [StringLength(50)] [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonVarchar { [DebuggerStepThrough] get { return kolonVarchar; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonVarchar!= value)) { this.RowState = DataRowState.Modified; } kolonVarchar = value; } } [StringLength(-1)] [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonVarcharMax { [DebuggerStepThrough] get { return kolonVarcharMax; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonVarcharMax!= value)) { this.RowState = DataRowState.Modified; } kolonVarcharMax = value; } } [Required] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public string KolonXml { [DebuggerStepThrough] get { return kolonXml; } [DebuggerStepThrough] set { if ((this.RowState == DataRowState.Unchanged) && (kolonXml!= value)) { this.RowState = DataRowState.Modified; } kolonXml = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string OrnekTabloKeyAsString { [DebuggerStepThrough] get { return ornekTabloKey.ToString(); } [DebuggerStepThrough] set { try { Guid _a = new Guid(value); OrnekTabloKey = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"OrnekTabloKey",string.Format(CEVIRI_YAZISI,"OrnekTabloKey","Guid"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonBigIntAsString { [DebuggerStepThrough] get { return kolonBigInt != null ? kolonBigInt.ToString() : ""; } [DebuggerStepThrough] set { try { long _a = Convert.ToInt64(value); KolonBigInt = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonBigInt",string.Format(CEVIRI_YAZISI,"KolonBigInt","long"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonBinaryAsString { [DebuggerStepThrough] get { return kolonBinary != null ? kolonBinary.ToString() : ""; } [DebuggerStepThrough] set { throw new ArgumentException("String'ten byte[] array'e cevirim desteklenmemektedir"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonBitAsString { [DebuggerStepThrough] get { return kolonBit != null ? kolonBit.ToString() : ""; } [DebuggerStepThrough] set { try { bool _a = Convert.ToBoolean(value); KolonBit = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonBit",string.Format(CEVIRI_YAZISI,"KolonBit","bool"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonDateTimeAsString { [DebuggerStepThrough] get { return kolonDateTime != null ? kolonDateTime.ToString() : ""; } [DebuggerStepThrough] set { try { DateTime _a = Convert.ToDateTime(value); KolonDateTime = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonDateTime",string.Format(CEVIRI_YAZISI,"KolonDateTime","DateTime"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonDecimalAsString { [DebuggerStepThrough] get { return kolonDecimal != null ? kolonDecimal.ToString() : ""; } [DebuggerStepThrough] set { try { decimal _a = Convert.ToDecimal(value); KolonDecimal = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonDecimal",string.Format(CEVIRI_YAZISI,"KolonDecimal","decimal"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonFloatAsString { [DebuggerStepThrough] get { return kolonFloat != null ? kolonFloat.ToString() : ""; } [DebuggerStepThrough] set { try { double _a = Convert.ToDouble(value); KolonFloat = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonFloat",string.Format(CEVIRI_YAZISI,"KolonFloat","double"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonImageAsString { [DebuggerStepThrough] get { return kolonImage != null ? kolonImage.ToString() : ""; } [DebuggerStepThrough] set { throw new ArgumentException("String'ten byte[] array'e cevirim desteklenmemektedir"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonIntAsString { [DebuggerStepThrough] get { return kolonInt != null ? kolonInt.ToString() : ""; } [DebuggerStepThrough] set { try { int _a = Convert.ToInt32(value); KolonInt = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonInt",string.Format(CEVIRI_YAZISI,"KolonInt","int"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonMoneyAsString { [DebuggerStepThrough] get { return kolonMoney != null ? kolonMoney.ToString() : ""; } [DebuggerStepThrough] set { try { decimal _a = Convert.ToDecimal(value); KolonMoney = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonMoney",string.Format(CEVIRI_YAZISI,"KolonMoney","decimal"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonNumericAsString { [DebuggerStepThrough] get { return kolonNumeric != null ? kolonNumeric.ToString() : ""; } [DebuggerStepThrough] set { try { decimal _a = Convert.ToDecimal(value); KolonNumeric = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonNumeric",string.Format(CEVIRI_YAZISI,"KolonNumeric","decimal"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonRealAsString { [DebuggerStepThrough] get { return kolonReal != null ? kolonReal.ToString() : ""; } [DebuggerStepThrough] set { try { float _a = Convert.ToSingle(value); KolonReal = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonReal",string.Format(CEVIRI_YAZISI,"KolonReal","float"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonSmallDateTimeAsString { [DebuggerStepThrough] get { return kolonSmallDateTime != null ? kolonSmallDateTime.ToString() : ""; } [DebuggerStepThrough] set { try { DateTime _a = Convert.ToDateTime(value); KolonSmallDateTime = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonSmallDateTime",string.Format(CEVIRI_YAZISI,"KolonSmallDateTime","DateTime"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonSmallIntAsString { [DebuggerStepThrough] get { return kolonSmallInt != null ? kolonSmallInt.ToString() : ""; } [DebuggerStepThrough] set { try { short _a = Convert.ToInt16(value); KolonSmallInt = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonSmallInt",string.Format(CEVIRI_YAZISI,"KolonSmallInt","short"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonSmallMoneyAsString { [DebuggerStepThrough] get { return kolonSmallMoney != null ? kolonSmallMoney.ToString() : ""; } [DebuggerStepThrough] set { try { decimal _a = Convert.ToDecimal(value); KolonSmallMoney = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonSmallMoney",string.Format(CEVIRI_YAZISI,"KolonSmallMoney","decimal"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonSqlVariantAsString { [DebuggerStepThrough] get { return kolonSqlVariant != null ? kolonSqlVariant.ToString() : ""; } [DebuggerStepThrough] set { try { object _a =(object) value; KolonSqlVariant = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonSqlVariant",string.Format(CEVIRI_YAZISI,"KolonSqlVariant","object"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonTimeStampAsString { [DebuggerStepThrough] get { return kolonTimeStamp != null ? kolonTimeStamp.ToString() : ""; } [DebuggerStepThrough] set { throw new ArgumentException("String'ten byte[] array'e cevirim desteklenmemektedir"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonTinyIntAsString { [DebuggerStepThrough] get { return kolonTinyInt != null ? kolonTinyInt.ToString() : ""; } [DebuggerStepThrough] set { try { byte _a = Convert.ToByte(value); KolonTinyInt = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonTinyInt",string.Format(CEVIRI_YAZISI,"KolonTinyInt","byte"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonUniqueIdentifierAsString { [DebuggerStepThrough] get { return kolonUniqueIdentifier != null ? kolonUniqueIdentifier.ToString() : ""; } [DebuggerStepThrough] set { try { Guid _a = new Guid(value); KolonUniqueIdentifier = _a; } catch(Exception) { this.Onaylayici.OnaylayiciListesi.Add(new DaimaBasarisiz(this,"KolonUniqueIdentifier",string.Format(CEVIRI_YAZISI,"KolonUniqueIdentifier","Guid"))); } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonVarBinaryAsString { [DebuggerStepThrough] get { return kolonVarBinary != null ? kolonVarBinary.ToString() : ""; } [DebuggerStepThrough] set { throw new ArgumentException("String'ten byte[] array'e cevirim desteklenmemektedir"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] [XmlIgnore, SoapIgnore] [ScaffoldColumn(false)] public string KolonVarBinaryMaxAsString { [DebuggerStepThrough] get { return kolonVarBinaryMax != null ? kolonVarBinaryMax.ToString() : ""; } [DebuggerStepThrough] set { throw new ArgumentException("String'ten byte[] array'e cevirim desteklenmemektedir"); } } public OrnekTablo ShallowCopy() { OrnekTablo obj = new OrnekTablo(); obj.ornekTabloKey = ornekTabloKey; obj.kolonBigInt = kolonBigInt; obj.kolonBinary = kolonBinary; obj.kolonBit = kolonBit; obj.kolonChar = kolonChar; obj.kolonDateTime = kolonDateTime; obj.kolonDecimal = kolonDecimal; obj.kolonFloat = kolonFloat; obj.kolonImage = kolonImage; obj.kolonInt = kolonInt; obj.kolonMoney = kolonMoney; obj.kolonNchar = kolonNchar; obj.kolonNtext = kolonNtext; obj.kolonNumeric = kolonNumeric; obj.kolonNvarchar = kolonNvarchar; obj.kolonNvarcharMax = kolonNvarcharMax; obj.kolonReal = kolonReal; obj.kolonSmallDateTime = kolonSmallDateTime; obj.kolonSmallInt = kolonSmallInt; obj.kolonSmallMoney = kolonSmallMoney; obj.kolonSqlVariant = kolonSqlVariant; obj.kolonText = kolonText; obj.kolonTimeStamp = kolonTimeStamp; obj.kolonTinyInt = kolonTinyInt; obj.kolonUniqueIdentifier = kolonUniqueIdentifier; obj.kolonVarBinary = kolonVarBinary; obj.kolonVarBinaryMax = kolonVarBinaryMax; obj.kolonVarchar = kolonVarchar; obj.kolonVarcharMax = kolonVarcharMax; obj.kolonXml = kolonXml; return obj; } protected override void OnaylamaListesiniOlusturCodeGeneration() { } public class PropertyIsimleri { public const string OrnekTabloKey = "OrnekTabloKey"; public const string KolonBigInt = "KolonBigInt"; public const string KolonBinary = "KolonBinary"; public const string KolonBit = "KolonBit"; public const string KolonChar = "KolonChar"; public const string KolonDateTime = "KolonDateTime"; public const string KolonDecimal = "KolonDecimal"; public const string KolonFloat = "KolonFloat"; public const string KolonImage = "KolonImage"; public const string KolonInt = "KolonInt"; public const string KolonMoney = "KolonMoney"; public const string KolonNchar = "KolonNChar"; public const string KolonNtext = "KolonNText"; public const string KolonNumeric = "KolonNumeric"; public const string KolonNvarchar = "KolonNVarchar"; public const string KolonNvarcharMax = "KolonNVarcharMax"; public const string KolonReal = "KolonReal"; public const string KolonSmallDateTime = "KolonSmallDateTime"; public const string KolonSmallInt = "KolonSmallInt"; public const string KolonSmallMoney = "KolonSmallMoney"; public const string KolonSqlVariant = "KolonSqlVariant"; public const string KolonText = "KolonText"; public const string KolonTimeStamp = "KolonTimeStamp"; public const string KolonTinyInt = "KolonTinyInt"; public const string KolonUniqueIdentifier = "KolonUniqueIdentifier"; public const string KolonVarBinary = "KolonVarBinary"; public const string KolonVarBinaryMax = "KolonVarBinaryMax"; public const string KolonVarchar = "KolonVarchar"; public const string KolonVarcharMax = "KolonVarcharMax"; public const string KolonXml = "KolonXml"; } } }
using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Demo.SpaceGame.Entities { public interface IEntityManager { T AddEntity<T>(T entity) where T : Entity; } public class EntityManager : IEntityManager { private readonly List<Entity> _entities; public IEnumerable<Entity> Entities => _entities; public EntityManager() { _entities = new List<Entity>(); } public T AddEntity<T>(T entity) where T : Entity { _entities.Add(entity); return entity; } public void Update(GameTime gameTime) { foreach (var entity in _entities.Where(e => !e.IsDestroyed)) { entity.Update(gameTime); } _entities.RemoveAll(e => e.IsDestroyed); } public void Draw(SpriteBatch spriteBatch) { foreach (var entity in _entities.Where(e => !e.IsDestroyed)) { entity.Draw(spriteBatch); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Hand.cs" company=""> // // </copyright> // <summary> // The hand. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Poker { using System.Collections.Generic; /// <summary> /// The hand. /// </summary> public class Hand : IHand { /// <summary> /// Initializes a new instance of the <see cref="Hand"/> class. /// </summary> /// <param name="cards"> /// The cards. /// </param> public Hand(IList<ICard> cards) { this.Cards = cards; } /// <summary> /// Gets the cards. /// </summary>t public IList<ICard> Cards { get; private set; } /// <summary> /// The to string. /// </summary> /// <returns> /// The <see cref="string"/>. /// </returns> public override string ToString() { return string.Join(" ", this.Cards); } } }
using System; namespace IntegradorZeusPDV.MODEL.ClassesPDV { public class MovimentoFiscal { public decimal IDMovimentoFiscal { get; set; } public decimal Serie { get; set; } public byte[] XMLEnvio { get; set; } public byte[] XMLRetorno { get; set; } public decimal Emitida { get; set; } public decimal Cancelada { get; set; } public DateTime DataEmissao { get; set; } public decimal? IDVenda { get; set; } public string Chave { get; set; } public decimal? cStat { get; set; } public string xMotivo { get; set; } public DateTime? DataRecebimento { get; set; } public decimal Contingencia { get; set; } public decimal Numero { get; set; } public decimal TipoDocumento { get; set; } public decimal Ambiente { get; set; } public decimal? IDNFe { get; set; } public MovimentoFiscal() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ITDepartment.DataAccess; namespace ITDepartment.Utilities { public static class SessionHelper { public static string GetUsername() { return HttpContext.Current.Session["UserName"]?.ToString(); } public static string GetRole() { return HttpContext.Current.Session["Role"]?.ToString(); } public static bool CanView(string resourceName) { ITDepartmentEntities db = new ITDepartmentEntities(); var resource = db.Resource.FirstOrDefault(x => x.ResourceName == resourceName); if (resource == null) return false; var roleName = GetRole(); var resourceRole = db.ResourceRole.FirstOrDefault(x => x.ResourceId == resource.ResourceId && x.RoleId == db.Role.FirstOrDefault(y => y.RoleName == roleName).RoleId); return resourceRole == null ? false : resourceRole.CanView; } } }
using System; namespace NeuralNetwork { public static class Activations { static double SigmoidActivation(double x) { return 1 / (1 + Math.Pow(Math.E, -x)); } static double SigmoidDerivative(double x){ return x * (1 - x); } static double BinaryStepActivation(double x) { return x < 0 ? 0 : 1; } public static ActivationFunc Sigmoid = new ActivationFunc(SigmoidActivation, SigmoidDerivative); } }
 namespace VideoSite.Web.Controllers { using System.Web.Mvc; using VideoSite.Services.IServices; using System.Collections; using System.Linq; /// <summary> /// User Controller /// </summary> public class UserController : Controller { /// <summary> /// The m_ user service /// </summary> protected IUserService m_UserService; /// <summary> /// Initializes a new instance of the <see cref="UserController"/> class. /// </summary> /// <param name="UserService">The user service.</param> public UserController(IUserService UserService) { m_UserService = UserService; } /// <summary> /// Indexes this instance. /// GET: /User/Index /// </summary> /// <returns></returns> public ActionResult Index() { if (Request.IsAjaxRequest()) { IEnumerable list = from user in m_UserService.List() select new { user.UserId, user.Username,user.Password,user.UserInfoId,user.Extra }; return Json(list); } else { return View(m_UserService.List()); } } /// <summary> /// Detailses the specified id. /// GET: /User/Details/5 /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public ActionResult Details(int id) { if (Request.IsAjaxRequest()) { return View("JSDetails.html", m_UserService.GetUserById(id)); } else { return View(m_UserService.GetUserById(id)); } } /// <summary> /// Creates this instance. /// GET: /User/Create /// </summary> /// <returns></returns> public ActionResult Create() { if (Request.IsAjaxRequest()) { return View("JSCreate.html"); } else { return View(); } } /// <summary> /// Creates the specified collection. /// POST: /User/Create /// </summary> /// <param name="collection">The collection.</param> /// <returns></returns> [HttpPost] public ActionResult Create(FormCollection collection) { return RedirectToAction("Index"); } /// <summary> /// Edits the specified id. /// GET: /User/Edit/5 /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public ActionResult Edit(int id) { if (Request.IsAjaxRequest()) { return View("JSCreate.html", m_UserService.GetUserById(id)); } else { return View(m_UserService.GetUserById(id)); } } /// <summary> /// Edits the specified id. /// POST: /User/Edit/5 /// </summary> /// <param name="id">The id.</param> /// <param name="collection">The collection.</param> /// <returns></returns> [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } /// <summary> /// Deletes the specified id. /// GET: /User/Delete/5 /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public ActionResult Delete(int id) { return View(); } /// <summary> /// Deletes the specified id. /// POST: /User/Delete/5 /// </summary> /// <param name="id">The id.</param> /// <param name="collection">The collection.</param> /// <returns></returns> [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } } }
// -------------------------------- // <copyright file="CarModelManagerTest.cs" > // © 2013 KarzPlus Inc. // </copyright> // <author>JDuverge</author> // <summary> // CarModel Test Layer Object. // </summary> // --------------------------------- using System; using System.Collections.Generic; using System.Linq; using KarzPlus.Business; using KarzPlus.Entities; using KarzPlus.Entities.ExtensionMethods; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace KarzPlus.Tests { /// <summary> ///This is a test class for CarModelManagerTest and is intended ///to contain all CarModelManagerTest Unit Tests ///</summary> [TestClass] public class CarModelManagerTest { private CarModel CarModelTestObject { get; set; } [TestInitialize] public void CreateTestObject() { int carMakeId = default(int); string errorMessage; Random rand = new Random(); List<CarMake> carMakes = CarMakeManager.LoadAll().ToList(); if (carMakes.SafeAny()) { carMakeId = carMakes.First().MakeId.GetValueOrDefault(); } else { CarMake carMake = new CarMake { Name = string.Format("TestCarMake_{0}", rand.Next(1, 1000)), Manufacturer = "TestManufacturer" }; CarMakeManager.Save(carMake, out errorMessage); if (carMake.MakeId.HasValue) { carMakeId = carMake.MakeId.Value; } } CarModelTestObject = new CarModel { ModelId = null, MakeId = carMakeId, Name = string.Format("TestCarModel_{0}", rand.Next(1, 1000)) }; CarModelManager.Save(CarModelTestObject, out errorMessage); } [TestCleanup] public void DestroyTestObject() { if (CarModelTestObject != null && CarModelTestObject.ModelId.HasValue) { CarModelManager.HardDelete(CarModelTestObject.ModelId.Value); } } /// <summary> ///A test for Load ///</summary> [TestMethod] public void CarModelLoadTest() { Assert.IsNotNull(CarModelTestObject, "Test object was null"); Assert.IsNotNull(CarModelTestObject.ModelId, "Test object was not saved successfully"); CarModel entity = CarModelManager.Load(CarModelTestObject.ModelId.Value); Assert.IsNotNull(entity, "CarModel object was null"); Assert.IsTrue(entity.MakeId == CarModelTestObject.MakeId, "MakeId was not as expected"); Assert.IsTrue(entity.Name.SafeEquals(CarModelTestObject.Name), "Name was not as expected"); } /// <summary> ///A test for Save ///</summary> [TestMethod] public void CarModelSaveTest() { Assert.IsNotNull(CarModelTestObject, "Test object was null"); Assert.IsNotNull(CarModelTestObject.ModelId, "Test object was not saved successfully"); CarModel entity = CarModelManager.Load(CarModelTestObject.ModelId.Value); Assert.IsNotNull(entity, "CarModel object was null"); string newModel = string.Format("Not_{0}", entity.Name); entity.Name = newModel; string errorMessage; CarModelManager.Save(entity, out errorMessage); Assert.IsTrue(errorMessage.IsNullOrWhiteSpace(), "Error while saving object"); Assert.IsNotNull(entity.ModelId, "Entity doesn't have an ID"); CarModel newEntity = CarModelManager.Load(entity.ModelId.Value); Assert.IsNotNull(newEntity, "Could not load new entity"); Assert.IsTrue(newEntity.Name.SafeEquals(newModel), "Name edit was not persisted to data store"); } /// <summary> ///A test for Validate ///</summary> [TestMethod] public void CarModelValidateTest() { Assert.IsNotNull(CarModelTestObject, "Test object was null"); string errorMessage; bool valid = CarModelManager.Validate(CarModelTestObject, out errorMessage); Assert.IsTrue(valid, "CarModel was not valid when it should have been"); Assert.IsTrue(errorMessage.IsNullOrWhiteSpace(), "Errors found when there shouldn't have been any"); string name = CarModelTestObject.Name; int makeId = CarModelTestObject.MakeId; CarModelTestObject.Name = string.Empty; CarModelTestObject.MakeId = -1; valid = CarModelManager.Validate(CarModelTestObject, out errorMessage); Assert.IsFalse(valid, "CarModel was valid when it shouldn't have been"); Assert.IsTrue(errorMessage.HasValue(), "Errors not found when there should have been any"); Assert.IsTrue(errorMessage.Contains("MakeId must be valid", StringComparison.InvariantCultureIgnoreCase)); Assert.IsTrue(errorMessage.Contains("Name is required", StringComparison.InvariantCultureIgnoreCase)); CarModel newCarModel = new CarModel { MakeId = makeId, Name = name }; valid = CarModelManager.Validate(newCarModel, out errorMessage); Assert.IsFalse(valid, "CarModel was valid when it shouldn't have been"); Assert.IsTrue(errorMessage.HasValue(), "Errors not found when there should have been any"); Assert.IsTrue(errorMessage.Contains("Cannot have multiple car models with the same name from the same make", StringComparison.InvariantCultureIgnoreCase)); } } }
// Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace NtApiDotNet { /// <summary> /// Class representing a NT File Mailslot client object /// </summary> public class NtMailslotFile : NtFile { #region Constructors internal NtMailslotFile(SafeKernelObjectHandle handle, IoStatus io_status) : base(handle, io_status) { } #endregion #region Private Members private NtResult<FileMailslotQueryInformation> QueryInfo(bool throw_on_error) { return Query<FileMailslotQueryInformation>(FileInformationClass.FileMailslotQueryInformation, default, throw_on_error); } #endregion #region Public Methods /// <summary> /// Set the mailslot read timeout. /// </summary> /// <param name="timeout">The timeout to set.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT Status code.</returns> public NtStatus SetReadTimeout(NtWaitTimeout timeout, bool throw_on_error) { LargeInteger read_timeout = timeout?.Timeout ?? new LargeInteger(-1); FileMailslotSetInformation set_info = new FileMailslotSetInformation() { ReadTimeout = read_timeout.ToStruct() }; return Set(FileInformationClass.FileMailslotSetInformation, set_info, throw_on_error); } /// <summary> /// Peek on the current status of the Mailslot. /// </summary> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The peek status.</returns> public NtResult<FileMailslotPeekBuffer> Peek(bool throw_on_error) { using (var buffer = new SafeStructureInOutBuffer<FileMailslotPeekBuffer>()) { return FsControl(NtWellKnownIoControlCodes.FSCTL_MAILSLOT_PEEK, buffer, buffer, throw_on_error).Map(_ => buffer.Result); } } /// <summary> /// Peek on the current status of the Mailslot. /// </summary> /// <returns>The peek status.</returns> public FileMailslotPeekBuffer Peek() { return Peek(true).Result; } #endregion #region Public Properties /// <summary> /// Get or set the Read Timeout. /// </summary> public NtWaitTimeout ReadTimeout { get => QueryInfo(true).Result.ReadTimeout.ToTimeout(); set => SetReadTimeout(value, true); } /// <summary> /// Get maximum message size. /// </summary> public int MaximumMessageSize => QueryInfo(true).Result.MaximumMessageSize; /// <summary> /// Get mailslot quota. /// </summary> public int MailslotQuota => QueryInfo(true).Result.MailslotQuota; /// <summary> /// Get next message size. /// </summary> public int NextMessageSize => QueryInfo(true).Result.NextMessageSize; /// <summary> /// Get messages available. /// </summary> public int MessagesAvailable => QueryInfo(true).Result.MessagesAvailable; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpheroProject { class RollState { public RollState() { Heading = 0; Speed = 1f; } public int Heading { get; set; } public float Speed { get; set; } public void Flip() { if (Heading == 180) Heading = 0; else Heading = 180; } } }
using IdentityServer4.EntityFramework.DbContexts; using IdentityServer4.EntityFramework.Mappers; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Promact.Oauth.Server.Configuration.DefaultAPIResource; using Promact.Oauth.Server.Configuration.DefaultIdentityResource; using System.Linq; namespace Promact.Oauth.Server.Seed { public class IdentityServerInitialize { #region Public Method /// <summary> /// Method used to migrate PersistedGrantDbContext and ConfigurationDbContext of IdentityServer /// and store predefined value of API Resource and Identity Resource /// </summary> /// <param name="app">IApplicationBuilder</param> /// <param name="defaultApiResource">IDefaultApiResources</param> /// <param name="defaultIdentityResource">IDefaultIdentityResources</param> public void InitializeDatabaseForPreDefinedAPIResourceAndIdentityResources(IApplicationBuilder app, IDefaultApiResources defaultApiResource, IDefaultIdentityResources defaultIdentityResource) { using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate(); var configurationDbContext = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>(); configurationDbContext.Database.Migrate(); //Adding Predefined value of API Resource if (!configurationDbContext.ApiResources.Any()) { foreach (var resource in defaultApiResource.GetDefaultApiResource()) { configurationDbContext.ApiResources.Add(resource.ToEntity()); } configurationDbContext.SaveChanges(); } // Adding Predefined value of Identity Resource if (!configurationDbContext.IdentityResources.Any()) { foreach (var resource in defaultIdentityResource.GetIdentityResources()) { configurationDbContext.IdentityResources.Add(resource.ToEntity()); } configurationDbContext.SaveChanges(); } } } #endregion } }
namespace Plus.Communication.Packets.Outgoing.Rooms.Furni.RentableSpaces { public class RentableSpaceComposer : MessageComposer { public RentableSpaceComposer() : base(ServerPacketHeader.RentableSpaceMessageComposer) { } public override void Compose(ServerPacket packet) { packet.WriteBoolean(true); //Is rented y/n packet.WriteInteger(-1); //No fucking clue packet.WriteInteger(-1); //No fucking clue packet.WriteString("Tyler-Retros"); //Username of who owns. packet.WriteInteger(360); //Time to expire. packet.WriteInteger(-1); //No fucking clue } } }
using System; using System.Collections.Generic; using System.Text; namespace appMarsRovers { public class MesetaMarteBE { private int limiteX; public int LimiteX { get { return limiteX; } set { limiteX = value; } } private int limiteY; public int LimiteY { get { return limiteY; } set { limiteY = value; } } public MesetaMarteBE(int pLimiteX, int pLimiteY) { limiteX = pLimiteX; limiteY = pLimiteY; } public bool ValorX_FueraDeRango(int pValorX) { return pValorX > limiteX; } public bool ValorY_FueraDeRango(int pValorY) { return pValorY > limiteY; } } }
namespace OmniGui.VisualStates { public class Setter { public void Apply() { Target.Apply(Value); } public SetterTarget Target { get; set; } public object Value { get; set; } } }
#region Header /* This file is part of NDoctor. NDoctor 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. NDoctor 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 NDoctor. If not, see <http://www.gnu.org/licenses/>. */ #endregion Header namespace Probel.NDoctor.Domain.Components { using System; using System.Collections.Generic; using Castle.DynamicProxy; using log4net; using Probel.NDoctor.Domain.Components.AuthorisationPolicies; using Probel.NDoctor.Domain.Components.Interceptors; using Probel.NDoctor.Domain.DAL.Components; using Probel.NDoctor.Domain.DAL.Remote; using Probel.NDoctor.Domain.DTO.Components; using Probel.NDoctor.Domain.DTO.Exceptions; using Probel.NDoctor.Domain.DTO.Objects; using Probel.NDoctor.Domain.DTO.Remote; using StructureMap; /// <summary> /// Give an instance of a component and add dynamic interceptors to the call of every methods /// of the components /// </summary> public class ComponentFactory { #region Fields /// <summary> /// First instanciation into the static ctor because it needs the StructureMap configuration before. /// </summary> private static readonly AuthorisationInterceptor AuthorisationInterceptor; private static readonly ProxyGenerator Generator = new ProxyGenerator(new PersistentProxyBuilder()); private readonly bool BenchmarkEnabled = false; private readonly uint ExecutionTimeThreshold; private readonly bool IsUnderTest = false; private readonly ILog Logger = LogManager.GetLogger(typeof(ComponentFactory)); #endregion Fields #region Constructors static ComponentFactory() { ObjectFactory.Configure(x => { //Administration plugin x.For<IAdministrationComponent>().Add<AdministrationComponent>(); x.SelectConstructor<AdministrationComponent>(() => new AdministrationComponent()); //BmiRecord plugin x.For<IBmiComponent>().Add<BmiComponent>(); x.SelectConstructor<BmiComponent>(() => new BmiComponent()); //DbConvert plugin x.For<IImportComponent>().Add<ImportComponent>(); x.SelectConstructor<ImportComponent>(() => new ImportComponent()); //Debug plugin x.For<ISqlComponent>().Add<SqlComponent>(); x.SelectConstructor<SqlComponent>(() => new SqlComponent()); ; //Family manager plugin x.For<IFamilyComponent>().Add<FamilyComponent>(); x.SelectConstructor<FamilyComponent>(() => new FamilyComponent()); //Medical record plugin x.For<IMedicalRecordComponent>().Add<MedicalRecordComponent>(); x.SelectConstructor<MedicalRecordComponent>(() => new MedicalRecordComponent()); //Meeting manager plugin x.For<ICalendarComponent>().Add<CalendarComponent>(); x.SelectConstructor<CalendarComponent>(() => new CalendarComponent()); //Pathology plugin x.For<IPathologyComponent>().Add<PathologyComponent>(); x.SelectConstructor<PathologyComponent>(() => new PathologyComponent()); //Patient data plugin x.For<IPatientDataComponent>().Add<PatientDataComponent>(); x.SelectConstructor<PatientDataComponent>(() => new PatientDataComponent()); //Patient session plugin x.For<IPatientSessionComponent>().Add<PatientSessionComponent>(); x.SelectConstructor<PatientSessionComponent>(() => new PatientSessionComponent()); //Picture manager plugin x.For<IPictureComponent>().Add<PictureComponent>(); x.SelectConstructor<PictureComponent>(() => new PictureComponent()); //Prescription manager plugin x.For<IPrescriptionComponent>().Add<PrescriptionComponent>(); x.SelectConstructor<PrescriptionComponent>(() => new PrescriptionComponent()); //User session manager x.For<IUserSessionComponent>().Add<UserSessionComponent>(); x.SelectConstructor<UserSessionComponent>(() => new UserSessionComponent()); //Authorisation manager x.For<IAuthorisationComponent>().Add<AuthorisationComponent>(); x.SelectConstructor<AuthorisationComponent>(() => new AuthorisationComponent()); //Application statistics manager x.For<IApplicationStatisticsComponent>().Add<ApplicationStatisticsComponent>(); x.SelectConstructor<ApplicationStatisticsComponent>(() => new ApplicationStatisticsComponent()); //Data statistics manager x.For<IDataStatisticsComponent>().Add<DataStatisticsComponent>(); x.SelectConstructor<DataStatisticsComponent>(() => new DataStatisticsComponent()); //Database settings x.For<IDbSettingsComponent>().Add<DbSettingsComponent>(); x.SelectConstructor<DbSettingsComponent>(() => new DbSettingsComponent()); //Authorisation policies x.For<IAuthorisationPolicy>().Add<AuthorisationPolicy>(); //Check remotly for new versions x.For<IVersionNotifyer>().Add<VersionNotifyer>(); x.SelectConstructor<VersionNotifyer>(() => new RemoteService().NewVersionNotifyer()); //Data manager x.For<IRescueToolsComponent>().Add<RescueToolsComponent>(); x.SelectConstructor<RescueToolsComponent>(() => new RescueToolsComponent()); }); AuthorisationInterceptor = new AuthorisationInterceptor(); } /// <summary> /// Initializes a new instance of the <see cref="ComponentFactory"/> class. /// </summary> /// <param name="benchmarkEnabled">if set to <c>true</c> component loggin is enabled.</param> public ComponentFactory(bool benchmarkEnabled, uint executionTimeThreshold) : this(benchmarkEnabled, executionTimeThreshold, false) { } private ComponentFactory(bool benchmarkEnabled, uint executionTimeThreshold, bool isUnderTest) { this.BenchmarkEnabled = benchmarkEnabled; this.ExecutionTimeThreshold = executionTimeThreshold; this.IsUnderTest = isUnderTest; } #endregion Constructors #region Methods /// <summary> /// Gets a factory ready for test. That's only the Authorisation proxy will be hooked to the instance. /// </summary> public static ComponentFactory TestInstance(bool benchmarkEnabled = false) { return new ComponentFactory(benchmarkEnabled, int.MaxValue, true); } /// <summary> /// Connects the specified user into the application. /// </summary> /// <param name="user">The user.</param> public void ConnectUser(SecurityUserDto user) { AuthorisationInterceptor.User = user; } /// <summary> /// Gets hte configured instance for the specified interface. /// </summary> /// <typeparam name="T">The IoC Container will search for an instance of that specified interface</typeparam> /// <returns>An instance that imlements the specified interface</returns> public T GetInstance<T>() where T : class { try { T instance = ObjectFactory.GetInstance<T>(); if (instance is BaseComponent) { return Generator.CreateInterfaceProxyWithTarget<T>(instance, this.GetInterceptors()); } else { return instance; } } catch (Exception ex) { this.Logger.Warn("An error occured when instanciating a component", ex); throw new ComponentException(ex); } } /// <summary> /// Gets hte configured instance that will be used for unit tests for the specified interface. /// This instance will have only one dynamic proxy of type <see cref="TransactionInterceptor"/>. /// Using this /// </summary> /// <typeparam name="T">The IoC Container will search for an instance of that specified interface</typeparam> /// <returns>An instance that imlements the specified interface</returns> private IInterceptor[] GetInterceptors() { var interceptors = new List<IInterceptor>(); if (this.BenchmarkEnabled) { interceptors.Add(new BenchmarkInterceptor(this.ExecutionTimeThreshold)); } if (!this.IsUnderTest) { interceptors.Add(new TransactionInterceptor()); interceptors.Add(new LogInterceptor()); } interceptors.Add(AuthorisationInterceptor); return interceptors.ToArray(); } #endregion Methods } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Scripts.GameLogic.EnemySystem { public class TilePos { public int x; public int y; public TilePos(int x, int y) { this.x = x; this.y = y; } public override bool Equals(object obj) { if (!(obj is TilePos)) return false; TilePos other = (TilePos)obj; return x == other.x && y == other.y; } public override int GetHashCode() { return base.GetHashCode(); } } }
namespace Dealership.Engine.Factories { using Contracts.Commands; using Contracts.Factories; using Engine.Commands; public class CommandFactory : ICommandFactory { public ICommand CreateCommands() { var registerUser = new RegisterUser(); var login = new Login(); var logout = new Logout(); var addVehicle = new AddVehicle(); var removeVehicle = new RemoveVehicle(); var addComment = new AddComment(); var removeComment = new RemoveComment(); var showUsers = new ShowUsers(); var showVehicles = new ShowVehicles(); registerUser.SetSuccessor(login); login.SetSuccessor(logout); logout.SetSuccessor(addVehicle); addVehicle.SetSuccessor(removeVehicle); removeVehicle.SetSuccessor(addComment); addComment.SetSuccessor(removeComment); removeComment.SetSuccessor(showUsers); showUsers.SetSuccessor(showVehicles); return registerUser; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Service.Interface; using DataObject; using DataAccessLayer; namespace Service.Implements { public class BoPhanService:IBoPhan { public int ThemBoPhan(BoPhan bp) { throw new NotImplementedException(); } public int CapNhatBoPhan(BoPhan bp) { throw new NotImplementedException(); } public int XoaBoPhan(int maBP) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Person { public class Employer : INotifyPropertyChanged { private string surname; private string name; private string patronymic; public int salary; private Company company; public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName]string prop = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); } public string Surname { get { return surname; } set { if (surname != value) { surname = value; OnPropertyChanged(nameof(Surname)); } } } public string Name { get { return name; } set { if (name != value) { name = value; OnPropertyChanged(nameof(Name)); } } } public string Patronymic { get { return patronymic; } set { if (patronymic != value) { patronymic = value; OnPropertyChanged(nameof(Surname)); } } } public int Salary { get { return salary; } set { if (salary != value) { salary = value; OnPropertyChanged(nameof(Salary)); } } } public Company Company { get { return company; } set { if (company != value) { company = value; OnPropertyChanged(nameof(Company)); } } } public override string ToString() { return $"{Surname}, ${Name}, ${Patronymic}, ${Company}"; } public Employer() { Company = new Company(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainManager : MonoBehaviour { [SerializeField] AudioClip ButtonClickSound; public void OnClickStart() { SoundManager.instance.SFXPlay("ButtonClick", ButtonClickSound); SceneManager.LoadScene("Stage1"); } public void OnClickExit() { SoundManager.instance.SFXPlay("ButtonClick", ButtonClickSound); Application.Quit(); } }
using App.Entity.AttibutesProperty; using System.ComponentModel; using System.Data.Linq.Mapping; namespace App.Entity { [Table(Name = "MeasurementUnit")] public class MeasurementUnitBE { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> [SettingProperties( Label: "ID", CausesValidation: true, DefaultValue: 0, IsAutoIncrement: true, IsPrimaryKey: true, IsReferenceKey: false, PropertyName: "ID", ReferenceColumn: "", ReferenceTable: "", Regex: @"[\d]", IsUnique: true, Required: true, TypeColumn: typeof(int))] [Column(Name = "ID")] [Description("PRIMARY KEY")] public int ID { get; set; } /// <summary> /// Gets or sets the name. /// </summary> /// <value> /// The name. /// </value> [SettingProperties( Label: "Nombre", CausesValidation: true, DefaultValue: "", MaxSize: 50, PropertyName: "Name", Regex: @"^[a-zA-Z0-9()]{3,20}$", Required: true, IsUnique: true, TypeColumn: typeof(string))] [Column(Name = "Name")] public string Name { get; set; } } }
using Sandbox; using Sandbox.UI; using Sandbox.UI.Construct; using System.Linq; public class BallsAmount : Panel { public Label Label; public BallsAmount() { Label = Add.Label( "", "value" ); } public override void Tick() { Label.Text = $"Count: {Entity.All.OfType<Prop>().Where( x => x.GetModelName() == "models/citizen_props/beachball.vmdl" ).Count()}"; } }
using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using AutoMapper; using BPiaoBao.AppServices.Contracts.DomesticTicket; using BPiaoBao.AppServices.DataContracts; using BPiaoBao.AppServices.DataContracts.DomesticTicket; using BPiaoBao.Common; using BPiaoBao.Common.Enums; using BPiaoBao.DomesticTicket.Domain.Models.Orders; using BPiaoBao.DomesticTicket.Domain.Models.TravelPaper; using BPiaoBao.DomesticTicket.Domain.Services; using BPiaoBao.SystemSetting.Domain.Models.Businessmen; using BPiaoBao.SystemSetting.Domain.Services.Auth; using JoveZhao.Framework; using JoveZhao.Framework.DDD; using StructureMap; namespace BPiaoBao.AppServices.DomesticTicket { public class TravelPaperService : ITravelPaperService { IUnitOfWork unitOfWork = ObjectFactory.GetNamedInstance<IUnitOfWork>(EnumModule.DomesticTicket.ToString()); IUnitOfWorkRepository unitOfWorkRepository = ObjectFactory.GetNamedInstance<IUnitOfWorkRepository>(EnumModule.DomesticTicket.ToString()); ITravelGrantRecordRepository m_travelGrantRecordRepository; ITravelPaperRepository m_travelPaperRepository; IBusinessmanRepository m_businessmanRepository; IOrderRepository orderRepository; IAfterSaleOrderRepository AfterSaleorderRepository; CurrentUserInfo currentUser; public TravelPaperService(ITravelGrantRecordRepository travelGrantRecordRepository, ITravelPaperRepository travelPaperRepository, IOrderRepository orderRepository, IAfterSaleOrderRepository afterSaleorderRepository, IBusinessmanRepository businessmanRepository) { this.m_travelGrantRecordRepository = travelGrantRecordRepository; this.m_travelPaperRepository = travelPaperRepository; this.m_businessmanRepository = businessmanRepository; this.orderRepository = orderRepository; this.AfterSaleorderRepository = afterSaleorderRepository; currentUser = AuthManager.GetCurrentUser(); } /// <summary> /// 分配行程单 /// </summary> /// <param name="travelPaper"></param> [ExtOperationInterceptor("分配行程单")] public int AddTravelPaper(string buyerBusinessman, string startTripNumber, string endTripNumber, string useOffice, string iataCode, string ticketCompanyName, string tripRemark) { string BusinessmanCode = currentUser.Code; string BusinessmanName = currentUser.BusinessmanName; int dataCount = -1; string strMsg = string.Empty; string useBusinessmanCode = string.Empty; string useBusinessmanName = string.Empty; if (string.IsNullOrEmpty(buyerBusinessman)) { strMsg = "分配商户名称或者商户号不能为空!"; } else if (string.IsNullOrEmpty(BusinessmanCode)) { strMsg = "供应商户号不能为空!"; } else if (string.IsNullOrEmpty(BusinessmanName)) { strMsg = "供应商户号不能为空!"; } else if (string.IsNullOrEmpty(startTripNumber) || string.IsNullOrEmpty(endTripNumber) || startTripNumber.Trim().Length != 10 || endTripNumber.Trim().Length != 10 ) { strMsg = "行程单号段数据不完整!"; } else if (string.IsNullOrEmpty(useOffice)) { strMsg = "行程单号终端号不能为空!"; } else if (string.IsNullOrEmpty(iataCode)) { strMsg = "航协号不能为空!"; } else if (string.IsNullOrEmpty(ticketCompanyName)) { strMsg = "填开单位不能为空!"; } else { if (!string.IsNullOrEmpty(startTripNumber) && !string.IsNullOrEmpty(endTripNumber)) { int start = int.Parse(startTripNumber.Substring(6, 4)); int end = int.Parse(endTripNumber.Substring(6, 4)); if (start > end) { strMsg = "行程单号段范围有误!"; } } } //判断商户号是否存在 Businessman businessman = this.m_businessmanRepository.FindAll(p => p.Code == buyerBusinessman || p.Name == buyerBusinessman).FirstOrDefault(); if (businessman == null) { strMsg = "分配商户号或者商户名称不存在!"; } else { useBusinessmanCode = businessman.Code; useBusinessmanName = businessman.Name; } //useBusinessmanCode = "caigou";//businessman.Code; //useBusinessmanName = "采购";//businessman.Name; if (string.IsNullOrEmpty(useBusinessmanCode)) { strMsg = "分配商户号或者商户名称不存在!"; } if (string.IsNullOrEmpty(strMsg)) { string StartCode = startTripNumber.Substring(0, 6); string start = startTripNumber.Substring(6, 4); string end = endTripNumber.Substring(6, 4); tripRemark = tripRemark.Replace("'", ""); //分配行程单 dataCount = unitOfWorkRepository.ExecuteCommand( "EXEC [dbo].[TravelPaperImport] @p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11,@p12 ", "0", StartCode, start, end, useOffice, iataCode, ticketCompanyName, BusinessmanCode, BusinessmanName, useBusinessmanCode, useBusinessmanName, tripRemark, "" ); if (dataCount > 0) { TravelGrantRecord travelGrantRecord = new TravelGrantRecord(); travelGrantRecord.BusinessmanCode = BusinessmanCode; travelGrantRecord.BusinessmanName = BusinessmanName; travelGrantRecord.UseBusinessmanCode = useBusinessmanCode; travelGrantRecord.UseBusinessmanName = useBusinessmanName; travelGrantRecord.GrantTime = System.DateTime.Now; travelGrantRecord.Office = useOffice; travelGrantRecord.TripCount = int.Parse(end) - int.Parse(start) + 1; travelGrantRecord.TripScope = startTripNumber + "-" + endTripNumber; travelGrantRecord.TripRemark = tripRemark; //添加发放记录 unitOfWorkRepository.PersistCreationOf(travelGrantRecord); unitOfWork.Commit(); } } if (!string.IsNullOrEmpty(strMsg)) { throw new OrderCommException(strMsg); } return dataCount; } /// <summary> /// 查询可用行程单号 /// </summary> /// <param name="buyBusinessmanCode"></param> /// <returns></returns> [ExtOperationInterceptor("查询可用行程单号")] public DataPack<TravelPaperDto> FindUseTravelPaperDto(string buyBusinessmanCode) { var result = m_travelPaperRepository.FindAll(p => p.UseBusinessmanCode.Trim() == buyBusinessmanCode.Trim()); result = result.Where(p => p.TripStatus == EnumTripStatus.NoUsed || p.TripStatus == EnumTripStatus.BlankRecoveryUsed); List<TravelPaper> TravelPaperList = result.ToList(); DataPack<TravelPaperDto> data = new DataPack<TravelPaperDto>(); data.TotalCount = TravelPaperList.Count(); data.List = Mapper.Map<List<TravelPaper>, List<TravelPaperDto>>(TravelPaperList); return data; } /// <summary> /// 查询行程单详情 /// </summary> /// <returns></returns> [ExtOperationInterceptor("查询行程单详情")] public DataPack<TravelPaperDto> FindTravelPaper(string buyBusinessmanCode, string buyBusinessmanName, string useOffice, string startTripNumber, string endTripNumber, string startTicketNumber, string endTicketNumber, DateTime? startCreateTime, DateTime? endCreateTime, DateTime? startVoidTime, DateTime? endVoidTime, DateTime? startGrantTime, DateTime? endGrantTime, DateTime? startRecoveryTime, DateTime? endRecoveryTime, string PageSource, int? tripStatus, int pageIndex, int pageSize, bool isPager = true, int?[] tripStatuss = null, string OrderId = "" ) { string BusinessmanCode = string.Empty; StringBuilder sbSqlWhere = new StringBuilder(); if (tripStatuss == null) { BusinessmanCode = currentUser.Code; //"111";// sbSqlWhere.AppendFormat(" and BusinessmanCode='{0}' ", BusinessmanCode); //采购商户号 if (!string.IsNullOrEmpty(buyBusinessmanCode)) { sbSqlWhere.AppendFormat(" and UseBusinessmanCode='{0}' ", buyBusinessmanCode.Trim()); } } else { //采购商户号 if (!string.IsNullOrEmpty(currentUser.Code)) { sbSqlWhere.AppendFormat(" and UseBusinessmanCode='{0}' ", currentUser.Code.Trim()); } } //采购商户名 if (!string.IsNullOrEmpty(buyBusinessmanName)) { sbSqlWhere.AppendFormat(" and UseBusinessmanName='{0}' ", buyBusinessmanName.Trim()); } //office if (!string.IsNullOrEmpty(useOffice)) { sbSqlWhere.AppendFormat(" and UseOffice='{0}' ", useOffice.Trim()); } ////票号段 if (!string.IsNullOrEmpty(startTicketNumber) && !string.IsNullOrEmpty(endTicketNumber)) { startTicketNumber = startTicketNumber.Replace("-", "").Replace("\'", "").Trim(); endTicketNumber = endTicketNumber.Replace("-", "").Replace("\'", "").Trim(); sbSqlWhere.AppendFormat(" and TicketNumber between '{0}' and '{1}' ", startTicketNumber.Replace("'", ""), endTicketNumber.Replace("'", "")); } if (!string.IsNullOrEmpty(startTripNumber) && !string.IsNullOrEmpty(endTripNumber)) { //行程单号段 sbSqlWhere.AppendFormat(" and TripNumber between '{0}' and '{1}' ", startTripNumber.Replace("'", "").Trim(), endTripNumber.Replace("'", "").Trim()); } //行程单状态 if (PageSource == "black")//来源空白行程单 { if (tripStatus != null && tripStatus.HasValue && tripStatus.Value != -1) { sbSqlWhere.AppendFormat(" and TripStatus ={0} ", tripStatus.Value); } else { sbSqlWhere.AppendFormat(" and TripStatus in(3,4) "); } } else { if (tripStatus != null && tripStatus.HasValue && tripStatus.Value != -1) { sbSqlWhere.AppendFormat(" and TripStatus ={0} ", tripStatus.Value); } } if (startCreateTime != null && startCreateTime.HasValue) { sbSqlWhere.AppendFormat(" and PrintTime >='{0}' ", startCreateTime.Value.ToString("yyyy-MM-dd")); } if (endCreateTime != null && endCreateTime.HasValue) { sbSqlWhere.AppendFormat(" and PrintTime <='{0} 23:59:59' ", endCreateTime.Value.ToString("yyyy-MM-dd")); } if (startVoidTime != null && startVoidTime.HasValue) { sbSqlWhere.AppendFormat(" and InvalidTime >='{0}' ", startVoidTime.Value.ToString("yyyy-MM-dd")); } if (endVoidTime != null && endVoidTime.HasValue) { sbSqlWhere.AppendFormat(" and InvalidTime <='{0} 23:59:59' ", endVoidTime.Value.ToString("yyyy-MM-dd")); } if (startGrantTime != null && startGrantTime.HasValue) { sbSqlWhere.AppendFormat(" and GrantTime >='{0}' ", startGrantTime.Value.ToString("yyyy-MM-dd")); } if (endGrantTime != null && endGrantTime.HasValue) { sbSqlWhere.AppendFormat(" and GrantTime <='{0} 23:59:59' ", endGrantTime.Value.ToString("yyyy-MM-dd")); } if (startRecoveryTime != null && startRecoveryTime.HasValue) { sbSqlWhere.AppendFormat(" and BlankRecoveryTime >='{0}' ", startRecoveryTime.Value.ToString("yyyy-MM-dd")); } if (endRecoveryTime != null && endRecoveryTime.HasValue) { sbSqlWhere.AppendFormat(" and BlankRecoveryTime <='{0} 23:59:59' ", endRecoveryTime.Value.ToString("yyyy-MM-dd")); } if (tripStatuss != null && tripStatuss.Count() > 0)//行程单号状态 { sbSqlWhere.AppendFormat(" and TripStatus in({0}) ", string.Join(",", tripStatuss.ToArray())); } if (!string.IsNullOrEmpty(OrderId))//订单号 { sbSqlWhere.AppendFormat(" and OrderId = '{0}' ", OrderId); } string sql = ""; if (isPager) { sql = "SELECT TOP " + pageSize + " * " + "FROM TravelPaper " + " WHERE " + "(ID >(SELECT isnull(MAX(ID),0) " + " FROM (SELECT TOP " + ((pageIndex - 1) * pageSize) + " ID " + " FROM TravelPaper where 1=1 " + sbSqlWhere.ToString() + " " + " ORDER BY ID) AS T)) " + sbSqlWhere.ToString() + " " + " ORDER BY ID "; } else { sql = "select * from TravelPaper where 1=1 " + sbSqlWhere.ToString() + " Order By ID"; } DataPack<TravelPaperDto> data = new DataPack<TravelPaperDto>(); List<TravelPaper> TravelPaperList = new List<TravelPaper>(); DbRawSqlQuery dbRawSqlQuery = unitOfWorkRepository.SqlQuery(sql, typeof(TravelPaper)); TravelPaperList = dbRawSqlQuery.Cast<TravelPaper>().ToList(); sql = "select count(*) from TravelPaper where 1=1 " + sbSqlWhere.ToString(); dbRawSqlQuery = unitOfWorkRepository.SqlQuery(sql, typeof(int)); data.TotalCount = dbRawSqlQuery.Cast<int>().FirstOrDefault(); data.List = Mapper.Map<List<TravelPaper>, List<TravelPaperDto>>(TravelPaperList); return data; } [ExtOperationInterceptor("查询行程单发放记录")] public DataPack<TravelGrantRecordDto> FindTravelRecord(string useBusinessmanCode, string office, DateTime? startTime, DateTime? endTime, int pageIndex, int pageSize, bool isPager = true) { string BusinessmanCode = currentUser.Code; var result = m_travelGrantRecordRepository.FindAll(p => p.BusinessmanCode.Trim() == BusinessmanCode.Trim()); if (startTime != null && startTime.HasValue) { result = result.Where(p => p.GrantTime >= startTime.Value); } if (endTime != null && endTime.HasValue) { DateTime entime = DateTime.Parse(endTime.Value.ToString("yyyy-MM-dd") + " 23:59:59"); result = result.Where(p => p.GrantTime <= entime); } if (!string.IsNullOrEmpty(useBusinessmanCode)) { result = result.Where(p => (p.UseBusinessmanCode.Trim() == useBusinessmanCode.Trim() || p.UseBusinessmanName.Trim() == useBusinessmanCode.Trim())); } if (!string.IsNullOrEmpty(office)) { result = result.Where(p => p.Office.ToLower().Trim() == office.ToLower().Trim()); } List<TravelGrantRecord> TravelGrantRecordList = new List<TravelGrantRecord>(); DataPack<TravelGrantRecordDto> data = new DataPack<TravelGrantRecordDto>(); if (isPager) { TravelGrantRecordList = result.OrderByDescending(p => p.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } else { TravelGrantRecordList = result.ToList(); } List<TravelGrantRecordDto> travelGrantRecordDtoList = Mapper.Map<List<TravelGrantRecord>, List<TravelGrantRecordDto>>(TravelGrantRecordList); //合计 if (travelGrantRecordDtoList.Count > 0) { travelGrantRecordDtoList.Add(new TravelGrantRecordDto() { TripCount = travelGrantRecordDtoList.Sum(p => p.TripCount), UseBusinessmanName = "合计" }); } data.TotalCount = result.Count() + 1; data.List = travelGrantRecordDtoList; return data; } /// <summary> /// 查询行程单统计数据 /// </summary> /// <returns></returns> [ExtOperationInterceptor("查询行程单统计数据")] public TravelPaperStaticsDto FindTravelPaperStatistics(string buyBusinessmanCode, string buyBusinessmanName) { string BusinessmanCode = currentUser.Code; TravelPaperStaticsDto travelPaperStaticsDto = new TravelPaperStaticsDto(); var result = m_travelPaperRepository.FindAll(p => p.BusinessmanCode.Trim() != "" && p.BusinessmanCode.Trim() == BusinessmanCode.Trim()); result.GroupBy(p => p.UseBusinessmanCode.Trim()).Each(p => { TravelPaper travelPaper = null; if (string.IsNullOrEmpty(buyBusinessmanCode) && string.IsNullOrEmpty(buyBusinessmanName)) { travelPaper = result.FirstOrDefault(p1 => p1.UseBusinessmanCode.Trim() == p.Key.Trim()); } else { if (!string.IsNullOrEmpty(buyBusinessmanCode)) { result = result.Where(p1 => p1.UseBusinessmanCode.Trim() == buyBusinessmanCode.Trim()); } if (!string.IsNullOrEmpty(buyBusinessmanName)) { result = result.Where(p1 => p1.UseBusinessmanName.Trim() == buyBusinessmanName.Trim()); } travelPaper = result.FirstOrDefault(p1 => p1.UseBusinessmanCode.Trim() == p.Key.Trim()); } if (travelPaper != null && !string.IsNullOrEmpty(travelPaper.UseBusinessmanCode)) { travelPaperStaticsDto.ItemStaticsList.Add( new TravelPaperItem() { BusinessmanCode = travelPaper.BusinessmanCode, BusinessmanName = travelPaper.BusinessmanName, UseBusinessmanCode = travelPaper.UseBusinessmanCode, UseBusinessmanName = travelPaper.UseBusinessmanName, TotalCount = result.Where(p2 => p2.UseBusinessmanCode == p.Key && (int)p2.TripStatus != 3).Count(), TotalNoUse = result.Where(p2 => p2.UseBusinessmanCode == p.Key && ((int)p2.TripStatus == 0)).Count(), TotalUse = result.Where(p2 => p2.UseBusinessmanCode == p.Key && ((int)p2.TripStatus == 1)).Count(), TotalVoid = result.Where(p2 => p2.UseBusinessmanCode == p.Key && ((int)p2.TripStatus == 2)).Count(), TotalBlankRecovery = result.Where(p2 => p2.UseBusinessmanCode == p.Key && (int)p2.TripStatus == 3).Count(), TotalValidateUse = result.Where(p2 => p2.UseBusinessmanCode == p.Key && (int)p2.TripStatus == 4).Count() + result.Where(p2 => p2.UseBusinessmanCode == p.Key && ((int)p2.TripStatus == 0)).Count() }); } }); travelPaperStaticsDto.Total.UseBusinessmanName = "合计"; travelPaperStaticsDto.Total.TotalCount = travelPaperStaticsDto.ItemStaticsList.Sum(p => p.TotalCount); travelPaperStaticsDto.Total.TotalUse = travelPaperStaticsDto.ItemStaticsList.Sum(p => p.TotalUse); travelPaperStaticsDto.Total.TotalNoUse = travelPaperStaticsDto.ItemStaticsList.Sum(p => p.TotalNoUse); travelPaperStaticsDto.Total.TotalBlankRecovery = travelPaperStaticsDto.ItemStaticsList.Sum(p => p.TotalBlankRecovery); travelPaperStaticsDto.Total.TotalVoid = travelPaperStaticsDto.ItemStaticsList.Sum(p => p.TotalVoid); travelPaperStaticsDto.Total.TotalValidateUse = travelPaperStaticsDto.ItemStaticsList.Sum(p => p.TotalValidateUse); return travelPaperStaticsDto; } /// <summary> /// 发放空白行程单 /// </summary> /// <param name="travelPaper"></param> [ExtOperationInterceptor("发放空白行程单")] public int GrantBlankRecoveryTravelPaper( string useBusinessman, string useOffice, string iataCode, string ticketCompanyName, string TripRemark, List<int> selectIds) { int dataCount = -1; string strMsg = string.Empty; string BusinessmanCode = currentUser.Code; string BusinessmanName = currentUser.BusinessmanName; string useBusinessmanCode = string.Empty; string useBusinessmanName = string.Empty; var result = m_travelPaperRepository.FindAll(p => p.BusinessmanCode.Trim() == BusinessmanCode.Trim()); Businessman businessman = this.m_businessmanRepository.FindAll(p => p.Code.Trim() == useBusinessman.Trim() || p.Name.Trim() == useBusinessman.Trim()).FirstOrDefault(); if (businessman == null) { strMsg = "分配采购商户号或者采购商户名称不存在!"; } else { useBusinessmanCode = businessman.Code; useBusinessmanName = businessman.Name; } //useBusinessmanCode = "caigou";//businessman.Code; //useBusinessmanName = "采购";//businessman.Name; if (string.IsNullOrEmpty(strMsg)) { List<int> Ids = new List<int>(); List<string> tripNumber = new List<string>(); result.Where(p => selectIds.Contains(p.ID)).Each(p => { Ids.Add(p.ID); tripNumber.Add(p.TripNumber); }); //发放空白行程单 dataCount = unitOfWorkRepository.ExecuteCommand( "EXEC [dbo].[TravelPaperImport] @p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11,@p12 ", "2", "", "0", "0", useOffice, iataCode, ticketCompanyName, BusinessmanCode, BusinessmanName, useBusinessmanCode, useBusinessmanName, TripRemark, string.Join(",", Ids.ToArray()) ); if (dataCount <= 0) { strMsg = "发放空白行程单失败!"; } else { if (dataCount > 0) { TravelGrantRecord travelGrantRecord = new TravelGrantRecord(); travelGrantRecord.BusinessmanCode = BusinessmanCode; travelGrantRecord.BusinessmanName = BusinessmanName; travelGrantRecord.UseBusinessmanCode = useBusinessmanCode; travelGrantRecord.UseBusinessmanName = useBusinessmanName; travelGrantRecord.GrantTime = System.DateTime.Now; travelGrantRecord.Office = useOffice; travelGrantRecord.TripCount = tripNumber.Count(); travelGrantRecord.TripScope = string.Join(",", tripNumber.ToArray()); travelGrantRecord.TripRemark = TripRemark; //添加发放记录 unitOfWorkRepository.PersistCreationOf(travelGrantRecord); unitOfWork.Commit(); } } } if (!string.IsNullOrEmpty(strMsg)) { throw new OrderCommException(strMsg); } return dataCount; } /// <summary> /// 批量修改Office /// </summary> /// <param name="useOffice"></param> /// <param name="BusinessmanCode"></param> /// <param name="SelectIds"></param> [ExtOperationInterceptor("批量修改Office")] public int UpdateOffice(string useOffice, List<int> selectIds) { int dataCount = -1; string BusinessmanCode = currentUser.Code; try { List<TravelPaper> travelPaperList = m_travelPaperRepository.FindAll(p => p.BusinessmanCode == BusinessmanCode && selectIds.Contains(p.ID)).ToList(); if (travelPaperList != null && travelPaperList.Count > 0) { for (int i = 0; i < travelPaperList.Count; i++) { travelPaperList[i].WriteLog(new TravelPaperLog() { OperationContent = "原Office:" + travelPaperList[i].UseOffice + " 新Office:" + useOffice, OperationType = "修改Office", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); travelPaperList[i].UseOffice = useOffice; unitOfWorkRepository.PersistUpdateOf(travelPaperList[i]); } unitOfWork.Commit(); dataCount = travelPaperList.Count; } else { throw new OrderCommException("批量修改Office失败!"); } } catch (Exception ex) { throw new OrderCommException(ex.Message); } return dataCount; } /// <summary> /// 回收空白行程单 /// </summary> /// <param name="travelPaper"></param> [ExtOperationInterceptor("回收空白行程单")] public int RecoveryBlackTravelPaper(List<int> travelIdList) { int dataCount = -1; string BusinessmanCode = currentUser.Code; try { List<TravelPaper> travelPaperList = this.m_travelPaperRepository.FindAll(p => p.BusinessmanCode == BusinessmanCode && travelIdList.Contains(p.ID) && (p.TripStatus == EnumTripStatus.NoUsed || p.TripStatus == EnumTripStatus.BlankRecoveryUsed) ).ToList(); if (travelPaperList != null && travelPaperList.Count > 0) { for (int i = 0; i < travelPaperList.Count; i++) { travelPaperList[i].WriteLog(new TravelPaperLog() { OperationContent = "回收空白行程单", OperationType = "空白回收", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); travelPaperList[i].TripStatus = EnumTripStatus.BlankRecoveryNoUsed; travelPaperList[i].PrintTime = DateTime.Parse("1900-01-01"); travelPaperList[i].InvalidTime = DateTime.Parse("1900-01-01"); travelPaperList[i].BlankRecoveryTime = System.DateTime.Now; travelPaperList[i].UseBusinessmanCode = ""; travelPaperList[i].UseBusinessmanName = ""; travelPaperList[i].UseOffice = ""; unitOfWorkRepository.PersistUpdateOf(travelPaperList[i]); } unitOfWork.Commit(); dataCount = travelPaperList.Count; } else { throw new OrderCommException("请选择空白回收的行程单!"); } } catch (Exception ex) { throw new OrderCommException(ex.Message); } return dataCount; } /// <summary> /// 回收作废行程单 /// </summary> /// <param name="travelPaper"></param> [ExtOperationInterceptor("回收作废行程单")] public int RecoveryVoidTravelPaper(List<int> travelIdList) { int dataCount = -1; string BusinessmanCode = currentUser.Code; try { List<TravelPaper> travelPaperList = this.m_travelPaperRepository.FindAll(p => p.BusinessmanCode == BusinessmanCode && travelIdList.Contains(p.ID)).ToList(); if (travelPaperList != null && travelPaperList.Count > 0) { for (int i = 0; i < travelPaperList.Count; i++) { travelPaperList[i].WriteLog(new TravelPaperLog() { OperationContent = "回收作废行程单", OperationType = "回收作废", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); travelPaperList[i].TripStatus = EnumTripStatus.VoidRecoveryUsed; travelPaperList[i].BlankRecoveryTime = System.DateTime.Now; unitOfWorkRepository.PersistUpdateOf(travelPaperList[i]); } unitOfWork.Commit(); dataCount = travelPaperList.Count; } else { throw new OrderCommException("请选择回收作废的行程单!"); } } catch (Exception ex) { throw new OrderCommException(ex.Message); } return dataCount; } /// <summary> /// 查询行程单号详情 /// </summary> /// <param name="TripNumber"></param> /// <returns></returns> [ExtOperationInterceptor("查询行程单号详情")] public TravelPaperDto QueryTripNumberDetail(string tripNumber) { TravelPaperDto TravelPaperDto = null; var result = m_travelPaperRepository.FindAll(p => p.TripNumber == tripNumber); TravelPaper travelPaper = result.FirstOrDefault(); if (travelPaper != null) { TravelPaperDto = Mapper.Map<TravelPaper, TravelPaperDto>(travelPaper); TravelPaperDto.TravelPaperLogDtos = Mapper.Map<List<TravelPaperLog>, List<TravelPaperLogDto>>(travelPaper.TravelPaperLogs); } else { throw new OrderCommException("未能查到该【" + tripNumber + "】行程单号的信息"); } return TravelPaperDto; } /// <summary> /// 批量修改行程单数据 /// </summary> /// <param name="tripNumber"></param> /// <param name="ticketNumber"></param> /// <param name="tripStatus"></param> /// <param name="useOffice"></param> /// <param name="iataCode"></param> /// <param name="ticketCompanyName"></param> /// <returns></returns> [ExtOperationInterceptor("批量修改行程单数据")] public bool UpdateTripNumberInfo(List<string> tripNumberList, string ticketNumber, EnumTripStatus tripStatus, string useOffice, string iataCode, string ticketCompanyName) { bool IsUpdate = false; if (tripNumberList == null || tripNumberList.Count == 0) throw new OrderCommException("需要修改的行程单数据不能为空!"); var result = m_travelPaperRepository.FindAll(p => tripNumberList.Contains(p.TripNumber)).ToList(); if (result.Count > 0) { result.ForEach(p => { TravelPaper travelPaper = p; if (travelPaper != null) { string tripNumber = p.TripNumber; StringBuilder sbCon = new StringBuilder(); if (!string.IsNullOrEmpty(ticketNumber) && ticketNumber != travelPaper.TicketNumber) { travelPaper.TicketNumber = ticketNumber; sbCon.AppendFormat("原票号:{0} 新票号:{1},", travelPaper.TicketNumber, tripNumber); } if (tripStatus != travelPaper.TripStatus) { travelPaper.TripStatus = tripStatus; sbCon.AppendFormat("原状态:{0} 新状态:{1},", EnumItemManager.GetDesc(travelPaper.TripStatus), EnumItemManager.GetDesc(tripStatus)); } if (!string.IsNullOrEmpty(useOffice) && useOffice != travelPaper.UseOffice) { travelPaper.UseOffice = useOffice; sbCon.AppendFormat("原Office号:{0} 新Office号:{1},", travelPaper.UseOffice, useOffice); } if (!string.IsNullOrEmpty(iataCode) && iataCode != travelPaper.IataCode) { travelPaper.IataCode = iataCode; sbCon.AppendFormat("原航协号:{0} 新航协号:{1},", travelPaper.IataCode, iataCode); } if (!string.IsNullOrEmpty(ticketCompanyName) && ticketCompanyName != travelPaper.TicketCompanyName) { travelPaper.TicketCompanyName = ticketCompanyName; sbCon.AppendFormat("原填开单位:{0} 新填开单位:{1},", travelPaper.TicketCompanyName, ticketCompanyName); } travelPaper.WriteLog(new TravelPaperLog() { OperationType = "修改", OperationPerson = currentUser.OperatorAccount, OperationDatetime = System.DateTime.Now, OperationContent = sbCon.ToString() }); unitOfWorkRepository.PersistUpdateOf(travelPaper); } }); //提交 unitOfWork.Commit(); IsUpdate = true; } else { throw new OrderCommException("未能查到行程单数据!"); } return IsUpdate; } /// <summary> /// 创建行程单 /// </summary> /// <param name="req"></param> [ExtOperationInterceptor("创建行程单")] public TravelAppResponse CreateTrip(BPiaoBao.AppServices.DataContracts.DomesticTicket.TravelAppRequrst req) { TravelAppResponse response = new TravelAppResponse(); try { FlightService flightDestineService = new FlightService(this.m_businessmanRepository, currentUser); response = flightDestineService.CreateTrip(req); if (response.IsSuc) { if (response.PnrAnalysisTripNumber.Trim() != req.TripNumber.Trim()) { response.IsSuc = false; } else { if (req.Flag == 0)//如果是正常订单 { //更改状态 Order order = this.orderRepository.FindAll(p => p.OrderId == req.OrderId).FirstOrDefault(); TravelPaper travelPaper = this.m_travelPaperRepository.FindAll(p => p.TripNumber == req.TripNumber).FirstOrDefault(); if (order != null && travelPaper != null) { order.Passengers.Each(p => { if (p.Id == req.PassengerId) { p.PassengerTripStatus = EnumPassengerTripStatus.HasCreate; p.TravelNumber = req.TripNumber; } }); travelPaper.OrderId = req.OrderId; travelPaper.PassengerId = req.PassengerId; travelPaper.TripStatus = EnumTripStatus.HasCreatedUsed; travelPaper.PrintTime = System.DateTime.Now; travelPaper.TicketNumber = req.TicketNumber; string strLog = "行程单号:" + response.TripNumber + "票号:" + response.TicketNumber + " Office:" + response.CreateOffice + " " + response.ShowMsg; travelPaper.WriteLog(new TravelPaperLog() { OperationContent = strLog, OperationType = "创建行程单", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); order.OrderLogs.Add(new OrderLog() { OperationContent = strLog, OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount, IsShowLog = true }); } unitOfWorkRepository.PersistUpdateOf(order); unitOfWorkRepository.PersistUpdateOf(travelPaper); unitOfWork.Commit(); } else//如果是售后订单 { //更改状态 int id = int.Parse(req.OrderId); AfterSaleOrder order = this.AfterSaleorderRepository.FindAll(p => p.Id == id).FirstOrDefault(); TravelPaper travelPaper = this.m_travelPaperRepository.FindAll(p => p.TripNumber == req.TripNumber).FirstOrDefault(); if (order != null && travelPaper != null) { order.Passenger.Each(p => { if (p.Id == req.PassengerId) { p.PassengerTripStatus = EnumPassengerTripStatus.HasCreate; p.AfterSaleTravelNum = req.TripNumber; p.AfterSaleTravelTicketNum = req.TicketNumber; } }); travelPaper.OrderId = req.OrderId; travelPaper.PassengerId = req.PassengerId; travelPaper.TripStatus = EnumTripStatus.HasCreatedUsed; travelPaper.PrintTime = System.DateTime.Now; travelPaper.TicketNumber = req.TicketNumber; string strLog = "改签行程单号:" + response.TripNumber + "改签票号:" + response.TicketNumber + " 改签Office:" + response.CreateOffice + " " + response.ShowMsg; travelPaper.WriteLog(new TravelPaperLog() { OperationContent = strLog, OperationType = "创建改签行程单", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); order.Order.OrderLogs.Add(new OrderLog() { OperationContent = strLog, OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount, IsShowLog = true }); } unitOfWorkRepository.PersistUpdateOf(order); unitOfWorkRepository.PersistUpdateOf(travelPaper); unitOfWork.Commit(); } } } } catch (Exception ex) { throw new CustomException(111, ex.Message); } return response; } /// <summary> /// 作废行程单 /// </summary> /// <param name="req"></param> [ExtOperationInterceptor("作废行程单")] public TravelAppResponse VoidTrip(BPiaoBao.AppServices.DataContracts.DomesticTicket.TravelAppRequrst req) { TravelAppResponse response = new TravelAppResponse(); try { FlightService flightDestineService = new FlightService(this.m_businessmanRepository, currentUser); response = flightDestineService.VoidTrip(req); if (response.IsSuc) { if (response.PnrAnalysisTripNumber.Trim() != req.TripNumber.Trim()) { response.IsSuc = false; } else { if (req.Flag == 0) { //更改状态 Order order = this.orderRepository.FindAll(p => p.OrderId == req.OrderId).FirstOrDefault(); TravelPaper travelPaper = this.m_travelPaperRepository.FindAll(p => p.TripNumber == req.TripNumber).FirstOrDefault(); if (order != null && travelPaper != null) { order.Passengers.Each(p => { if (p.Id == req.PassengerId) { p.PassengerTripStatus = EnumPassengerTripStatus.HasVoid; } }); travelPaper.OrderId = req.OrderId; travelPaper.PassengerId = req.PassengerId; travelPaper.TripStatus = EnumTripStatus.HasObsoleteUsed; travelPaper.InvalidTime = System.DateTime.Now; string strLog = "行程单号:" + response.TripNumber + "票号:" + response.TicketNumber + " Office:" + response.CreateOffice + " " + response.ShowMsg; travelPaper.WriteLog(new TravelPaperLog() { OperationContent = strLog, OperationType = "作废行程单", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); order.OrderLogs.Add(new OrderLog() { OperationContent = strLog, OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount, IsShowLog = true }); unitOfWorkRepository.PersistUpdateOf(order); unitOfWorkRepository.PersistUpdateOf(travelPaper); unitOfWork.Commit(); } } else { //更改状态 int id = int.Parse(req.OrderId); AfterSaleOrder order = this.AfterSaleorderRepository.FindAll(p => p.Id == id).FirstOrDefault(); TravelPaper travelPaper = this.m_travelPaperRepository.FindAll(p => p.TripNumber == req.TripNumber).FirstOrDefault(); if (order != null && travelPaper != null) { order.Passenger.Each(p => { if (p.Id == req.PassengerId) { p.PassengerTripStatus = EnumPassengerTripStatus.HasVoid; } }); travelPaper.OrderId = req.OrderId; travelPaper.PassengerId = req.PassengerId; travelPaper.TripStatus = EnumTripStatus.HasObsoleteUsed; travelPaper.InvalidTime = System.DateTime.Now; string strLog = "改签行程单号:" + response.TripNumber + "改签票号:" + response.TicketNumber + " 改签Office:" + response.CreateOffice + " " + response.ShowMsg; travelPaper.WriteLog(new TravelPaperLog() { OperationContent = strLog, OperationType = "作废改签行程单", OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount }); order.Order.OrderLogs.Add(new OrderLog() { OperationContent = strLog, OperationDatetime = System.DateTime.Now, OperationPerson = currentUser.OperatorAccount, IsShowLog = true }); unitOfWorkRepository.PersistUpdateOf(order); unitOfWorkRepository.PersistUpdateOf(travelPaper); unitOfWork.Commit(); } } } } } catch (Exception ex) { throw new CustomException(111, ex.Message); } return response; } } }
using FiveOhFirstDataCore.Core.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FiveOhFirstDataCore.Core.Structures { public class DiscordBotConfiguration { public ulong HomeGuild { get; set; } public Dictionary<CShop, Dictionary<string, Dictionary<string, ulong[]>>> CShopRoleBindings { get; set; } public Dictionary<string, Dictionary<string, DiscordRoleDetails>> RoleBindings { get; set; } } }
namespace WikiMusic.Services.Models { using System.Collections.Generic; using WikiMusic.Models; public class UpdateAlbumSongs { public int Id { get; set; } public IEnumerable<SongRequestModel> Songs { get; set; } } }
using System; namespace SoccerFieldServer.Core.Extensions { public static class DateTimeExtensions { public static DateTime GetCurrentTimeZoneTime(string timeZoneId = "Pacific Standard Time") { return DateTime.UtcNow.ToTimeZoneTime(timeZoneId); } public static DateTime GetStartDateFromCurrentTimeZoneTime(string timeZoneId = "Pacific Standard Time") { var currentTimeZoneTime = GetCurrentTimeZoneTime(timeZoneId); return currentTimeZoneTime.GetStartDateTimeZoneTime(timeZoneId); } public static DateTime GetStartDateTimeZoneTime(this DateTime dt, string timeZoneId = "Pacific Standard Time") { var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); var offset = tzi.GetUtcOffset(dt); return dt.StartTimeOfDate().Subtract(offset); } public static DateTime GetEndDateFromCurrentTimeZoneTime(string timeZoneId = "Pacific Standard Time") { var currentTimeZoneTime = GetCurrentTimeZoneTime(timeZoneId); return currentTimeZoneTime.GetEndDateTimeZoneTime(timeZoneId); } public static DateTime GetEndDateTimeZoneTime(this DateTime dt, string timeZoneId = "Pacific Standard Time") { var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); var offset = tzi.GetUtcOffset(dt); return dt.EndTimeOfDate().Subtract(offset); } public static DateTime ToUtcTime(this DateTime dt, TimeZoneInfo tzi) { return TimeZoneInfo.ConvertTimeToUtc(dt, tzi); } public static DateTime ToUtcTime(this DateTime dt, string timeZoneId = "Pacific Standard Time") { var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return dt.ToUtcTime(tzi); } public static DateTime ToTimeZoneTime(this DateTime dt, TimeZoneInfo tzi) { return TimeZoneInfo.ConvertTimeFromUtc(dt, tzi); } public static DateTime ToTimeZoneTime(this DateTime dt, string timeZoneId = "Pacific Standard Time") { var tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); return dt.ToTimeZoneTime(tzi); } private static DateTime StartTimeOfDate(this DateTime dt) { return dt.Date; } private static DateTime EndTimeOfDate(this DateTime dt) { return dt.StartTimeOfDate().AddDays(1).AddTicks(-1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SaleaeApiUi.Common { public abstract class PeriodicAction : IDisposable { //========================================================================================== // Set these up before calling Start()!!! public TimeSpan Period { get; set; } = TimeSpan.FromSeconds(2); public TimeSpan StartAfter { get; set; } = TimeSpan.Zero; public object StateObj { get; set; } //========================================================================================== public abstract void PeriodicFunction(object state); public void Start() { Stop(); lock (TimerObjLock) { TimerObj = new Timer(PeriodicFunction, StateObj, StartAfter, Period); } } public void Stop() { lock (TimerObjLock) { TimerObj?.Dispose(); TimerObj = null; } } //================================================================================ Timer private Timer TimerObj; private object TimerObjLock = new object(); //================================================================================ Implement IDisposable #region Implement IDisposable private bool disposed = false; private object disposeLock = new object(); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { lock (disposeLock) { // Check to see if Dispose has already been called. if (!this.disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Dispose managed resources. lock (TimerObjLock) { if (TimerObj != null) { TimerObj.Dispose(); TimerObj = null; } } } // Call the appropriate methods to clean up // unmanaged resources here. // If disposing is false, // only the following code is executed. // Note disposing has been done. disposed = true; } } } ~PeriodicAction() { Dispose(false); } #endregion Implement IDisposable //================================================================================ } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ProductController.cs" company="Eyefinity, Inc"> // 2013 Eyefinity, Inc // </copyright> // <summary> // Defines the ProductController type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Eyefinity.PracticeManagement.Controllers { using System.Web.Mvc; using Eyefinity.PracticeManagement.Common; using Eyefinity.PracticeManagement.Common.Api; /// <summary> /// The work in progress controller. /// </summary> [NoCache] public class ProductController : Controller { // GET: /WorkInProgress/ /// <summary> /// The lookup. /// </summary> /// <returns> /// The <see cref="ActionResult"/>. /// </returns> public ActionResult Lookup() { return this.View(); } /// <summary> /// The inventory. /// </summary> /// <returns> /// The <see cref="ActionResult"/>. /// </returns> public ActionResult Inventory() { var authorizationTicketHelper = new AuthorizationTicketHelper(); var user = authorizationTicketHelper.GetUserInfo(); return this.View(user); } /// <summary> /// The work in progress. /// </summary> /// <returns> /// The <see cref="ActionResult"/>. /// </returns> public ActionResult WorkInProgress() { return this.View(); } /// <summary> /// The print labels. /// </summary> /// <returns> /// The <see cref="ActionResult"/>. /// </returns> public ActionResult PrintLabels() { return this.View(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SelfDestroy : MonoBehaviour { [SerializeField] private float m_aliveTime = 5f; private void Start() { Destroy(gameObject, m_aliveTime); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HouseParty.Client.Contracts.Questions { public class QuestionUpdateViewModel { public int Id { get; set; } public string Title { get; set; } public Boolean WhetherSeen { get; set; } public Boolean WontDo { get; set; } public string WontDoReason { get; set; } public Boolean WhetherShubhiSubmitted { get; set; } public Boolean WhetherAdityaSubmitted { get; set; } public string ShubhiSolution { get; set; } public string AdityaSolution { get; set; } public string QuestionUrl { get; set; } public string Notes { get; set; } public QuestionType QuestionType { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace TpUbiComp.Models { public class ApplicationLocale { [Key] public int Id { get; set; } public Application Application { get; set; } public Locale Locale { get; set; } public string Url { get; set; } } }
using LogicBuilder.Attributes; namespace CheckMySymptoms.Forms.Parameters.Common { public class SortParameters { public SortParameters() { } public SortParameters ( [Comments("Update modelType first. Property name from the target object. Use a period for nested fields i.e. foo.bar.")] [ParameterEditorControl(ParameterControlType.ParameterSourcedPropertyInput)] [NameValue(AttributeNames.PROPERTYSOURCEPARAMETER, "modelType")] string field, [Domain("asc,desc")] [ParameterEditorControl(ParameterControlType.DropDown)] string dir, [ParameterEditorControl(ParameterControlType.ParameterSourceOnly)] [NameValue(AttributeNames.DEFAULTVALUE, "CheckMySymptoms.Domain.Entities")] [Comments("Fully qualified class name for the model type.")] string modelType = null ) { Field = field; Dir = dir; } public string Field { get; set; } public string Dir { get; set; } } }
using System.IO; using Android.App; using Android.OS; using Android.Support.V7.App; using Android.Widget; using Passcore.Android.Helper; namespace Passcore.Android.Views { [Activity(Label = "@string/settings", Theme = "@style/AppTheme", ParentActivity = typeof(MainActivity))] public class SettingsActivity : AppCompatActivity { Switch SwtBlockScreenshot, SwtSaveEnhance, SwtSavePassword, SwtSaveMasterKey, SwtSavePasswordLength, SwtSaveIsCharRequired; Button BtnResetAll; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_settings); SupportActionBar.SetDisplayHomeAsUpEnabled(true); // TODO: Store it SwtBlockScreenshot = FindViewById<Switch>(Resource.Id.SwtBlockScreenshot); SwtSaveEnhance = FindViewById<Switch>(Resource.Id.SwtSaveEnhance); SwtSavePassword = FindViewById<Switch>(Resource.Id.SwtSavePassword); SwtSaveMasterKey = FindViewById<Switch>(Resource.Id.SwtSaveMasterKey); SwtSavePasswordLength = FindViewById<Switch>(Resource.Id.SwtSavePasswordLength); SwtSaveIsCharRequired = FindViewById<Switch>(Resource.Id.SwtSaveIsCharRequired); BtnResetAll = FindViewById<Button>(Resource.Id.BtnResetAll); SwtSaveEnhance.Checked = Shared.Config.IsStoreEnhance; SwtSavePassword.Checked = Shared.Config.IsStorePassword; SwtSaveMasterKey.Checked = Shared.Config.IsStoreMasterKey; SwtSavePasswordLength.Checked = Shared.Config.IsStorePasswordLength; SwtSaveIsCharRequired.Checked = Shared.Config.IsStoreCharRequired; SwtBlockScreenshot.Checked = Shared.MainActivity != null ? Shared.MainActivity.IsSecure : false; SwtBlockScreenshot.CheckedChange += SwtBlockScreenshot_CheckedChange; SwtSaveMasterKey.CheckedChange += SwtSaveMasterKey_CheckedChange; SwtSaveEnhance.CheckedChange += SwtSaveEnhance_CheckedChange; SwtSavePassword.CheckedChange += SwtSavePassword_CheckedChange; SwtSavePasswordLength.CheckedChange += SwtSavePasswordLength_CheckedChange; SwtSaveIsCharRequired.CheckedChange += SwtSaveIsCharRequired_CheckedChange; BtnResetAll.Click += BtnResetAll_Click; } private void BtnResetAll_Click(object sender, System.EventArgs e) { var a = new global::Android.App.AlertDialog.Builder(this).Create(); a.SetTitle(Resources.GetString(Resource.String.caution)); a.SetMessage(Resources.GetString(Resource.String.reset_all_warn)); a.SetButton(Resources.GetString(Resource.String.ok), (s, d) => { File.Delete(Path.Combine(IOHelper.GetDataPath(), "config.pc")); System.Environment.Exit(0); }); a.SetButton2(Resources.GetString(Resource.String.cancel), (s, d) => { }); a.Show(); } private void SwtSaveIsCharRequired_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { Shared.Config.IsStoreCharRequired = SwtSaveIsCharRequired.Checked; } private void SwtSavePasswordLength_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { Shared.Config.IsStorePasswordLength = SwtSavePasswordLength.Checked; } private void SwtSavePassword_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { Shared.Config.IsStorePassword = SwtSavePassword.Checked; } private void SwtSaveEnhance_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { Shared.Config.IsStoreEnhance = SwtSaveEnhance.Checked; } private void SwtSaveMasterKey_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { Shared.Config.IsStoreMasterKey = SwtSaveMasterKey.Checked; } private void SwtBlockScreenshot_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { ActivityHelper.SetSecureFlag(this, SwtBlockScreenshot.Checked); if (Shared.MainActivity != null) Shared.MainActivity.IsSecure = SwtBlockScreenshot.Checked; } } }
using Catalogo.Domain.Entities; using Catalogo.Domain.Repositories; using Catalogo.Domain.Services; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Catalogo.Services { public class CategoriaService : Service<Categoria>, ICategoriaService { public CategoriaService(IUnitOfWork unitOfWork) : base(unitOfWork) { } public async Task AdicionarCategoria(Categoria entity) { await _unitOfWork.CategoriaRepository.Add(entity); } public Task AtualizarCategoria(Categoria entity) { throw new NotImplementedException(); } public Categoria BuscarCategoriaPorId(Guid id) { throw new NotImplementedException(); } public Task DeletarCategoria(Categoria entity) { throw new NotImplementedException(); } public IList<Categoria> ListarCategorias() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using biz.dfch.CS.LogShipper.Public; using System.Management.Automation; using System.IO; using System.Collections.Specialized; namespace biz.dfch.CS.LogShipper.Extensions { [Export(typeof(ILogShipperParser))] [ExportMetadata("Name", "PowerShellParser")] public class PowerShellParser : ILogShipperParser { readonly PowerShell _ps = PowerShell.Create(); private String _scriptFile; private NameValueCollection _configuration; public NameValueCollection Configuration { get { return _configuration; } set { if (!VerifyAndSetConfiguration(value)) { throw new ArgumentNullException("Configuration", "DefaultTextParser.Configuration: Parameter validation FAILED. Parameter must not be null."); } } } // DFTODO Implement OffsetParsed private UInt32 _offsetParsed; public UInt32 OffsetParsed { get { return _offsetParsed; } set { _offsetParsed = value; } } public List<String> Parse(String data) { if (null == _configuration) { throw new ArgumentNullException("Configuration", "PowerShellParser.Configuration: Parameter validation FAILED. Parameter must not be null."); } _offsetParsed = 0; var list = new List<String>(); if (String.IsNullOrEmpty(data)) { list.Clear(); return list; } _ps.Commands.Clear(); _ps .AddScript(String.Format("[System.Diagnostics.Trace]::WriteLine('{0}')", data)) .AddScript(String.Format("return @('and the result is: {0}')", data)) .AddCommand(_scriptFile) .AddParameter("InputObject", data) ; var results = _ps .Invoke(); foreach (var result in results) { var line = result.BaseObject.ToString(); System.Diagnostics.Trace.WriteLine(String.Format("result: '{0}'", line)); list.Add(line); } return list; } public bool UpdateConfiguration(NameValueCollection configuration) { return VerifyAndSetConfiguration(configuration); } private bool VerifyAndSetConfiguration(NameValueCollection configuration) { var fReturn = false; try { if (null == configuration) { throw new ArgumentNullException("configuration", "configuration: Parameter validation FAILED. Parameter must not be null."); } var scriptFile = configuration.Get("ScriptFile"); if (String.IsNullOrWhiteSpace(scriptFile)) { throw new ArgumentNullException("ScriptFile", "PowerShellParser.Configuration: Parameter validation FAILED. ScriptFile must not be null."); } if (null == scriptFile || String.IsNullOrWhiteSpace(scriptFile)) throw new ArgumentNullException("scriptFile", String.Format("scriptFile: Parameter validation FAILED. Parameter cannot be null or empty.")); if (String.IsNullOrWhiteSpace(Path.GetDirectoryName(scriptFile))) { scriptFile = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(scriptFile)); } var achFileName = Path.GetFileName(scriptFile).ToCharArray(); var achFileInvalidChars = Path.GetInvalidFileNameChars(); if ('\0' != achFileName.Intersect(achFileInvalidChars).FirstOrDefault()) { throw new ArgumentException("ScriptFile: Parameter validation FAILED. ScriptFile name contains invalid characters.", scriptFile); } if (!File.Exists(scriptFile)) throw new FileNotFoundException(String.Format("scriptFile: Parameter validation FAILED. File '{0}' does not exist.", scriptFile), scriptFile); _configuration = new NameValueCollection(configuration); _scriptFile = scriptFile; fReturn = true; } catch(Exception ex) { fReturn = false; } return fReturn; } } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using UnityEngine; public class Dialogue { private List<DialogueLine> script; private int idx; public Dialogue (TextAsset textFile) { script = new List<DialogueLine> (); idx = 0; ParseFile (textFile); } //Parse the given TextAsset and populate the script private void ParseFile(TextAsset textFile) { string contents; string[] splitContents; string currentSpeaker = ""; contents = textFile.text; contents = Regex.Replace (contents, "\r|\n", ""); splitContents = Regex.Split (contents, "==="); foreach (string section in splitContents) { if (Regex.Match (section, "<(.*)>").Success) { currentSpeaker = Regex.Replace (section, "<|>| ", ""); } else { script.Add (new DialogueLine (currentSpeaker, section)); } } } public string NextLine() { string tempText = script [idx].GetText (); idx++; return tempText; } public bool HasLine() { bool temp = idx < script.Count; if (!temp) { idx = 0; } return temp; } public string PeekNextSpeaker() { return script[idx].GetSpeaker (); } }
using Microsoft.AspNetCore.Mvc; using Skaitykla.Domains; using Skaitykla.MVC.Models; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace Skaitykla.MVC.Controllers { public class BookController : Controller { public IActionResult Index() { return View(); } [HttpGet] public IActionResult NewBook() { var myAuthorList = new List<Author>() { new Author("Stephen", "King"), new Author("Salomeja", "Neris") }; return View(myAuthorList); } [HttpPost] public IActionResult NewBook(NewBookViewModel model) { if (!ModelState.IsValid) { ViewBag.AuthError = "ivyko klaida"; return RedirectToAction("Index", "Auath"); } var myNewBook = new Book { Title = model.Title, // Author = _db.authors.where(Author => ) }; //Db.Save(); return RedirectToAction("NewBook"); } } }
using System; using System.Linq; using NGrams.Profiles; namespace NGrams.DistanceCalculation { /// <summary> /// Расстояние Колмогорова-Смирнова sum( xi-yi ) / 2 /// </summary> public class KolmogorovSmirnovDistance : DistanceBase { public override double GetDistance<TCriteria>(IProfile<TCriteria> profile1, IProfile<TCriteria> profile2) { var criteries = this.MergeCriteries(profile1, profile2); decimal distance = criteries.Sum(criteria => Math.Abs(profile2.GetCriteriaOccurencyFrequency(criteria) - profile1.GetCriteriaOccurencyFrequency(criteria))); return (double)(distance / 2); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Model.Schema.EIVO; using System.Text.RegularExpressions; using System.Globalization; using Model.DataEntity; using DataAccessLayer.basis; namespace Model.InvoiceManagement { public static partial class CancelInvoiceRootValidator { //檢查基本必填項目(作廢發票) public static Exception CheckMandatoryFields(this CancelInvoiceRootCancelInvoice invItem,GenericManager<EIVOEntityDataContext> mgr,OrganizationToken owner, out InvoiceItem invoice,out DateTime cancelDate) { invoice = null; cancelDate = default(DateTime); if (String.IsNullOrEmpty(invItem.CancelInvoiceNumber) || !Regex.IsMatch(invItem.CancelInvoiceNumber, "^[a-zA-Z]{2}[0-9]{8}$")) { return new Exception(String.Format("作廢發票號碼錯誤,作廢發票號碼長度應為10碼(含字軌),傳送資料:{0},TAG:< CancelInvoiceNumber />", invItem.CancelInvoiceNumber)); } String invNo, trackCode; trackCode = invItem.CancelInvoiceNumber.Substring(0, 2); invNo = invItem.CancelInvoiceNumber.Substring(2); DateTime invoiceDate; if (String.IsNullOrEmpty(invItem.InvoiceDate) || !DateTime.TryParseExact(invItem.InvoiceDate,"yyyy/MM/dd",CultureInfo.CurrentCulture,DateTimeStyles.None,out invoiceDate)) { return new Exception("發票日期錯誤,TAG:< InvoiceDate/>"); } if (!DateTime.TryParseExact(invItem.InvoiceDate, "yyyy/MM/dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out invoiceDate)) { return new Exception(String.Format("發票日期格式錯誤(YYYY/MM/DD),傳送資料:{0},TAG:< InvoiceDate/>", invItem.InvoiceDate)); } invoice = mgr.GetTable<InvoiceItem>().Where(i => i.No == invNo && i.TrackCode == trackCode).FirstOrDefault(); if (invoice == null) { return new Exception(String.Format("發票號碼不存在:{0}", invItem.CancelInvoiceNumber)); } if (invoice.SellerID != owner.CompanyID) { return new Exception(String.Format("作廢之發票非原發票開立人,發票號碼:{0}", invItem.CancelInvoiceNumber)); } if (invoice.InvoiceCancellation != null) { return new Exception(String.Format("作廢發票已存在,發票號碼:{0}", invItem.CancelInvoiceNumber)); } if (String.IsNullOrEmpty(invItem.SellerId)) { return new Exception("賣方識別碼錯誤,TAG:< SellerId />"); } if (String.IsNullOrEmpty(invItem.CancelDate)) { return new Exception("作廢日期,TAG:< CancelDate />"); } if (String.IsNullOrEmpty(invItem.CancelTime)) { return new Exception("作廢時間,TAG:< CancelTime />"); } if (!DateTime.TryParseExact(String.Format("{0} {1}", invItem.CancelDate, invItem.CancelTime), "yyyy/MM/dd HH:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out invoiceDate)) { return new Exception(String.Format("作廢發票日期、發票時間格式錯誤(YYYY/MM/DD HH:mm:ss);傳送資料:{0} {1}", invItem.CancelDate, invItem.CancelTime)); } if (String.IsNullOrEmpty(invItem.CancelReason)) { return new Exception("作廢原因不可空白,TAG:< CancelReason />"); } if (invItem.CancelReason.Length > 20) { return new Exception(String.Format("資料格式長度最少1碼,最多20碼,傳送資料:{0},TAG:< CancelReason />", invItem.CancelReason)); } //備註 if (invItem.Remark!=null && invItem.Remark.Length > 200) { return new Exception(String.Format("備註資料長度不可超過200,傳送資料:{0},TAG:< Remark />", invItem.Remark)); } return null; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Result : MonoBehaviour { public GameObject proceedsObj; //売上 public Text proceedsText; //売上のテキスト public GameObject sellProductNumObj; //商品を売った個数 public Text sellProductNumText; //商品を撃った個数のテキスト public GameObject targetObj; //目標 public Text targetText; //目標のテキスト public GameObject gameClear; //ゲームクリア時の画像 public GameObject gameOver; //ゲームオーバー時の画像 public GameObject tapCollision; //タッチ判定 private int countTime = 0; //経過時間 private const int RESULT_INTERVAL = 45; //各成績を表示させる間隔 [SerializeField] private int activeCount = 0; //どこの成績を表示させるかの段階 public int sellCount = 0; //売れた個数 public int proceedsMoney = 0; //売り上げ金額 public bool isStageClear = false; //ステージをクリアしたか(目標金額に到達したか) private UIManager uiManagerScript; void Awake() { uiManagerScript = GameObject.Find ("UIManager").GetComponent<UIManager> (); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { countTime++; //成績をINTERVALフレームごとに表示する if (countTime % RESULT_INTERVAL == 0) { switch (activeCount) { case 0: proceedsObj.SetActive (true); //proceedsText.text = proceedsMoney.ToString (); proceedsText.text = uiManagerScript.money.ToString (); activeCount++; break; case 1: sellProductNumObj.SetActive (true); sellProductNumText.text = sellCount.ToString (); activeCount++; break; case 2: targetObj.SetActive (true); targetText.text = uiManagerScript.target.ToString(); activeCount++; break; case 3: if ( uiManagerScript.money >= uiManagerScript.target) { gameClear.SetActive (true); isStageClear = true; SEManager.isSeSound [(int)SEManager.SE_LIST.STAGE_CLEAR] = true; } else { gameOver.SetActive (true); SEManager.isSeSound [(int)SEManager.SE_LIST.STAGE_FAILURE] = true; } tapCollision.SetActive (true); activeCount++; break; default: break; } } } //画面をクリックしてステージ選択画面に戻る public void resultScreenClick() { NextStageLevel (); SceneManager.LoadScene ("StageSelect"); } public void InitResult() { activeCount = 0; sellCount = 0; proceedsMoney = 0; isStageClear = false; proceedsObj.SetActive (false); sellProductNumObj.SetActive (false); targetObj.SetActive (false); gameClear.SetActive (false); gameOver.SetActive (false); } public void NextStageLevel() { Result resultScript = GameObject.Find ("ResultCanvas").GetComponent<Result> (); if (resultScript.isStageClear == true) { //正規仕様 //StageManager.stageLevel++; //we are 仕様 switch(StageManager.stageLevel) { case 1: StageManager.stageLevel = 3; break; case 3: StageManager.stageLevel = 8; break; case 8: StageManager.stageLevel = 9; break; case 9: break; } if (StageManager.stageLevelMax <= StageManager.stageLevel) { StageManager.stageLevelMax = StageManager.stageLevel; } resultScript.isStageClear = false; } } }
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace ItlaSocial.Data.Migrations { public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles"); migrationBuilder.DropIndex( name: "RoleNameIndex", table: "AspNetRoles"); migrationBuilder.AddColumn<DateTime>( name: "BirthDate", table: "AspNetUsers", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<string>( name: "LastName", table: "AspNetUsers", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<string>( name: "Name", table: "AspNetUsers", nullable: false, defaultValue: ""); migrationBuilder.CreateTable( name: "ProfilePhotos", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), AplicationUserId = table.Column<int>(nullable: false), ApplicationUserId = table.Column<string>(nullable: true), Date = table.Column<DateTime>(nullable: false), Deleted = table.Column<bool>(nullable: false), Description = table.Column<string>(nullable: true), MediaUrl = table.Column<string>(nullable: false), PrivacyLevel = table.Column<int>(nullable: false), Reported = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ProfilePhotos", x => x.Id); table.ForeignKey( name: "FK_ProfilePhotos_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Publications", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ApplicationUserId = table.Column<string>(nullable: true), Date = table.Column<DateTime>(nullable: false), Deleted = table.Column<bool>(nullable: false), Description = table.Column<string>(nullable: true), OriginalPublicationId = table.Column<int>(nullable: true), PrivacyLevel = table.Column<int>(nullable: false), Reported = table.Column<bool>(nullable: false), SharedPublicationId = table.Column<int>(nullable: true), Title = table.Column<string>(maxLength: 100, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Publications", x => x.Id); table.ForeignKey( name: "FK_Publications_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Publications_Publications_OriginalPublicationId", column: x => x.OriginalPublicationId, principalTable: "Publications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Publications_Publications_SharedPublicationId", column: x => x.SharedPublicationId, principalTable: "Publications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Comments", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ApplicationUserId = table.Column<string>(nullable: true), Date = table.Column<DateTime>(nullable: false), Deleted = table.Column<bool>(nullable: false), Description = table.Column<string>(nullable: true), OriginalCommentId = table.Column<int>(nullable: true), PublicationId = table.Column<int>(nullable: false), Reported = table.Column<bool>(nullable: false), SuperCommentId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Comments", x => x.Id); table.ForeignKey( name: "FK_Comments_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Comments_Comments_OriginalCommentId", column: x => x.OriginalCommentId, principalTable: "Comments", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Comments_Publications_PublicationId", column: x => x.PublicationId, principalTable: "Publications", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Comments_Comments_SuperCommentId", column: x => x.SuperCommentId, principalTable: "Comments", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PublicationLikes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ApplicationUserId = table.Column<string>(nullable: true), DisLike = table.Column<bool>(nullable: false), PublicationId = table.Column<string>(nullable: true), PublicationId1 = table.Column<int>(nullable: true), UnLike = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PublicationLikes", x => x.Id); table.ForeignKey( name: "FK_PublicationLikes_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_PublicationLikes_Publications_PublicationId1", column: x => x.PublicationId1, principalTable: "Publications", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PublicationMedias", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Date = table.Column<DateTime>(nullable: false), Deleted = table.Column<bool>(nullable: false), Description = table.Column<string>(nullable: true), MediaType = table.Column<int>(nullable: false), MediaUrl = table.Column<string>(nullable: false), PublicationId = table.Column<int>(nullable: false), Reported = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PublicationMedias", x => x.Id); table.ForeignKey( name: "FK_PublicationMedias_Publications_PublicationId", column: x => x.PublicationId, principalTable: "Publications", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CommentLikes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ApplicationUserId = table.Column<string>(nullable: true), CommentId = table.Column<string>(nullable: true), CommentId1 = table.Column<int>(nullable: true), DisLike = table.Column<bool>(nullable: false), UnLike = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_CommentLikes", x => x.Id); table.ForeignKey( name: "FK_CommentLikes_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_CommentLikes_Comments_CommentId1", column: x => x.CommentId1, principalTable: "Comments", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); migrationBuilder.CreateIndex( name: "IX_Comments_ApplicationUserId", table: "Comments", column: "ApplicationUserId"); migrationBuilder.CreateIndex( name: "IX_Comments_OriginalCommentId", table: "Comments", column: "OriginalCommentId"); migrationBuilder.CreateIndex( name: "IX_Comments_PublicationId", table: "Comments", column: "PublicationId"); migrationBuilder.CreateIndex( name: "IX_Comments_SuperCommentId", table: "Comments", column: "SuperCommentId"); migrationBuilder.CreateIndex( name: "IX_CommentLikes_ApplicationUserId", table: "CommentLikes", column: "ApplicationUserId"); migrationBuilder.CreateIndex( name: "IX_CommentLikes_CommentId1", table: "CommentLikes", column: "CommentId1"); migrationBuilder.CreateIndex( name: "IX_ProfilePhotos_ApplicationUserId", table: "ProfilePhotos", column: "ApplicationUserId"); migrationBuilder.CreateIndex( name: "IX_Publications_ApplicationUserId", table: "Publications", column: "ApplicationUserId"); migrationBuilder.CreateIndex( name: "IX_Publications_OriginalPublicationId", table: "Publications", column: "OriginalPublicationId"); migrationBuilder.CreateIndex( name: "IX_Publications_SharedPublicationId", table: "Publications", column: "SharedPublicationId"); migrationBuilder.CreateIndex( name: "IX_PublicationLikes_ApplicationUserId", table: "PublicationLikes", column: "ApplicationUserId"); migrationBuilder.CreateIndex( name: "IX_PublicationLikes_PublicationId1", table: "PublicationLikes", column: "PublicationId1"); migrationBuilder.CreateIndex( name: "IX_PublicationMedias_PublicationId", table: "PublicationMedias", column: "PublicationId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "CommentLikes"); migrationBuilder.DropTable( name: "ProfilePhotos"); migrationBuilder.DropTable( name: "PublicationLikes"); migrationBuilder.DropTable( name: "PublicationMedias"); migrationBuilder.DropTable( name: "Comments"); migrationBuilder.DropTable( name: "Publications"); migrationBuilder.DropIndex( name: "RoleNameIndex", table: "AspNetRoles"); migrationBuilder.DropColumn( name: "BirthDate", table: "AspNetUsers"); migrationBuilder.DropColumn( name: "LastName", table: "AspNetUsers"); migrationBuilder.DropColumn( name: "Name", table: "AspNetUsers"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; namespace DotNetNuke.Services.Social.Messaging { /// <summary> /// Represents the Messaging User Preference /// </summary> [Serializable] public class UserPreference { /// <summary> /// Portal where the preference are applied /// </summary> public int PortalId { get; set; } /// <summary> /// User Identifier /// </summary> public int UserId { get; set; } /// <summary> /// The Email Delivery Frequency used for Messages /// </summary> public Frequency MessagesEmailFrequency { get; set; } /// <summary> /// The Email Delivery Frequency used for Notifications /// </summary> public Frequency NotificationsEmailFrequency { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EFConsole { class Program { static void Main(string[] args) { using (var efDbContext = new EfDbContext()) { efDbContext.Blogs.Add(new Blog() { Name = "Test", Url = "Test" }); efDbContext.SaveChanges(); } } } }
namespace PrimeNumbers.API.Models.Requests { public class CheckIsPrimeNumberRequest { public int? Number { get; set; } } }
namespace WMagic.Brush.Basic { /// <summary> /// 角度范围类 /// </summary> public class GAngle { #region 变量 // 起始角 private double f; // 结束角 private double t; #endregion #region 属性方法 public double F { get { return this.f; } set { this.f = value; } } public double T { get { return this.t; } set { this.t = value; } } #endregion #region 构造函数 public GAngle() : this(0.0, 0.0) { } public GAngle(double f, double t) { this.f = f; this.t = t; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DiceZone : MonoBehaviour { Vector3 diceVelocity; private DiceScript DiceScript; public float diceValue = 0; void Awake() { DiceScript = GameObject.Find("Dice").GetComponent<DiceScript>(); } void FixedUpdate() { diceVelocity = DiceScript.diceVelocity; } public void OnTriggerStay (Collider col) { if (diceVelocity.x == 0f && diceVelocity.y == 0f && diceVelocity.z == 0f) { switch (col.gameObject.name) { case "Side1": diceValue = 6; break; case "Side2": diceValue = 5; break; case "Side3": diceValue = 4; break; case "Side4": diceValue = 3; break; case "Side5": diceValue = 2; break; case "Side6": diceValue = 1; break; } } } void Update() { } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class StunEffect : Effect { private GameObject effectIcon; protected override void Awake() { base.Awake(); effectIcon = enemy.transform.Find("Effects").Find("IconStun").gameObject; } public override IEnumerator ApplyEffectCoroutine() { effectIcon.SetActive(true); enemy.IsStun = true; yield return new WaitForSeconds(duration); effectIcon.SetActive(false); enemy.IsStun = false; Destroy(gameObject); } public override void Interrupt() { StopCoroutine("ApplyEffectCoroutine"); effectIcon.SetActive(false); enemy.IsStun = false; Destroy(gameObject); } }
using Domain.Models; using Infrastructure.ExternalServiceCaller.Proxy; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; namespace Infrastructure.Utils { internal static class CachedCryptoCurrencyHelper { internal static List<CryptoCurrency> ReturnCryptoData(this ConcurrentDictionary<string, CachedCryptoCurrency> cache) { return cache.Values.Select(x => new CryptoCurrency() { Id = x.Id, Code = x.Code, CurrencyQuotes = x.CurrencyQuotes }).ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Moshen.WP7.FAS.Controls { class FavouritePlayerSelectorControl { } }
using System; namespace OCP.Files { /** * Class FileNameTooLongException * * @package OCP\Files * @since 8.1.0 */ class FileNameTooLongException : InvalidPathException { } }
namespace SharpDL.Graphics { public interface ITrueTypeTextFactory { /// <summary>Creates a TTF element to render words from a font. /// </summary> /// <param name="renderer">Renderer from which the text will be drawn</param> /// <param name="fontPath">Path of the font to load for the text</param> /// <param name="text">Text to be drawn</param> /// <param name="fontSize">Size of the font to be drawn</param> /// <returns>TTF element to be rendered</returns> ITrueTypeText CreateTrueTypeText(IRenderer renderer, string fontPath, string text, int fontSize); /// <summary>Creates a TTF element to render words from a font. /// </summary> /// <param name="renderer">Renderer from which the text will be drawn</param> /// <param name="fontPath">Path of the font to load for the text</param> /// <param name="text">Text to be drawn</param> /// <param name="fontSize">Size of the font to be drawn</param> /// <param name="color">Color of the text to be drawn</param> /// <returns>TTF element to be rendered</returns> ITrueTypeText CreateTrueTypeText(IRenderer renderer, string fontPath, string text, int fontSize, Color color); /// <summary>Creates a TTF element to render words from a font. Supports text wrapping. /// </summary> /// <param name="renderer">Renderer from which the text will be drawn</param> /// <param name="fontPath">Path of the font to load for the text</param> /// <param name="text">Text to be drawn</param> /// <param name="fontSize">Size of the font to be drawn</param> /// <param name="color">Color of the text to be drawn</param> /// <param name="wrapLength">Wrap the text at a specific width (line breaks)</param> /// <returns>TTF element to be rendered</returns> ITrueTypeText CreateTrueTypeText(IRenderer renderer, string fontPath, string text, int fontSize, Color color, int wrapLength); } }
using System.Collections.Generic; namespace MvcPL.Models { public class QuestionViewModel { public int Id { get; set; } public string Content { get; set; } public int Cost { get; set; } public string CostView { get { return string.Format("{0} points", this.Cost); } } public IEnumerable<AnswerViewModel> Answers { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GlobalDevelopment.SocialNetworks.Facebook.Interfaces { public interface IFacebookCover { string PhotoID { get; set; } string CoverID { get; set; } string OffsetX { get; set; } string OffsetY { get; set; } string SourceUrl { get; set; } } }
using Plus.HabboHotel.Groups; namespace Plus.Communication.Packets.Outgoing.Groups { internal class ManageGroupComposer : MessageComposer { public Group Group { get; } public string[] BadgeParts { get; } public ManageGroupComposer(Group group, string[] badgeParts) : base(ServerPacketHeader.ManageGroupMessageComposer) { Group = group; BadgeParts = badgeParts; } public override void Compose(ServerPacket packet) { packet.WriteInteger(0); packet.WriteBoolean(true); packet.WriteInteger(Group.Id); packet.WriteString(Group.Name); packet.WriteString(Group.Description); packet.WriteInteger(1); packet.WriteInteger(Group.Colour1); packet.WriteInteger(Group.Colour2); packet.WriteInteger(Group.Type == GroupType.Open ? 0 : Group.Type == GroupType.Locked ? 1 : 2); packet.WriteInteger(Group.AdminOnlyDeco); packet.WriteBoolean(false); packet.WriteString(""); packet.WriteInteger(5); for (int x = 0; x < BadgeParts.Length; x++) { string symbol = BadgeParts[x]; packet.WriteInteger((symbol.Length >= 6) ? int.Parse(symbol.Substring(0, 3)) : int.Parse(symbol.Substring(0, 2))); packet.WriteInteger((symbol.Length >= 6) ? int.Parse(symbol.Substring(3, 2)) : int.Parse(symbol.Substring(2, 2))); packet.WriteInteger(symbol.Length < 5 ? 0 : symbol.Length >= 6 ? int.Parse(symbol.Substring(5, 1)) : int.Parse(symbol.Substring(4, 1))); } int i = 0; while (i < (5 - BadgeParts.Length)) { packet.WriteInteger(0); packet.WriteInteger(0); packet.WriteInteger(0); i++; } packet.WriteString(Group.Badge); packet.WriteInteger(Group.MemberCount); } } }
//----------------------------------------------------------------------- // <copyright file="PwdCommandHandler.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> // <author>Mark Junker</author> //----------------------------------------------------------------------- using System.Threading; using System.Threading.Tasks; using FubarDev.FtpServer.FileSystem; namespace FubarDev.FtpServer.CommandHandlers { /// <summary> /// Implements the <c>PWD</c> command. /// </summary> public class PwdCommandHandler : FtpCommandHandler { /// <summary> /// Initializes a new instance of the <see cref="PwdCommandHandler"/> class. /// </summary> /// <param name="connectionAccessor">The accessor to get the connection that is active during the <see cref="Process"/> method execution.</param> public PwdCommandHandler(IFtpConnectionAccessor connectionAccessor) : base(connectionAccessor, "PWD", "XPWD") { } /// <inheritdoc/> public override Task<FtpResponse> Process(FtpCommand command, CancellationToken cancellationToken) { var path = Connection.Data.Path.GetFullPath(); if (path.EndsWith("/") && path.Length > 1) { path = path.Substring(0, path.Length - 1); } return Task.FromResult(new FtpResponse(257, $"\"{path}\"")); } } }
using System; namespace IMDB.Api.Repositories.Interfaces { public interface IGenreRepository : IGenericRepository<Entities.Genre> { } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace JoveZhao.Framework { public class EnumItemManager { static Hashtable hs = new Hashtable(); public static List<KeyValuePair<T?, string>> GetItemList<T>() where T:struct { var result = hs[typeof(T?)] as List<KeyValuePair<T?, string>>; if (result == null) { var fs = typeof(T).GetFields().Select(p => new { p, att = p.GetCustomAttributes(false).FirstOrDefault(q => q is DescriptionAttribute) as DescriptionAttribute }).Where(p => p.att != null).ToList(); result = new List<KeyValuePair<T?, string>>(); foreach (var f in fs) { T t = (T)Enum.Parse(typeof(T), f.p.GetValue(null).ToString()); result.Add(new KeyValuePair<T?, string>(t, f.att.Description)); } hs[typeof(T)] = result; } return result; } public static string GetDesc(Enum source ) { if (source == null) return string.Empty; var l = GetCustomAttribute(source); if (l == null) return ""; return l.Description; } public static DescriptionAttribute GetCustomAttribute(Enum source) { if (source == null) return null; Type sourceType = source.GetType(); string sourceName = Enum.GetName(sourceType, source); FieldInfo field = sourceType.GetField(sourceName); object[] attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); foreach (object attribute in attributes) { if (attribute is DescriptionAttribute) return attribute as DescriptionAttribute; } return null; } } }
using System; using System.Text; namespace Takistid { class TakistiProov { public static void Main(string[] arg) { Takisti t1 = new Takisti(5, 2); //5 oomi, 2 watti double PatareiPinge = 1.5; //volti if (t1.KasLubatudVõimsusVastavaltPingele(PatareiPinge)) { Console.WriteLine("Patareilt " + PatareiPinge + "V saadakse " + " takistiga " + t1.LeiaTakistus() + " oomi vool " + t1.LeiaVool(PatareiPinge) + "A ja " + " võimsus " + t1.LeiaV6imsus(PatareiPinge) + "W"); } else { Console.WriteLine("Pingel "+PatareiPinge+"V tekkiv võimsus "+ t1.LeiaV6imsus(PatareiPinge, false)+"W ületab lubatud "+ "võimsust "+t1.LeiaMaksimumV6imsus()+"W"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using Entities.Concrete; using Microsoft.EntityFrameworkCore; namespace DataAccess.Concrete.EntityFramework { public class SalesTrackingContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"server=.;Database=salestracking;trusted_connection=true;"); } public DbSet<Dealer> Dealers { get; set; } public DbSet<Packet> Packets { get; set; } public DbSet<Status> Status { get; set; } public DbSet<User> Users { get; set; } } }
namespace Dealership.Engine.Commands { using System; using System.Collections.Generic; using System.Linq; using Common; using Common.Enums; using Contracts; using Contracts.Factories; public class RegisterUser : Command { protected override bool CanExecute(string commandName) { var result = !string.IsNullOrWhiteSpace(commandName) && commandName.ToLower() == Constants.RegisterUserCommandName.ToLower(); return result; } protected override string StartExecute( IList<string> commandAsList, IVehicleFactory vehicleFactory, IDealershipFactory dealershipFactory, ICollection<IUser> users, IUser[] loggedUser) { var username = commandAsList[1]; var firstName = commandAsList[2]; var lastName = commandAsList[3]; var password = commandAsList[4]; var role = Role.Normal; if (commandAsList.Count > 5) { role = (Role)Enum.Parse(typeof(Role), commandAsList[5]); } if (loggedUser[0] != null) { return string.Format(Constants.UserLoggedInAlready, loggedUser[0].Username); } if (users.Any(u => u.Username.ToLower() == username.ToLower())) { return string.Format(Constants.UserAlreadyExist, username); } var user = dealershipFactory.CreateUser(username, firstName, lastName, password, role.ToString()); loggedUser[0] = user; users.Add(user); return string.Format(Constants.UserRegisterеd, username); } } }
using UnityEngine; namespace UnityExtensions.Audio.Components.Controllers { public abstract class AAudioController : MonoBehaviour { #region Attributes protected AudioSource m_audioSource; #endregion Attributes #region Methods #region Accessors and Mutators //_____________________________________________________________________ ACCESSORS AND MUTATORS _____________________________________________________________________ #endregion Accessors and Mutators #region Inherited Methods //_______________________________________________________________________ INHERITED METHODS _______________________________________________________________________ // Use this for initialization protected void Start() { m_audioSource = GetComponentInChildren<AudioSource>(); } #endregion Inherited Methods #region Events //_____________________________________________________________________________ EVENTS _____________________________________________________________________________ #endregion Events #region Other Methods //__________________________________________________________________________ OTHER METHODS _________________________________________________________________________ #endregion Other Methods #endregion Methods } }
using LeoESCTest.Components; using Leopotam.Ecs; using UnityEngine; using Object = UnityEngine.Object; namespace LeoESCTest.UnityComponents.EntityTemplates { public class UnityObjectTemplateBase<T> : MonoBehaviour, IEntityTemplate where T : Object { [SerializeField] private T _object; public void Create(EcsEntity entity) { entity.Replace(new UnityObjectComponent<T> {Object = _object}); } } }
namespace E05_Workdays { using System; public class Workdays { public static void Main(string[] args) { // Write a method that calculates the number of // workdays between today and given date, passed // as parameter. // Consider that workdays are all days from Monday // to Friday except a fixed list of public holidays // specified preliminary as array. // example: // date workdays // 31/12/2015 221 CalculateWorkdays(); } private static void CalculateWorkdays() { Console.WriteLine("Calculate the number of workdays " + "between today and given date in 2015."); DateTime startDate = DateTime.Today; Console.WriteLine("Today is : {0:dd/MM/yyyy}", startDate); DateTime endDate = new DateTime(); endDate = GetDate("date you want"); Console.WriteLine(); int workdays = (int)(endDate - startDate).TotalDays; if (workdays < 0) { workdays *= -1; } workdays += 1; // add the current day workdays -= FilterWeekend(startDate, endDate); workdays -= FilterHolidays(startDate, endDate); Console.WriteLine("The business days in this interval are : {0}", workdays); } private static int FilterWeekend(DateTime start, DateTime end) { if (end < start) return FilterWeekend(end, start); int result = 0; for (DateTime weekend = start; weekend <= end; weekend = weekend.AddDays(1)) { if (weekend.DayOfWeek == DayOfWeek.Saturday || weekend.DayOfWeek == DayOfWeek.Sunday) { result++; } } return result; } private static int FilterHolidays(DateTime start, DateTime end) { if (end < start) return FilterHolidays(end, start); int result = 0; DateTime[] holidays = { new DateTime(2015, 01, 01), new DateTime(2015, 03, 03), new DateTime(2015, 04, 10), new DateTime(2015, 04, 13), new DateTime(2015, 05, 01), new DateTime(2015, 05, 06), new DateTime(2015, 05, 24), new DateTime(2015, 09, 06), new DateTime(2015, 09, 22), new DateTime(2015, 12, 24), new DateTime(2015, 12, 25), }; foreach (DateTime holiday in holidays) { if (start < holiday && holiday < end && !(holiday.DayOfWeek == DayOfWeek.Saturday || holiday.DayOfWeek == DayOfWeek.Sunday)) { result++; } } return result; } private static DateTime GetDate(string name) { DateTime date = DateTime.MinValue; bool isDate = false; do { Console.Write("Please, enter {0}: ", name); isDate = DateTime.TryParse(Console.ReadLine(), out date); } while (isDate == false); return date; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace tayana_draft_2.backend { public partial class WebForm4 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { lblErrorMessage.Visible = false; lblErrorMessage1.Visible = false; } protected void RegoSubmit(object sender, EventArgs e) { string config = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["TayanaConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(config); string Cmd = "SELECT * FROM TayanaUserTable WHERE username = @username"; SqlCommand command = new SqlCommand(Cmd, conn); conn.Open(); command.Parameters.AddWithValue("@Username", Session["username"].ToString()); SqlDataReader datareader = command.ExecuteReader(); datareader.Read(); if (txtUsername.Text != datareader["username"].ToString()) { datareader.Close(); string query = "INSERT INTO TayanaUserTable (FName, SName, Email, UserName, Password, CPassword, isAdmin) VALUES (@txtFname, @txtSname, @txtEmail, @txtUserName, @txtPassword, @txtCpassword, @CheckBox1)"; SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.AddWithValue("@txtFname", txtFname.Text); cmd.Parameters.AddWithValue("@txtSname", txtSname.Text); cmd.Parameters.AddWithValue("@txtEmail", txtEmail.Text); cmd.Parameters.AddWithValue("@txtUserName", txtUsername.Text); cmd.Parameters.AddWithValue("@txtPassword", txtPassword.Text); cmd.Parameters.AddWithValue("@txtCpassword", txtCpassword.Text); cmd.Parameters.AddWithValue("@CheckBox1", GetCheck()); cmd.ExecuteNonQuery(); conn.Close(); Response.Redirect(this.Request.Url.ToString()); } else { Server.Transfer("rego.aspx"); lblErrorMessage1.Text = "THE USERNAME HAS BEEN TAKEN, TRY A DIFFERENT ONE."; } Response.Redirect("Content_Cut.aspx"); } protected string GetCheck() { string v = ""; foreach (ListItem item in CheckBoxList1.Items) { if (item.Selected == true) { if (v.Length > 0) { v += ","; } v += item.Value; } } return v; } protected void Button1_OnClick(object sender, EventArgs e) { Response.Redirect("Content_Cut.aspx"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ModuleContainer { private Module module; private int x, y; private bool isPossible = true; public Module Module { get => module; set => module = value; } public bool IsPossible { get => isPossible; set => isPossible = value; } public int X { get => x; set => x = value; } public int Y { get => y; set => y = value; } public ModuleContainer(Module module, int x, int y) { this.isPossible = true; this.module = module; this.x = x; this.y = y; } }
using System; using System.Collections.Generic; namespace NChampions.Application.ViewModels { public class ChampionshipViewModel { public Guid Id { get; set; } public string ChampionshipName { get; set; } public bool isActive { get; set; } public IList<TeamViewModel> ChampionshipTeams { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("UIBHighlight")] public class UIBHighlight : MonoBehaviour { public UIBHighlight(IntPtr address) : this(address, "UIBHighlight") { } public UIBHighlight(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void HighlightOnce() { base.method_8("HighlightOnce", Array.Empty<object>()); } public void OnPress() { base.method_9("OnPress", new Class272.Enum20[0], Array.Empty<object>()); } public void OnPress(bool playSound) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Boolean }; object[] objArray1 = new object[] { playSound }; base.method_9("OnPress", enumArray1, objArray1); } public void OnRelease() { base.method_9("OnRelease", new Class272.Enum20[0], Array.Empty<object>()); } public void OnRelease(bool playSound) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Boolean }; object[] objArray1 = new object[] { playSound }; base.method_9("OnRelease", enumArray1, objArray1); } public void OnRollOut(bool force) { object[] objArray1 = new object[] { force }; base.method_8("OnRollOut", objArray1); } public void OnRollOver(bool force) { object[] objArray1 = new object[] { force }; base.method_8("OnRollOver", objArray1); } public void PlaySound(string soundFilePath) { object[] objArray1 = new object[] { soundFilePath }; base.method_8("PlaySound", objArray1); } public void Reset() { base.method_8("Reset", Array.Empty<object>()); } public void ResetState() { base.method_8("ResetState", Array.Empty<object>()); } public void Select() { base.method_8("Select", Array.Empty<object>()); } public void SelectNoSound() { base.method_8("SelectNoSound", Array.Empty<object>()); } public void ShowHighlightObject(GameObject obj, bool show) { object[] objArray1 = new object[] { obj, show }; base.method_8("ShowHighlightObject", objArray1); } public bool AlwaysOver { get { return base.method_11<bool>("get_AlwaysOver", Array.Empty<object>()); } } public bool EnableResponse { get { return base.method_11<bool>("get_EnableResponse", Array.Empty<object>()); } } public bool m_AllowSelection { get { return base.method_2<bool>("m_AllowSelection"); } } public bool m_AlwaysOver { get { return base.method_2<bool>("m_AlwaysOver"); } } public bool m_EnableResponse { get { return base.method_2<bool>("m_EnableResponse"); } } public bool m_HideMouseOverOnPress { get { return base.method_2<bool>("m_HideMouseOverOnPress"); } } public GameObject m_MouseDownHighlight { get { return base.method_3<GameObject>("m_MouseDownHighlight"); } } public string m_MouseDownSound { get { return base.method_4("m_MouseDownSound"); } } public string m_MouseOutSound { get { return base.method_4("m_MouseOutSound"); } } public GameObject m_MouseOverHighlight { get { return base.method_3<GameObject>("m_MouseOverHighlight"); } } public GameObject m_MouseOverSelectedHighlight { get { return base.method_3<GameObject>("m_MouseOverSelectedHighlight"); } } public string m_MouseOverSound { get { return base.method_4("m_MouseOverSound"); } } public GameObject m_MouseUpHighlight { get { return base.method_3<GameObject>("m_MouseUpHighlight"); } } public string m_MouseUpSound { get { return base.method_4("m_MouseUpSound"); } } public PegUIElement m_PegUIElement { get { return base.method_3<PegUIElement>("m_PegUIElement"); } } public GameObject m_SelectedHighlight { get { return base.method_3<GameObject>("m_SelectedHighlight"); } } public bool m_SelectOnRelease { get { return base.method_2<bool>("m_SelectOnRelease"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Pada1.BBCore.Tasks; using Pada1.BBCore; namespace BBUnity.Actions { [Action("EnemyBehaviour/MeleeAttackAction")] [Help("Attacks")] public class MeleeAttackAction : GOAction { [InParam("enemyBody")] public EnemyBody enemyBody; public AIUtilities.Timer timer; [InParam("attack")] public CloseCombatAttacks attack; [InParam("animator")] public Animator animator; [InParam("stats")] public EnemyStatistics stats; [InParam("InitAttack")] public bool initAttack; public override void OnStart() { if (timer == null) { timer = new AIUtilities.Timer(stats.GetStatValue(StatName.AttackRate)); if (!attack.canAttack && !timer.timerStarted) timer.StartTimer(() => SetCanAttack()); } else if (!attack.canAttack && !timer.timerStarted) { timer.StartTimer(() => SetCanAttack()); } if(attack.canAttack) { StartAttack(); } } public override TaskStatus OnUpdate() { if (attack.isAttacking) { // gameObject.transform.position = animator.rootPosition; return TaskStatus.RUNNING; } else { timer.StartTimer(() => SetCanAttack()); return TaskStatus.COMPLETED; } } private void StartAttack() { attack.Attack(); timer.setWaitTime(stats.GetStatValue(StatName.AttackRate)); attack.canAttack = false; initAttack = false; } public void SetCanAttack() { attack.canAttack = true; } public override void OnAbort() { timer.StartTimer(() => SetCanAttack()); attack.CancelAttack(); } } }
using System; using System.Collections.Generic; namespace BO { public class Excursion: AbstractIdentifiable { public string Name { get; set; } public DateTime Date { get; set; } public int NbPlaces { get; set; } public virtual ICollection<PersonsExcursions> SubscribePeople { get; set; } = new List<PersonsExcursions>(); public virtual Activity Activity { get; set; } public virtual Person Creator { get; set; } public virtual Weather Weather { get; set; } } }
using Payment.Data.Session; namespace Payment.Data { public class Database : IDatabase { private ISession Session { get; } public Database(ISession session) { Session = session; } public T Query<T>(IQuery<T> query) { return query.Execute(Session); } public void Execute(ICommand command) { command.Execute(Session); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlazorApp.Services { public class Oda { public int OdaId { get; set; } public int BinaId { get; set; } public int OdaM2 { get; set; } public int OdaFiyati { get; set; } public int OdaKati { get; set; } public string Acıklama { get; set; } } }
using System; using Xunit; namespace LearningCSharp { public class UnitTest1 { [Fact] public void Test1() { //Given (Arrange) int a = 10, b = 20, answer; //When (Act) answer = a + b; //Then (Assert) Assert.Equal(30, answer); } [Fact] public void CanCountTheLettersInAString() { var name = "Peter"; Assert.Equal(5, name.Length); } [Theory] [InlineData(2,2,4)] [InlineData(10,3,13)] [InlineData(18,2,20)] [InlineData(8,8,16)] public void CanAddTwoNumbers(int a, int b, int expected) { var answer = a + b; Assert.Equal(expected, answer); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace QuickCollab.Models { public class StartSettingsViewModel { public StartSettingsViewModel() { Public = true; } [Required(ErrorMessage="Please enter a session name")] [MaxLength(50)] public string SessionName { get; set; } public bool Public { get; set; } public bool PersistHistory { get; set; } public bool Secured { get; set; } [MinLength(8)] public string SessionPassword { get; set; } [Display(Name = "Connection Expiry")] public int ConnectionExpiryInHours { get; set; } public IEnumerable<SelectListItem> ConnectionExpiryOptions { get { List<SelectListItem> connectionExpiryOptions = new List<SelectListItem>(); connectionExpiryOptions.Add(new SelectListItem() { Text = "1 hour", Value = "1" }); connectionExpiryOptions.Add(new SelectListItem() { Text = "2 hours", Value = "2" }); connectionExpiryOptions.Add(new SelectListItem() { Text = "3 hours", Value = "3" }); connectionExpiryOptions.Add(new SelectListItem() { Text = "12 hours", Value = "12" }); connectionExpiryOptions.Add(new SelectListItem() { Text = "24 hours", Value = "24" }); connectionExpiryOptions.Add(new SelectListItem() { Text = "48 hours", Value = "48" }); connectionExpiryOptions.Add(new SelectListItem() { Text = "72 hours", Value = "72" }); return connectionExpiryOptions; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Erwine.Leonard.T.LoggingModule.ExtensionMethods { public static class TypeExtensions { public static readonly Regex GenericNameEnding = new Regex(@"(~\d+)+$", RegexOptions.Compiled); public static Type[] GetAllElementTypes(this IEnumerable enumerable) { if (enumerable == null) return null; Type elementType = enumerable.GetType().GetEnumeratedElementType(); if (elementType != null && (elementType.Equals(typeof(string)) || elementType.GetNullableUnderlyingOrType().IsValueType)) return new Type[] { elementType }; Type[] allDistinct = enumerable.Cast<object>().Where(o => o != null).Select(o => o.GetType()).Distinct().ToArray(); if (allDistinct.Length == 0 && elementType != null) return new Type[] { elementType }; if (allDistinct.All(t => t.IsValueType) && enumerable.Cast<object>().Any(o => o == null)) return allDistinct.Concat(new Type[] { typeof(object) }).ToArray(); return allDistinct; } public static Type GetNullableUnderlyingOrType(this Type type) { if (type != null && type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) return Nullable.GetUnderlyingType(type); return type; } public static Type GetDictionaryKeyType(this Type type) { if (type == null) return null; Type g = type.GetInterfacesOfGenericType(typeof(IDictionary<,>)).FirstOrDefault(); if (g != null) return g.GetGenericArguments()[0]; g = typeof(IDictionary); if (type.GetInterfaces().Any(t => t.Equals(g))) return typeof(object); return null; } public static Type GetDictionaryValueType(this Type type) { if (type == null) return null; Type g = type.GetInterfacesOfGenericType(typeof(IDictionary<,>)).FirstOrDefault(); if (g != null) return g.GetGenericArguments()[1]; g = typeof(IDictionary); if (type.GetInterfaces().Any(t => t.Equals(g))) return typeof(object); return null; } public static Type GetEnumeratedElementType(this Type type) { if (type == null) return null; if (type.IsArray) return type.GetElementType(); Type g = type.GetInterfacesOfGenericType(typeof(IEnumerable<>)).FirstOrDefault(); if (g != null) return g.GetGenericArguments()[0]; g = typeof(IEnumerable); if (type.GetInterfaces().Any(t => t.Equals(g))) return typeof(object); return null; } public static IEnumerable<Type> GetInterfacesOfGenericType(this Type type, Type genericTypeDefinition) { Type g = (genericTypeDefinition.IsGenericTypeDefinition) ? genericTypeDefinition : genericTypeDefinition.GetGenericTypeDefinition(); return type.GetInterfaces().Where(t => t.IsGenericType && t.GetGenericTypeDefinition().Equals(g)); } public static string ToXmlElementName(this Type type) { string elementName = (type == null || type.Equals(typeof(object))) ? "Any" : TypeExtensions.GenericNameEnding.Replace(type.Name, ""); return (type.IsArray && elementName != "Array") ? String.Format("ArrayOf{0}", elementName.Substring(elementName.Length - 2)) : elementName; } public static string ToCSharpTypeName(this Type type) { if (type == null || type.Equals(typeof(object))) return "object"; string typeName; if (type.IsArray) { int n = type.GetArrayRank(); typeName = type.GetElementType().ToCSharpTypeName(); for (int i = 0; i < n; i++) typeName += "[]"; return typeName; } if (type.IsPrimitive) { TypeCode tc = Type.GetTypeCode(type); switch (tc) { case TypeCode.Boolean: return "bool"; case TypeCode.Int16: return "short"; case TypeCode.Int32: return "int"; case TypeCode.Int64: return "long"; case TypeCode.Single: return "float"; case TypeCode.UInt16: return "ushort"; case TypeCode.UInt32: return "uint"; case TypeCode.UInt64: return "ulong"; case TypeCode.DateTime: case TypeCode.DBNull: case TypeCode.Empty: return tc.ToString("F"); default: return tc.ToString("F").ToLower(); } } typeName = TypeExtensions.GenericNameEnding.Replace(type.FullName, ""); if (type != null && type.IsGenericType) return String.Format("{0}<{1}>", typeName, String.Join(", ", type.GetGenericArguments().Select(a => a.ToCSharpTypeName()).ToArray())); return typeName; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DetectZaynPassingThrough : MonoBehaviour { Animator myAnim; private void Start() { myAnim = GetComponent<Animator>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { myAnim.SetBool("Crossed", false); myAnim.SetTrigger("Pastro"); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag == "Player") { myAnim.SetBool("Crossed", true); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using UnityEngine.UI; public class DoTweenExample_ZH : MonoBehaviour { public Image _Image; private Tween _Tween; private int _Number = 0; void Start() { //移动 //transform.DOMove(Vector3.one * 5, 1); //transform.DOBlendableMoveBy(new Vector3(0, 3, 0), 1); //ransform.DOBlendableLocalMoveBy(new Vector3(0, 3, 0), 1); //缩放 //transform.DOScaleY(3, 1); //transform.DOBlendableScaleBy(new Vector3(0, 3, 0), 1); //旋转 //transform.DORotate(new Vector3(0, 30, 0), 1); //transform.DOBlendableRotateBy(new Vector3(0, 30, 0), 1); //transform.DOBlendableLocalRotateBy(new Vector3(0, 30, 0), 1); //中止 //transform.DOPause(); //相对移动 //transform.DOMove(Vector3.one * 5, 2); //transform.DOMove(Vector3.one * 5, 2).From(); //循环 -1 表示无限循环 //transform.DOMove(Vector3.one * 5, 2).SetRelative().SetLoops(-1, LoopType.Yoyo); //DOTween.To(() => transform.position, x => transform.position = x, new Vector3(0, 3, 0), 1).SetRelative().SetLoops(-1,LoopType.Yoyo); //混合移动 缩放 旋转 //transform.DOBlendableLocalMoveBy(new Vector3(0, 3, 0), 1); //transform.DOBlendableRotateBy(new Vector3(0,30,0),1).SetRelative().SetLoops(-1, LoopType.Yoyo); // 2D 图片旋转 //_Tween = _Image.transform.DOLocalRotate(new Vector3(0,0,90), 1,RotateMode.LocalAxisAdd).SetEase(Ease.Linear).SetLoops(1,LoopType.Incremental); //图片透明通道消减 停止播放 //_Image.DOFade(0, 2).SetAutoKill(false);//.Pause() //图片颜色渐变 //_Image.DOColor(RandomColor(), 2); //DoTween 回调函数执行 _Tween = DOTween.To(() => _Number, x => _Number = x, 2, 5); //起始执行 _Tween.OnStart(OnStarTween); //类似Update执行 _Tween.OnUpdate(() => UpdateTween(_Number)); //如果油循环执行的方法 则方法执行一次 如果不是循环 则完成执行 _Tween.OnStepComplete(OnStepComplete); //完成所有回调函数 再执行 _Tween.OnComplete(OnComplete); //最后执行 只回调一次 _Tween.OnKill(OnKill); } public void OnClickStar() { //播放该物体所有的DOTween 动画 DOTween.PlayAll(); } public Color RandomColor() { Color _Color; _Color = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)); return _Color; } //起始执行 private void OnStarTween() { print("OnStarTween"); } //类似Update执行 private void UpdateTween(int Number) { print(Number); } //如果油循环执行的方法 则方法执行一次 如果不是循环 则完成执行 private void OnStepComplete() { print("OnStepComplete"); } //完成所有回调函数 再执行 private void OnComplete() { print("OnComplete"); } //最后执行 只回调一次 private void OnKill() { print("OnKill"); } }
using UnityEngine; using System.Collections; public class UnitStats : MonoBehaviour { public float m_health; public float m_armour; public float m_attack; public bool m_isDefending; public int m_actionPoints; public float Health { get { return m_health; } set { m_health = value; if (m_health <= 0) { //die } } } public float Armour { get { return m_armour; } set { m_armour = value; m_armour = m_armour < 0 ? 0 : value; } } public void Constructor(float a_health = 25, float a_armour = 10, float a_attack = 10, bool a_defending = false, int a_ap = 2) { m_health = a_health; m_armour = a_armour; m_attack = a_attack; m_isDefending = a_defending; m_actionPoints = a_ap; } }
namespace Lonely { public class Guardian : Enemy { public override bool hasTitanSheild { get { return _fsm.hasTitanSheild; } } private readonly GuardianFSM _fsm; public Guardian(GuardianFSM fsm) : base() { _fsm = fsm; } protected override void Initialize() { _fsm.ChangeState<EnemyState_Idle>(); } public override void Die() { _fsm.ChangeState<EnemyState_Die>(); } public override void Turn() { _fsm.EnemyTurn(); } } }
using System; using System.Collections.Generic; using tryfsharplib; using Xamarin.Forms; using Syncfusion.SfChart.XForms; using System.Collections.ObjectModel; using Syncfusion.SfBusyIndicator.XForms; namespace tryfsharpforms { public partial class CompareTwoStocksChartPage : ContentPage { public CompareTwoStocksChartPage (IEnumerable<Tuple<DateTime, decimal>> priceList1, IEnumerable<Tuple<DateTime, decimal>> priceList2, string ticker1, string ticker2) { InitializeComponent (); Title = ticker1.ToUpper() + " vs " + ticker2.ToUpper(); BackgroundColor = MyColors.MidnightBlue; series1.Color = MyColors.Turqoise; series2.Color = MyColors.Carrot; series1.Label = ticker1.ToUpper (); series2.Label = ticker2.ToUpper (); var svm = new StocksViewModel (priceList1, priceList2); BindingContext = svm; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SFP.SIT.SERV.Model.RESP { public class SIT_RESP_RREVISION { public Int64 repclave { set; get; } public SIT_RESP_RREVISION () {} } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GlobalDevelopment.SocialNetworks.Facebook.Models { public class FacebookEntityAtTextRange { /// <summary> /// ID of the profile. /// </summary> public string ID { get; set; } /// <summary> /// Number of characters in the text indicating the object. /// </summary> public int Length { get; set; } /// <summary> /// Name of the object. /// </summary> public string Name { get; set; } /// <summary> /// The object itself. /// </summary> public FacebookProfile Object { get; set; } /// <summary> /// The character offset in the source text of the text indicatin the object. /// </summary> public int Offset { get; set; } /// <summary> /// Type of the object. /// </summary> public string Type { get; set; } public FacebookEntityAtTextRange(JToken token) { JObject obj = JObject.Parse(token.ToString()); ID = (obj["id"] ?? "NA").ToString(); Length = int.Parse((obj["length"] ?? "0").ToString()); Name = (obj["name"] ?? "NA").ToString(); Object = new FacebookProfile(obj["object"]); Offset = int.Parse((obj["offset"] ?? "0").ToString()); Type = (obj["type"] ?? "NA").ToString(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Beamore.DAL.Configurations { public static class ConfigurationHelpers { public static string CONNECTION_STRING { get { return ConfigurationManager.ConnectionStrings["DataContext"].ConnectionString; } } } }
 using System; using System.Linq; using System.Web; using NopSolutions.NopCommerce.BusinessLogic; using NopSolutions.NopCommerce.BusinessLogic.Categories; using NopSolutions.NopCommerce.BusinessLogic.Content.NewsManagement; using NopSolutions.NopCommerce.BusinessLogic.Content.Topics; using NopSolutions.NopCommerce.BusinessLogic.Products; using NopSolutions.NopCommerce.BusinessLogic.SEO; using NopSolutions.NopCommerce.Common.Utils; namespace NopSolutions.NopCommerce.Web.MasterPages { public partial class root : BaseNopMasterPage { private void Page_Load(object sender, EventArgs e) { System.Web.SiteMap.Providers["NopDefaultXmlSiteMapProvider"].SiteMapResolve += this.ExpandCategoryPaths; } private SiteMapNode ExpandCategoryPaths(Object sender, SiteMapResolveEventArgs e) { SiteMapNode currentNode = null; if(NewsId != 0) { currentNode = ChangeNewsMap(e); } else if (TopicId != 0) { currentNode = ChangeTopicMap(e); } else { if (CategoryId != 0) { if (e.Provider.CurrentNode == null) { currentNode = e.Provider.FindSiteMapNode("~/Sitemap-Categories.aspx").Clone(true); } else { currentNode = e.Provider.CurrentNode.Clone(true); } ChangeCategoryMap(e, currentNode); } if (0 != ProductId) { currentNode = ChangeProductMap(e, currentNode); } } return currentNode; } private SiteMapNode ChangeNewsMap(SiteMapResolveEventArgs siteMapResolveEventArgs) { SiteMapNode currentNode = null; try { currentNode = siteMapResolveEventArgs.Provider.FindSiteMapNode("~/Sitemap-News.aspx").Clone(true); News news = NewsManager.GetNewsByID(NewsId); if (news != null) { currentNode.Url = SEOHelper.GetNewsURL(news); currentNode.Description = news.Title; currentNode.Title = news.Title; } } catch { } return currentNode; } private SiteMapNode ChangeProductMap(SiteMapResolveEventArgs e, SiteMapNode parent) { SiteMapNode currentProductNode = e.Provider.FindSiteMapNode("~/Sitemap-Products.aspx").Clone(true); try { SiteMapNode tempNode = currentProductNode; Product product = ProductManager.GetProductByID(ProductId); tempNode.Url = SEOHelper.GetProductURL(product.ProductID); tempNode.Description = product.Name; tempNode.Title = product.Name; tempNode.ParentNode = parent; } catch { } return currentProductNode; } private SiteMapNode ChangeTopicMap(SiteMapResolveEventArgs e) { SiteMapNode currentNode = null; try { currentNode = e.Provider.FindSiteMapNode("~/Sitemap-Topics.aspx").Clone(true); LocalizedTopic localizedTopic = TopicManager.GetLocalizedTopic(this.TopicId, NopContext.Current.WorkingLanguage.LanguageID); if (localizedTopic != null) { currentNode.Url = SEOHelper.GetTopicUrl(TopicId, localizedTopic.Title); currentNode.Description = localizedTopic.Title; currentNode.Title = localizedTopic.Title; } } catch { } return currentNode; } private void ChangeCategoryMap(SiteMapResolveEventArgs e, SiteMapNode currentNode) { try { SiteMapNode tempNode = currentNode; Category category = CategoryManager.GetCategoryByID(CategoryId); if (0 != CategoryId) { tempNode.Url = SEOHelper.GetCategoryURL(category.CategoryID); CategoryCollection categCollection = CategoryManager.GetBreadCrumb(category.CategoryID); string categoryPath = categCollection.Aggregate(String.Empty, (current, c) => current + String.Format( String.IsNullOrEmpty(current) ? "{0}" : "/{0}", c.Name)); tempNode.Title = categoryPath; tempNode.Description = categoryPath; } } catch { } } public int CategoryId { get { int categoryId = CommonHelper.QueryStringInt("CategoryID"); try { if (categoryId == 0) { Product product = ProductManager.GetProductByID(ProductId); if (product != null) { categoryId = product.ProductCategories.Find(p => p.Category.ParentCategory != null).CategoryID; } } } catch{//do nothing } return categoryId; } } public int ProductId { get { return CommonHelper.QueryStringInt("ProductID"); } } public int TopicId { get { return CommonHelper.QueryStringInt("TopicID"); } } public int NewsId { get { return CommonHelper.QueryStringInt("NewsID"); } } } }
using System; using System.Collections; using System.Linq; using State.Active; using Util; namespace Ads.State { public class VideoAdStateGate : ActiveGate { public AdType Type = AdType.Interstitial; public bool Invert; public bool AndDestroy; public VideoAdState[] States; private VideoAd _ad; private VideoAdState _state = VideoAdState.None; public override void Register(ActiveManager manager) { base.Register(manager); Objects.StartCoroutine(Init()); } public override void Unregister() { base.Unregister(); if (_ad != null) _ad.OnState -= OnState; } private IEnumerator Init() { for (;;) { switch (Type) { case AdType.Interstitial: _ad = StencilAds.Interstitial; break; case AdType.Rewarded: _ad = StencilAds.Rewarded; break; } if (_ad != null) break; yield return null; } _ad.OnState += OnState; } private void OnState(object sender, VideoAdState e) { _state = e; RequestCheck(); } public override bool? Check() { try { var visible = States.Contains(_state); if (Invert) visible = !visible; if (AndDestroy && !visible) Destroy(gameObject); return visible; } catch (Exception) { return null; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Jieshai.Pinyin { public class PinyinProvider { static Dictionary<string, string> ZikuPinyinDic; static PinyinProvider() { ZikuPinyinDic = ZikuLoader.LoadZiku("字库"); } public virtual bool TryGetPinyin(char hanzi, out string pinyin) { pinyin = string.Empty; if (ZikuPinyinDic.ContainsKey(hanzi.ToString())) { pinyin = ZikuPinyinDic[hanzi.ToString()]; return true; } return false; } /// <summary> /// 获取拼音简码 /// </summary> /// <param name="unicodeString"></param> /// <returns></returns> public string GetJianma(string str) { string pinyin; string jianma = ""; foreach (char hanzi in str) { if(this.TryGetPinyin(hanzi, out pinyin)) { jianma += pinyin[0]; } else { jianma += hanzi.ToString(); } } return jianma; } /// <summary> /// 获取全拼 /// </summary> /// <param name="unicodeString"></param> /// <returns></returns> public string GetQuanpin(string str) { string pinyin; string jianma = ""; foreach (char hanzi in str) { if (hanzi == ' ') { continue; } if (this.TryGetPinyin(hanzi, out pinyin)) { jianma += pinyin; } else { jianma += hanzi.ToString(); } } return jianma; } } }
using Microsoft.AspNetCore.Mvc; using MVCAppAssignment2.Models.Service; using MVCAppAssignment2.Models.ViewModel; namespace MVCAppAssignment2.Controllers { public class PeopleController : Controller { private IPeopleService MyService = new PeopleService(); //CreatePerson addPerson = new CreatePerson(); // bara för att debugga med Runar [HttpGet] public IActionResult Index() { /*addPerson.FirstName = "Runar"; // bara för att debugga addPerson.LastName = "Bengtsson"; MyService.Add(addPerson);*/ return View(MyService.All()); // (Denna innehåller nu en static lista på alla personer) } [HttpGet] public IActionResult Remove(int Id) { MyService.Remove(Id); return RedirectToAction(nameof(Index)); } [HttpGet] public IActionResult Edit(int Id) { return RedirectToAction(nameof(Index)); } [HttpPost] public IActionResult Filter(People theModel) // Still "" in datafields { // Eftersom inte datat kommer in ordentligt fungerar inte IsValid heller. People returnList = new People(); returnList = MyService.FindBy(theModel); ModelState.Clear(); return View("Index", returnList); } [HttpPost] public IActionResult Create(People theModel) // Still "" in datafields { if (ModelState.IsValid) // Eftersom inte datat kommer in ordentligt fungerar inte IsValid heller. { MyService.Add(theModel.Person); return RedirectToAction(nameof(Index)); //The RedirectToAction() method makes new requests, and URL in the } // browser's address bar is updated with the generated URL by MVC. return View("Index", MyService.All()); } } }
using UnityEngine; using System.Collections; public class Quit : MonoBehaviour { void OnTriggerEnter (Collider other) { MainMenuController.Quit (); } }
namespace Components.User { using Components.Core.DataAccess.Base.Interfaces; using Components.User.Automapper.Profiles; using Components.User.Business; using Components.User.Persistance; using Components.User.Persistance.Poco; using Components.User.Persistance.Repository; using Components.User.Persistance.UnitOfWork; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; public static class UserComponentExtension { public static IServiceCollection AddUserComponent(this IServiceCollection services) { services.AddInternalUserComponent(); return services; } private static IServiceCollection AddInternalUserComponent(this IServiceCollection services) { services.AddDbContext<UserDbContext>(optionsBuilder => { optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=Components.User;Trusted_Connection=True;"); }); services.AddAutoMapper(typeof(UserDomainProfile)); services.AddScoped<UserUnitOfWork>(); services.AddScoped<IUnitOfWorkWithDbContext<UserDbContext, User>>(s => s.GetService<UserUnitOfWork>()); services.AddScoped<IUserUnitOfWork>(s => s.GetService<UserUnitOfWork>()); services.AddScoped<IUserBusiness, UserBusiness>(); services.AddScoped<IUserRepository, UserRepository>(); return services; } } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.Files.Cache { /** * Scan files from the storage and save to the cache * * @since 9.0.0 */ public interface IScanner { //const SCAN_RECURSIVE_INCOMPLETE = 2; // only recursive into not fully scanned folders //const SCAN_RECURSIVE = true; //const SCAN_SHALLOW = false; //const REUSE_NONE = 0; //const REUSE_ETAG = 1; //const REUSE_SIZE = 2; /** * scan a single file and store it in the cache * * @param string file * @param int reuseExisting * @param int parentId * @param array | null cacheData existing data in the cache for the file to be scanned * @param bool lock set to false to disable getting an additional read lock during scanning * @return array an array of metadata of the scanned file * @throws \OC\ServerNotAvailableException * @throws \OCP\Lock\LockedException * @since 9.0.0 */ IList<string> scanFile(string file, int reuseExisting = 0, int parentId = -1, IList<string> cacheData = null, bool lockp = true); /** * scan a folder and all its children * * @param string path * @param bool recursive * @param int reuse * @param bool lock set to false to disable getting an additional read lock during scanning * @return array an array of the meta data of the scanned file or folder * @since 9.0.0 */ IList<string> scan(string path, bool recursive , int reuse = -1, bool lockp = true); /** * check if the file should be ignored when scanning * NOTE: files with a '.part' extension are ignored as well! * prevents unfinished put requests to be scanned * * @param string file * @return boolean * @since 9.0.0 */ bool isPartialFile(string file); /** * walk over any folders that are not fully scanned yet and scan them * * @since 9.0.0 */ void backgroundScan(); } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_TextAnchor : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.TextAnchor"); LuaObject.addMember(l, 0, "UpperLeft"); LuaObject.addMember(l, 1, "UpperCenter"); LuaObject.addMember(l, 2, "UpperRight"); LuaObject.addMember(l, 3, "MiddleLeft"); LuaObject.addMember(l, 4, "MiddleCenter"); LuaObject.addMember(l, 5, "MiddleRight"); LuaObject.addMember(l, 6, "LowerLeft"); LuaObject.addMember(l, 7, "LowerCenter"); LuaObject.addMember(l, 8, "LowerRight"); LuaDLL.lua_pop(l, 1); } }