text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace online_knjizara.ViewModels { public class StanjeUrediVM { public int ID { get; set; } [Required(ErrorMessage = "Unesite tip stanja.")] public string TipStanja { get; set; } } }
using OpenGov.Models; using System.Collections.Generic; namespace OpenGovAlerts.Models { public class ViewSearchModel { public Search Search { get; set; } public IList<ViewSearchSource> Sources { get; set; } public IList<Match> RecentMatches { get; set; } } public class ViewSearchSource { public Source Source { get; set; } public bool Selected { get; set; } } }
namespace DependencyInjectionExample.Interfaces { public interface ICommandProcessor { void Process(string input); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BankAccountNS { public enum Status { FROZEN, ACTIVE } public class BankAccount { private string m_customerName; private double m_balance; private int m_id; private string m_password; private int m_wrongLogin; private bool m_frozen = false; public const string DebitAmountExceedsBalanceMessage = "Debit amount exceeds balance"; public const string DebitAmountLessThanZeroMessage = "Debit amount less than zero"; private BankAccount() { } public BankAccount(string customerName, double balance, int id, string password) { m_customerName = customerName; m_balance = balance; m_id = id; m_password = password; } public string CustomerName { get { return m_customerName; } } public double Balance { get { return m_balance; } } public int Id { get { return m_id; } } public string Password { get { return m_password; } } public int WrongLogin { get { return m_wrongLogin; } } public bool Frozen { get { return m_frozen; } } public void Debit(double amount) { if (m_frozen) { throw new Exception("Account frozen"); } if (amount > m_balance) { throw new ArgumentOutOfRangeException("amount", amount, DebitAmountExceedsBalanceMessage); } if (amount < 0) { throw new ArgumentOutOfRangeException("amount", amount, DebitAmountLessThanZeroMessage); } m_balance -= amount; // intentionally incorrect code } public void Credit(double amount) { if (m_frozen) { throw new Exception("Account frozen"); } if (amount < 0) { throw new ArgumentOutOfRangeException("amount"); } m_balance += amount; } public bool Login (int id, string password) { if( id != m_id) { throw new Exception("wrong ID"); }else if (password != m_password) { ++m_wrongLogin; if(m_wrongLogin > 5) { m_frozen = true; } }else if (m_frozen == false) { return true; } return false; } private void FreezeAccount() { m_frozen = true; } private void UnfreezeAccount() { m_frozen = false; } public Status status() { return m_frozen ? Status.FROZEN : Status.ACTIVE; } public static void Main() { BankAccount ba = new BankAccount("Mr. Bryan Walton", 11.99, 123, "abc123"); ba.Credit(5.77); ba.Debit(11.22); Console.WriteLine("Current balance is ${0}", ba.Balance); } } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.Files.Mount { /** * A storage mounted to folder on the filesystem * @since 8.0.0 */ public interface IMountPoint { /** * get complete path to the mount point * * @return string * @since 8.0.0 */ string getMountPoint(); /** * Set the mountpoint * * @param string mountPoint new mount point * @since 8.0.0 */ void setMountPoint(string mountPoint); /** * Get the storage that is mounted * * @return \OC\Files\Storage\Storage * @since 8.0.0 */ Storage.IStorage getStorage(); /** * Get the id of the storages * * @return string * @since 8.0.0 */ string getStorageId(); /** * Get the id of the storages * * @return int * @since 9.1.0 */ int getNumericStorageId(); /** * Get the path relative to the mountpoint * * @param string path absolute path to a file or folder * @return string * @since 8.0.0 */ string getInternalPath(string path); /** * Apply a storage wrapper to the mounted storage * * @param callable wrapper * @since 8.0.0 */ void wrapStorage(Action wrapper); /** * Get a mount option * * @param string name Name of the mount option to get * @param mixed default Default value for the mount option * @return mixed * @since 8.0.0 */ object getOption(string name, object @default); /** * Get all options for the mount * * @return array * @since 8.1.0 */ IDictionary<string,object> getOptions(); /** * Get the file id of the root of the storage * * @return int * @since 9.1.0 */ int getStorageRootId(); /** * Get the id of the configured mount * * @return int|null mount id or null if not applicable * @since 9.1.0 */ int? getMountId(); /** * Get the type of mount point, used to distinguish things like shares and external storages * in the web interface * * @return string * @since 12.0.0 */ string getMountType(); } }
// ScopeUtils.cs // Author: // Stephen Shaw <sshaw@decriptor.com> // Copyright (c) 2012 sshaw using System; namespace Compiler.Parser { public static class ScopeUtils { /// <summary> /// Pops the top scope and returns the rest /// </summary> /// <param name='scope'> /// New scope /// </param> public static string Pop (string scope) { if (string.IsNullOrEmpty (scope)) throw new ArgumentNullException ("scope"); if (!scope.StartsWith ("g.") || scope.Length < 3) throw new ArgumentException (String.Format ("[ScopeUtils][Pop]scope is invalid: {0}", scope)); return scope.Substring (0, scope.LastIndexOf (".")); } /// <summary> /// Returns the top most scope /// </summary> /// <param name='scope'> /// Top level scope /// </param> public static string Top (string scope) { if (string.IsNullOrEmpty (scope)) throw new ArgumentNullException ("scope"); if (!scope.StartsWith ("g.") || scope.Length < 3) throw new ArgumentException (String.Format ("[ScopeUtils][Pop]scope is invalid: {0}", scope)); return scope.Substring (scope.LastIndexOf (".") + 1); } } }
using System; using System.Collections.Generic; namespace ProtoTypePattern.Models { public class PrototypeKeeper { private static IDictionary<string, ICloneable> Dict = new Dictionary<string, ICloneable>(); public static void AddICloneable(string key, ICloneable prototype) { Dict.Add(key, prototype); } public static ICloneable GetClone(string key) { ICloneable prototype = Dict?[key] ?? null; return prototype.Clone() as ICloneable; } } }
using System; namespace JobsityChatroom.WebAPI.Models.Chatroom { public class ChatMessageViewModel { public string UserId { get; set; } public string Body { get; set; } public DateTime CreatedOn { get; set; } } }
using MetroFramework.Forms; using PDV.CONTROLER.Funcoes; using PDV.DAO.Entidades; using PDV.DAO.Enum; using PDV.UTIL; using System; using System.Data; using System.Windows.Forms; namespace PDV.VIEW.FRENTECAIXA.Forms { public partial class GPDV_IdentificarClienteDAV : MetroForm { public DataRow DRCliente = null; public bool Identificar = false; private bool ClienteNovo = false; public string IDCliente = ""; private string _TipoCliente = "1"; public GPDV_IdentificarClienteDAV() { InitializeComponent(); ovTXT_ClienteEncontrado.Text = ""; ovTXT_CPFCNPJ.LostFocus += OvTXT_CPFCNPJ_LostFocus; ovTXT_TipoPessoa.LostFocus += ovTXT_TipoPessoa_LostFocus; AplicarMascara(); } private void ovTXT_TipoPessoa_LostFocus(object sender, EventArgs e) { if (!_TipoCliente.Equals(ovTXT_TipoPessoa.Text)) { AplicarMascara(); ovTXT_ClienteEncontrado.Text = string.Empty; ovTXT_EmailCliente.Text = string.Empty; } } private void AplicarMascara() { switch (ovTXT_TipoPessoa.Text.Trim()) { case "0": ovTXT_TipoDocumento.Text = "* CNPJ:"; ovTXT_CPFCNPJ.Mask = "##,###,###/####-##"; ovTXT_CPFCNPJ.Text = string.Empty; ovTXT_ClienteEncontrado.Text = string.Empty; break; case "1": ovTXT_TipoDocumento.Text = "* CPF:"; ovTXT_CPFCNPJ.Mask = "###,###,###-##"; ovTXT_CPFCNPJ.Text = string.Empty; ovTXT_ClienteEncontrado.Text = string.Empty; break; } } private void OvTXT_CPFCNPJ_LostFocus(object sender, EventArgs e) { if (!(ovTXT_TipoPessoa.Text.Trim().Equals("0") || ovTXT_TipoPessoa.Text.Trim().Equals("1"))) ovTXT_TipoPessoa.Text = "1"; DRCliente = FuncoesCliente.GetClientePorTipoEDocumento(Convert.ToDecimal(ovTXT_TipoPessoa.Text.Trim()), ZeusUtil.SomenteNumeros(ovTXT_CPFCNPJ.Text).ToString()); if (DRCliente == null) { ovTXT_EmailCliente.Text = string.Empty; ovTXT_ClienteEncontrado.Text = "Novo Cliente"; ovTXT_ClienteEncontrado.ForeColor = System.Drawing.Color.Red; ovTXT_NomeCliente.Visible = true; ClienteNovo = true; ovTXT_NomeCliente.Focus(); } else { ovTXT_EmailCliente.Text = DRCliente["EMAIL"].ToString(); ovTXT_ClienteEncontrado.Text = DRCliente["NOME"].ToString(); ; ovTXT_ClienteEncontrado.ForeColor = System.Drawing.Color.Green; } } protected override bool ProcessDialogKey(Keys keyData) { switch (keyData) { case Keys.Escape: Identificar = false; Close(); break; case Keys.F12: //IDENTIFICAR O CLIENTE SalvarIdentificacao(); break; case Keys.F3: metroButton2_Click(metroButton2, null); break; } return base.ProcessDialogKey(keyData); } private void metroButton1_Click(object sender, EventArgs e) { SalvarIdentificacao(); } private void SalvarIdentificacao() { if (string.IsNullOrEmpty(ZeusUtil.SomenteNumeros(ovTXT_CPFCNPJ.Text))) { ovTXT_CPFCNPJ.Select(); return; } if (ClienteNovo) { try { Cliente cliente = new Cliente(); cliente.Ativo = 1; cliente.Nome = ovTXT_NomeCliente.Text; cliente.TipoDocumento = decimal.Parse(ovTXT_TipoPessoa.Text); cliente.IDEndereco = null; cliente.IDContato = null; if (ovTXT_TipoPessoa.Text == "1") cliente.CPF = ovTXT_CPFCNPJ.Text.Replace(".", "").Replace("-", ""); else { cliente.RazaoSocial = ovTXT_NomeCliente.Text; cliente.CNPJ = ovTXT_CPFCNPJ.Text.Replace(".", "").Replace("-", "").Replace("/", ""); } cliente.Email = ovTXT_EmailCliente.Text; TipoOperacao Op = TipoOperacao.INSERT; FuncoesCliente.Salvar(cliente, Op); } catch (Exception ex) { string ss = ex.InnerException.ToString(); // throw new Exception("Não foi possível salvar o cliente"); } } Identificar = true; Close(); } private void metroButton2_Click(object sender, EventArgs e) { //FCO_ClienteDAV cliente = new FCO_ClienteDAV(); //cliente.Consulta(this); //cliente.ShowDialog(); //ovTXT_CPFCNPJ.Text = IDCliente.ToString(); //OvTXT_CPFCNPJ_LostFocus(ovTXT_CPFCNPJ, null); } } }
// Copyright 2020 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. using NtApiDotNet.Utilities.Reflection; namespace NtApiDotNet.Win32.Security.Authentication.Kerberos { #pragma warning disable 1591 /// <summary> /// Kerberos Error Type. /// </summary> public enum KerberosErrorType { [SDKName("KDC_ERR_NONE")] NONE = 0, [SDKName("KDC_ERR_NAME_EXP")] NAME_EXP = 1, [SDKName("KDC_ERR_SERVICE_EXP")] SERVICE_EXP = 2, [SDKName("KDC_ERR_BAD_PVNO")] BAD_PVNO = 3, [SDKName("KDC_ERR_C_OLD_MAST_KVNO")] C_OLD_MAST_KVNO = 4, [SDKName("KDC_ERR_S_OLD_MAST_KVNO")] S_OLD_MAST_KVNO = 5, [SDKName("KDC_ERR_C_PRINCIPAL_UNKNOWN")] C_PRINCIPAL_UNKNOWN = 6, [SDKName("KDC_ERR_S_PRINCIPAL_UNKNOWN")] S_PRINCIPAL_UNKNOWN = 7, [SDKName("KDC_ERR_PRINCIPAL_NOT_UNIQUE")] PRINCIPAL_NOT_UNIQUE = 8, [SDKName("KDC_ERR_NULL_KEY")] NULL_KEY = 9, [SDKName("KDC_ERR_CANNOT_POSTDATE")] CANNOT_POSTDATE = 10, [SDKName("KDC_ERR_NEVER_VALID")] NEVER_VALID = 11, [SDKName("KDC_ERR_POLICY")] POLICY = 12, [SDKName("KDC_ERR_BADOPTION")] BADOPTION = 13, [SDKName("KDC_ERR_ENCTYPE_NOSUPP")] ENCTYPE_NOSUPP = 14, [SDKName("KDC_ERR_SUMTYPE_NOSUPP")] SUMTYPE_NOSUPP = 15, [SDKName("KDC_ERR_PADATA_TYPE_NOSUPP")] PADATA_TYPE_NOSUPP = 16, [SDKName("KDC_ERR_TRTYPE_NOSUPP")] TRTYPE_NOSUPP = 17, [SDKName("KDC_ERR_CLIENT_REVOKED")] CLIENT_REVOKED = 18, [SDKName("KDC_ERR_SERVICE_REVOKED")] SERVICE_REVOKED = 19, [SDKName("KDC_ERR_TGT_REVOKED")] TGT_REVOKED = 20, [SDKName("KDC_ERR_CLIENT_NOTYET")] CLIENT_NOTYET = 21, [SDKName("KDC_ERR_SERVICE_NOTYET")] SERVICE_NOTYET = 22, [SDKName("KDC_ERR_KEY_EXP")] KEY_EXP = 23, [SDKName("KDC_ERR_PREAUTH_FAILED")] PREAUTH_FAILED = 24, [SDKName("KDC_ERR_PREAUTH_REQUIRED")] PREAUTH_REQUIRED = 25, [SDKName("KDC_ERR_SERVER_NOMATCH")] SERVER_NOMATCH = 26, [SDKName("KDC_ERR_MUST_USE_USER2USER")] MUST_USE_USER2USER = 27, [SDKName("KDC_ERR_PATH_NOT_ACCEPTED")] PATH_NOT_ACCEPTED = 28, [SDKName("KDC_ERR_SVC_UNAVAILABLE")] SVC_UNAVAILABLE = 29, [SDKName("KRB_AP_ERR_BAD_INTEGRITY")] BAD_INTEGRITY = 31, [SDKName("KRB_AP_ERR_TKT_EXPIRED")] TKT_EXPIRED = 32, [SDKName("KRB_AP_ERR_TKT_NYV")] TKT_NYV = 33, [SDKName("KRB_AP_ERR_REPEAT")] REPEAT = 34, [SDKName("KRB_AP_ERR_NOT_US")] NOT_US = 35, [SDKName("KRB_AP_ERR_BADMATCH")] BADMATCH = 36, [SDKName("KRB_AP_ERR_SKEW")] SKEW = 37, [SDKName("KRB_AP_ERR_BADADDR")] BADADDR = 38, [SDKName("KRB_AP_ERR_BADVERSION")] BADVERSION = 39, [SDKName("KRB_AP_ERR_MSG_TYPE")] MSG_TYPE = 40, [SDKName("KRB_AP_ERR_MODIFIED")] MODIFIED = 41, [SDKName("KRB_AP_ERR_BADORDER")] BADORDER = 42, [SDKName("KRB_AP_ERR_BADKEYVER")] BADKEYVER = 44, [SDKName("KRB_AP_ERR_NOKEY")] NOKEY = 45, [SDKName("KRB_AP_ERR_MUT_FAIL")] MUT_FAIL = 46, [SDKName("KRB_AP_ERR_BADDIRECTION")] BADDIRECTION = 47, [SDKName("KRB_AP_ERR_METHOD")] METHOD = 48, [SDKName("KRB_AP_ERR_BADSEQ")] BADSEQ = 49, [SDKName("KRB_AP_ERR_INAPP_CKSUM")] INAPP_CKSUM = 50, [SDKName("KRB_AP_PATH_NOT_ACCEPTED")] AP_PATH_NOT_ACCEPTED = 51, [SDKName("KRB_ERR_RESPONSE_TOO_BIG")] RESPONSE_TOO_BIG = 52, [SDKName("KRB_ERR_GENERIC")] GENERIC = 60, [SDKName("KRB_ERR_FIELD_TOOLONG")] FIELD_TOOLONG = 61, [SDKName("KDC_ERR_CLIENT_NOT_TRUSTED")] CLIENT_NOT_TRUSTED = 62, [SDKName("KDC_ERR_KDC_NOT_TRUSTED")] KDC_NOT_TRUSTED = 63, [SDKName("KDC_ERR_INVALID_SIG")] INVALID_SIG = 64, [SDKName("KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED")] DH_KEY_PARAMETERS_NOT_ACCEPTED = 65, [SDKName("KDC_ERR_CERTIFICATE_MISMATCH")] CERTIFICATE_MISMATCH = 66, [SDKName("KRB_AP_ERR_NO_TGT")] NO_TGT = 67, [SDKName("KDC_ERR_WRONG_REALM")] WRONG_REALM = 68, [SDKName("KRB_AP_ERR_USER_TO_USER_REQUIRED")] USER_TO_USER_REQUIRED = 69, [SDKName("KDC_ERR_CANT_VERIFY_CERTIFICATE")] CANT_VERIFY_CERTIFICATE = 70, [SDKName("KDC_ERR_INVALID_CERTIFICATE")] INVALID_CERTIFICATE = 71, [SDKName("KDC_ERR_REVOKED_CERTIFICATE")] REVOKED_CERTIFICATE = 72, [SDKName("KDC_ERR_REVOCATION_STATUS_UNKNOWN")] REVOCATION_STATUS_UNKNOWN = 73, [SDKName("KDC_ERR_REVOCATION_STATUS_UNAVAILABLE")] REVOCATION_STATUS_UNAVAILABLE = 74, [SDKName("KDC_ERR_CLIENT_NAME_MISMATCH")] CLIENT_NAME_MISMATCH = 75, [SDKName("KDC_ERR_INCONSISTENT_KEY_PURPOSE")] INCONSISTENT_KEY_PURPOSE = 77, [SDKName("KDC_ERR_DIGEST_IN_CERT_NOT_ACCEPTED")] DIGEST_IN_CERT_NOT_ACCEPTED = 78, [SDKName("KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED")] PA_CHECKSUM_MUST_BE_INCLUDED = 79, [SDKName("KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED")] DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED = 80, [SDKName("KDC_ERR_PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED")] PUBLIC_KEY_ENCRYPTION_NOT_SUPPORTED = 81, [SDKName("KRB_AP_ERR_IAKERB_KDC_NOT_FOUND")] IAKERB_KDC_NOT_FOUND = 85, [SDKName("KRB_AP_ERR_IAKERB_KDC_NO_RESPONSE")] IAKERB_KDC_NO_RESPONSE = 86, [SDKName("KDC_ERR_PREAUTH_EXPIRED")] PREAUTH_EXPIRED = 90, [SDKName("KDC_ERR_MORE_PREAUTH_DATA_REQUIRED")] MORE_PREAUTH_DATA_REQUIRED = 91, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TextLayoutChanger { class PropertyDescription { public string Name { get; set; } public string NameDB { get; set; } public string Type { get; set; } public PropertyDescription(string name, string nameDB, string type) { Name = name; NameDB = nameDB.Replace("\r\n", ""); Type = type.Replace("\r\n", ""); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using System; using System.IO; namespace Sms.Demo.Contacts { public static class ApplicationBuilderExtensions { #region Public methods /// <summary> /// Использовать статические файлы приложения /// </summary> /// <param name="builder">Строитель приложения</param> /// <param name="environmentProvider">Cреда приложения</param> /// <returns></returns> public static IApplicationBuilder UseAppStaticFiles( this IApplicationBuilder builder, IHostEnvironment env) { return builder .UseDefaultFiles(new DefaultFilesOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, Path.Join("App", "src"))), RequestPath = String.Empty }) .UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, Path.Join("App", "src"))), RequestPath = String.Empty }) .UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, Path.Join("App", "libs"))), RequestPath = "/libs" }) .UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, Path.Join("App", "assets"))), RequestPath = "/assets" }); } #endregion } }
// // 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; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Security; using DotNetNuke.Services.Social.Subscriptions.Entities; namespace DotNetNuke.Services.Social.Subscriptions { /// <summary> /// This controller provides permission info about the User Subscription. /// </summary> public class SubscriptionSecurityController : ServiceLocator<ISubscriptionSecurityController, SubscriptionSecurityController>, ISubscriptionSecurityController { protected override Func<ISubscriptionSecurityController> GetFactory() { return () => new SubscriptionSecurityController(); } public bool HasPermission(Subscription subscription) { var userInfo = GetUserFromSubscription(subscription); var moduleInfo = GetModuleFromSubscription(subscription); if (moduleInfo != null && !moduleInfo.InheritViewPermissions) { return HasUserModuleViewPermission(userInfo, moduleInfo); } var tabInfo = GetTabFromSubscription(subscription); if (tabInfo != null) { return HasUserTabViewPermission(userInfo, tabInfo); } return true; } #region Private Static Methods private static bool HasUserModuleViewPermission(UserInfo userInfo, ModuleInfo moduleInfo) { var portalSettings = new PortalSettings(moduleInfo.PortalID); return PortalSecurity.IsInRoles(userInfo, portalSettings, moduleInfo.ModulePermissions.ToString("VIEW")); } private static bool HasUserTabViewPermission(UserInfo userInfo, TabInfo tabInfo) { var portalSettings = new PortalSettings(tabInfo.PortalID); return PortalSecurity.IsInRoles(userInfo, portalSettings, tabInfo.TabPermissions.ToString("VIEW")); } private static TabInfo GetTabFromSubscription(Subscription subscription) { return TabController.Instance.GetTab(subscription.TabId, subscription.PortalId, false); } private static ModuleInfo GetModuleFromSubscription(Subscription subscription) { return ModuleController.Instance.GetModule(subscription.ModuleId, Null.NullInteger, true); } private static UserInfo GetUserFromSubscription(Subscription subscription) { return UserController.Instance.GetUser(subscription.PortalId, subscription.UserId); } #endregion } }
using System; using System.Security.Principal; namespace CallCenter.ServiceContracts.DataContracts { public interface IOperatorChatMessage:IIdentity { DateTime Date { get; set; } string Message { get; set; } ChatMessageType MessageType { get; set; } } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades; using PDV.DAO.Entidades.MDFe; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.CONTROLER.Funcoes { public class FuncoesPercurso { public static bool Salvar(PercursoMDFe Percurso) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"INSERT INTO PERCURSOMDFE(IDPERCURSOMDFE, IDMDFE, IDUNIDADEFEDERATIVAPERCURSO, INICIOVIAGEM) VALUES(@IDPERCURSOMDFE, @IDMDFE, @IDUNIDADEFEDERATIVAPERCURSO, @INICIOVIAGEM)"; oSQL.ParamByName["IDPERCURSOMDFE"] = Percurso.IDPercursoMDFe; oSQL.ParamByName["IDMDFE"] = Percurso.IDMDFe; oSQL.ParamByName["IDUNIDADEFEDERATIVAPERCURSO"] = Percurso.IDUnidadeFederativaPercurso; oSQL.ParamByName["INICIOVIAGEM"] = Percurso.InicioViagem; return oSQL.ExecSQL() == 1; } } public static bool Remover(decimal IDPercursoMDFe) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM PERCURSOMDFE WHERE IDPERCURSOMDFE = @IDPERCURSOMDFE"; oSQL.ParamByName["IDPERCURSOMDFE"] = IDPercursoMDFe; oSQL.Open(); if (oSQL.IsEmpty) return true; oSQL.ClearAll(); oSQL.SQL = "DELETE FROM PERCURSOMDFE WHERE IDPERCURSOMDFE = @IDPERCURSOMDFE"; oSQL.ParamByName["IDPERCURSOMDFE"] = IDPercursoMDFe; return oSQL.ExecSQL() == 1; } } public static DataTable GetPercursosPorMDFe(decimal IDMDFe) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.SIGLA, PERCURSOMDFE.INICIOVIAGEM, PERCURSOMDFE.IDPERCURSOMDFE, PERCURSOMDFE.IDMDFE, UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA AS IDUNIDADEFEDERATIVAPERCURSO FROM PERCURSOMDFE INNER JOIN UNIDADEFEDERATIVA ON (PERCURSOMDFE.IDUNIDADEFEDERATIVAPERCURSO = UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA) WHERE PERCURSOMDFE.IDMDFE = @IDMDFE ORDER BY PERCURSOMDFE.IDMDFE ASC"; oSQL.ParamByName["IDMDFE"] = IDMDFe; oSQL.Open(); return oSQL.dtDados; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Miscellaneous_technologies { public static class MultiViewControlStatus { public static int ViewStateStatus; } }
namespace BPiaoBao.DomesticTicket.EFRepository.Migrations { using System; using System.Data.Entity.Migrations; public partial class _201411121614 : DbMigration { public override void Up() { AddColumn("dbo.Policy", "IsCoordination", c => c.Boolean(nullable: false)); AddColumn("dbo.Policy", "MaxPoint", c => c.Decimal(precision: 18, scale: 2)); AddColumn("dbo.DeductionDetail", "DeductionSource", c => c.Int(nullable: false)); } public override void Down() { DropColumn("dbo.DeductionDetail", "DeductionSource"); DropColumn("dbo.Policy", "MaxPoint"); DropColumn("dbo.Policy", "IsCoordination"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CGI.Reflex.Core.Entities; using FluentNHibernate.Testing; using NUnit.Framework; namespace CGI.Reflex.Core.Tests.Entities { public class AppDatabaseLinkTest : BaseDbTest { [Test] public void It_should_persist() { new PersistenceSpecification<AppDatabaseLink>(NHSession, new PersistenceEqualityComparer()) .CheckReference(x => x.Application, Factories.Application.Save()) .CheckReference(x => x.Database, Factories.Database.Save()) .VerifyTheMappings(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using Autofac; using Caliburn.Micro; using Voronov.Nsudotnet.BuildingCompanyIS.Entities; using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces; using IContainer = Autofac.IContainer; namespace Voronov.Nsudotnet.BuildingCompanyIS.UI.ViewModels { public class BrigadeSimpleViewModel : PropertyChangedBase { public BrigadeSimpleViewModel(Brigade entity) { BrigadeEntity = entity; } public Brigade BrigadeEntity { get; private set; } public String Name { get { return BrigadeEntity.Name; } set { if (value == BrigadeEntity.Name) return; if (value.Length == 0) return; BrigadeEntity.Name = value; NotifyOfPropertyChange(()=>Name); } } } public class BrigadeViewModel : BrigadeSimpleViewModel { public BrigadeViewModel(Brigade entity) : base(entity) { _currentOrganizationUnit = new OrganizationUnitSimpleViewModel(entity.OrganizationUnit); _currentBrigadeer = (entity.Brigadeer == null) ? new WorkerViewModel() : new WorkerViewModel(entity.Brigadeer.Worker); } private WorkerViewModel _currentBrigadeer; public WorkerViewModel CurrentManager { get { return _currentBrigadeer; } } private OrganizationUnitSimpleViewModel _currentOrganizationUnit; public OrganizationUnitSimpleViewModel CurrentOrganizationUnit { get { return _currentOrganizationUnit; } } } public class BrigadeControlViewModel// : //SubUnitElementControlViewModel { /*public BrigadeControlViewModel(IContainer container) { _container = container; _brigadesService = _container.Resolve<ICrudService<Brigade>>(); _organizationUnits = new BindableCollection<OrganizationUnitSimpleViewModel>(); foreach (var organizationUnit in _container.Resolve<IOrganizationUnitsService>().All) { _organizationUnits.Add(new OrganizationUnitSimpleViewModel(organizationUnit)); } MyRefresh(); } private ICrudService<Brigade> _brigadesService; private IContainer _container; public override void Add() { try { if (_selectedOrganizationUnit == null) return; if (_newElementName == String.Empty) return; if (Elements.FirstOrDefault(e => e.Name == _newElementName) != null) return; var newBrigade = new Brigade() { Name = _newElementName, OrganizationUnitId = _selectedOrganizationUnit.OrganizationUnitEntity.Id }; _brigadesService.CreateAndSave(newBrigade); _newElementName = String.Empty; NotifyOfPropertyChange(() => NewElementName); Elements.Add(new BrigadeViewModel(newBrigade)); NotifyOfPropertyChange(() => Elements); } catch (DbException e) { Console.Out.WriteLine(e); Error = Messages.ErrorMessageOnAddingEntity; } } public override void MyRefresh() { Elements.Clear();; foreach (var site in _brigadesService.AllIncludeAll) { Elements.Add(new BrigadeViewModel(site)); } NotifyOfPropertyChange(() => Elements); _newElementName = String.Empty; NotifyOfPropertyChange(() => NewElementName); _selectedForFilterOrganizationUnit = null; _subUnitElementsCollectionViewSource.Refresh(); } public override void Delete() { try { if (_selectedElement == null) return; var brig = (BrigadeViewModel) _selectedElement; _brigadesService.DeleteAndSave(brig.BrigadeEntity); Elements.Remove(_selectedElement); NotifyOfPropertyChange(() => Elements); } catch (Exception e) { Console.Out.WriteLine(e); Error = Messages.ErrorMessageOnDeleteEntity; } } public override void OpenManagerControls() { IBrigadeerService brigadeerService = _container.Resolve<IBrigadeerService>(); IWorkersService workerService = _container.Resolve<IWorkersService>(); ICrudService<Brigade> crudService = _container.Resolve<ICrudService<Brigade>>(); IOrganizationUnitsService organizationUnitsService = _container.Resolve<IOrganizationUnitsService>(); _container.Resolve<IWindowManager>().ShowWindow(new SubUnitElementManagerDetailedStartViewModel(new BrigadeersDetailedViewModel(brigadeerService,workerService,crudService,organizationUnitsService))); } } /* public class SiteControlViewModel : PropertyChangedBaseWithError { public SiteControlViewModel(IContainer container) { _organizationUnits = new BindableCollection<OrganizationUnitSimpleViewModel>(); foreach (var organizationUnit in _container.Resolve<IOrganizationUnitsService>().All) { _organizationUnits.Add(new OrganizationUnitSimpleViewModel(organizationUnit)); } MyRefresh(); _sitesCollectionViewSource = CollectionViewSource.GetDefaultView(Sites); _sitesCollectionViewSource.Filter = Filter; } private BindableCollection<OrganizationUnitSimpleViewModel> _organizationUnits; public BindableCollection<OrganizationUnitSimpleViewModel> ForFilterOrganizationUnits { get { return _organizationUnits; } } private OrganizationUnitSimpleViewModel _selectedForFilterOrganizationUnit; public OrganizationUnitSimpleViewModel SelectedForFilterOrganizationUnit { get { return _selectedForFilterOrganizationUnit; } set { if (value == _selectedForFilterOrganizationUnit) return; _selectedForFilterOrganizationUnit = value; NotifyOfPropertyChange(()=>SelectedForFilterOrganizationUnit); _sitesCollectionViewSource.Refresh(); } } public BindableCollection<OrganizationUnitSimpleViewModel> OrganizationUnits { get { return _organizationUnits; } } private OrganizationUnitSimpleViewModel _selectedOrganizationUnit; public OrganizationUnitSimpleViewModel SelectedOrganizationUnit { get { return _selectedOrganizationUnit; } set { if (value == _selectedOrganizationUnit) return; _selectedOrganizationUnit = value; NotifyOfPropertyChange(()=>SelectedOrganizationUnit); } } public BindableCollection<SiteViewModel> Sites { get; private set; } private SiteViewModel _selectedSite; public SiteViewModel SelectedSite { get { return _selectedSite;} set { if (value == _selectedSite) return; _selectedSite = value; NotifyOfPropertyChange(()=>SelectedSite); } } private String _newSiteName; public String NewSiteName { get { return _newSiteName; } set { if (value == _newSiteName) return; _newSiteName = value; NotifyOfPropertyChange(()=>NewSiteName); } } public void Add() { try { if (_selectedOrganizationUnit == null) return; if (_newSiteName == String.Empty) return; if (Sites.FirstOrDefault(e => e.Name == _newSiteName) != null) return; var newSite = new Site { Name = _newSiteName, OrganizationUnitId = _selectedOrganizationUnit.OrganizationUnitEntity.Id }; _sitesService.CreateAndSave(newSite); _newSiteName = String.Empty; NotifyOfPropertyChange(() => NewSiteName); Sites.Add(new SiteViewModel(newSite)); NotifyOfPropertyChange(() => Sites); } catch (DbException e) { Console.Out.WriteLine(e); Error = Messages.ErrorMessageOnAddingEntity; } } public void Delete() { try { if (_selectedSite == null) return; _sitesService.DeleteAndSave(_selectedSite.SiteEntity); Sites.Remove(_selectedSite); NotifyOfPropertyChange(() => Sites); } catch (Exception e) { Console.Out.WriteLine(e); Error = Messages.ErrorMessageOnDeleteEntity; } } public void MyRefresh() { Sites = new BindableCollection<SiteViewModel>(); foreach (var site in _sitesService.AllIncludeAll) { Sites.Add(new SiteViewModel(site)); } NotifyOfPropertyChange(()=>Sites); _newSiteName = String.Empty; NotifyOfPropertyChange(()=>NewSiteName); _selectedForFilterOrganizationUnit = null; _sitesCollectionViewSource = CollectionViewSource.GetDefaultView(Sites); _sitesCollectionViewSource.Filter = Filter; } public void OpenManagerContorls() { _container.Resolve<IWindowManager>().ShowWindow(new SiteManagerDetailedViewModel(_container.Resolve<ISiteManagerService>(), _container.Resolve<IEngineerService>(), _sitesService, _container.Resolve<IOrganizationUnitsService>())); } public bool Filter(object obj) { var t = obj as SiteViewModel; if (t == null) return false; if (_selectedForFilterOrganizationUnit == null) return true; return t.CurrentOrganizationUnit.OrganizationUnitEntity.Id == _selectedForFilterOrganizationUnit.OrganizationUnitEntity.Id; } } */ } }
using UnityEngine; using System.Collections; public class UnitAbilities : MonoBehaviour { public GameObject m_target; [ContextMenu("Idle")] public void Idle() { m_target = null; } [ContextMenu("Move")] public void MoveToTarget() { if (GetComponent<UnitStats>().m_actionPoints > 0) { StartCoroutine(Move(m_target, Time.deltaTime * 2)); GetComponent<UnitStats>().m_actionPoints -= 1; } } [ContextMenu("Attack")] public void Attack() { if (GetComponent<UnitStats>().m_actionPoints > 0) { float att = m_target.GetComponent<UnitStats>().m_isDefending ? GetComponent<UnitStats>().m_attack / 2 : GetComponent<UnitStats>().m_attack; if (m_target.GetComponent<UnitStats>()) { if (m_target.GetComponent<UnitStats>().Armour > 0) { m_target.GetComponent<UnitStats>().Armour -= (att * 0.75f); } else { m_target.GetComponent<UnitStats>().Health -= (att); } } else { //Attack air } GetComponent<UnitStats>().m_actionPoints -= 1; } } [ContextMenu("Defend")] public void Defend() { if (GetComponent<UnitStats>().m_actionPoints > 0) { GetComponent<UnitStats>().m_isDefending = true; GetComponent<UnitStats>().m_actionPoints -= 1; } } [ContextMenu("End")] public void End() { GetComponent<UnitStats>().m_actionPoints = 2; } IEnumerator Move(GameObject target, float speed) { while (Vector3.Distance(transform.position, m_target.transform.position) > 0.1f) { transform.forward = target.transform.position - transform.position; transform.position += transform.forward * speed; yield return null; } } }
 /// <summary> /// Setting. /// Used to write key-value pairs to the local database /// </summary> using SQLite; namespace MCCForms { public class Setting { [PrimaryKey] public string Key { get; set; } public string Value { get; set; } } }
using Assets.Scripts.Generic.Dice; using Assets.Scripts.Overlay.Action_PopUps.TokenSelector; using Assets.Scripts.Player; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ActionProcesser : MonoBehaviour { public GameObject prefab; List<ActionContainer> currentActions; int currentIndex; public void ProcessAllActions() { FindObjectOfType<ContinueButton>().SetClickableTo(false); currentActions = GetAllActions(); currentIndex = 0; ProcessOneAction(); } private void ProcessOneAction() { if (currentIndex >= currentActions.Count) { ChangePhase(); return; } var action = currentActions[currentIndex]; PartyActions.ExecutingCharacter = action.GetExecutingCharacter(); if (action.ActionType == ActionType.preventDanger) { var processor = GetComponent<PreventDangerAction_Processing>(); processor.ProcessPreventAction(action); ProcessNextAction(); } else if (action.ActionType == ActionType.build) { var processor = GetComponent<BuildingHelper_Processing>(); processor.ProcessBuildAction(action); } else if (action.ActionType == ActionType.upgradeTent) { var processor = GetComponent<TentAction_Processing>(); processor.ProcessBuildAction_Tent(action); } else if (action.ActionType == ActionType.upgradeRoof) { var processor = GetComponent<RoofAction_Processing>(); processor.ProcessBuildAction_Roof(action); } else if (action.ActionType == ActionType.upgradeWall) { var processor = GetComponent<WallAction_Processing>(); processor.ProcessBuildAction_Wall(action); } else if (action.ActionType == ActionType.upgradeWeapons) { var processor = GetComponent<WeaponAction_Processing>(); processor.ProcessBuildAction_Weapon(action); } else if (action.ActionType == ActionType.collect) { var processor = GetComponent<GatheringActions_Processing>(); processor.ProcessCollectAction(action); } else if (action.ActionType == ActionType.explore) { var processor = GetComponent<ExploreActions_Processing>(); processor.ProcessExploreAction(action); } else if (action.ActionType == ActionType.clean) { var processor = GetComponent<CleanAction_Processing>(); processor.ProcessCleanAction(action); ProcessNextAction(); } else if (action.ActionType == ActionType.rest) { var processor = GetComponent<RestAction_Processing>(); processor.ProcessRestAction(action); ProcessNextAction(); } } public void ProcessNextAction() { currentIndex++; ProcessOneAction(); } private void ChangePhase() { //Change to next phase ResetCharacterActionTokens(); var phaseView = FindObjectOfType<PhaseView>(); phaseView.NextPhase(); } private void ResetCharacterActionTokens() { PartyActions.TokenReset(); } private List<ActionContainer> GetAllActions() { List<ActionContainer> importantActions = new List<ActionContainer>(); //Explore var explore = FindObjectsOfType<Action_Explore>(); foreach(var action in explore) { if(action.container.HasStoredAction) importantActions.Add(action.container); } //Gather var gather = FindObjectsOfType<Action_Gather>(); foreach (var action in gather) { foreach (var ressourceAction in action.container) { if (ressourceAction.Value.HasStoredAction) importantActions.Add(ressourceAction.Value); } } //Build var build = FindObjectsOfType<Action_Build>(); foreach (var action in build) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Clean var clean = FindObjectsOfType<Action_Clean>(); foreach (var action in clean) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Rest var rest = FindObjectsOfType<Action_Rest>(); foreach (var action in rest) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Prevent var prevent = FindObjectsOfType<Action_PreventDanger>(); foreach (var action in prevent) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Tent var tent = FindObjectsOfType<Action_BuildTent>(); foreach (var action in tent) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Roof var roof = FindObjectsOfType<Action_BuildRoof>(); foreach (var action in roof) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Wall var wall = FindObjectsOfType<Action_BuildWall>(); foreach (var action in wall) { if (action.container.HasStoredAction) importantActions.Add(action.container); } //Weapon var weapon = FindObjectsOfType<Action_BuildWeapon>(); foreach (var action in weapon) { if (action.container.HasStoredAction) importantActions.Add(action.container); } return importantActions; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.Entity; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using Navigation.DAL; using Navigation.Helper; using Navigation.Models; namespace Navigation.Controllers { public class PlaceController : Controller { private readonly NaviContext db = new NaviContext(); // GET: Place [HttpGet] [Auth] public ActionResult AddListing() { PlaceViewModel model = new PlaceViewModel(); model.category = db.Categories.ToList(); model.city = db.Cities.ToList(); model.Listing = db.Listings.FirstOrDefault(); return View(model); } //kategoriya servislerini getirir [HttpGet] public JsonResult CategoryService(int id) { if (id<=0) { return Json(new {status = 404, message = "Kateqoriya seçməmisiniz!"}, JsonRequestBehavior.AllowGet); } var model = db.CategoryServices.Where(x => x.CategoryId == id).Select(x=> new { ServiceId = x.ServiceId, Name=x.Service.Name }).ToList(); return Json(model, JsonRequestBehavior.AllowGet); } //place elave olunmasi [HttpPost] [ValidateAntiForgeryToken] [ValidateInput(false)] public JsonResult AddListing(Listing place, HttpPostedFileBase[] Photo) { if (Photo==null) { return Json(new { status = 404, message = "Şəkil əlavə etməmisiniz" }, JsonRequestBehavior.AllowGet); } if (string.IsNullOrEmpty(place.Title) || string.IsNullOrEmpty(place.Address) || string.IsNullOrEmpty(place.Description) || string.IsNullOrEmpty(place.Phone) || string.IsNullOrEmpty(place.Slogan) || string.IsNullOrEmpty(place.Website) || string.IsNullOrEmpty(place.Lat) || string.IsNullOrEmpty(place.Lng)) { return Json(new { status = 404, message = " * ilə qeyd olunmuş xanaları boş buraxmayın" }, JsonRequestBehavior.AllowGet); } place.UserId = (int)Session["user"]; place.Status = false; db.Listings.Add(place); db.SaveChanges(); foreach (HttpPostedFileBase files in Photo) { if (files != null && files.ContentLength > 0) { if (files.ContentLength > 2097152) { return Json(new{status=404, message="2Mb-dan artıq fayl yükləməyin"},JsonRequestBehavior.AllowGet); } if (files.ContentType != "image/jpeg" && files.ContentType!="image/png" && files.ContentType!="image/jpg" && files.ContentType!="image/gif") { return Json(new { status = 404, message="Ancaq .jpg .jpeg .png .gif formatda fayl yükləyin" }, JsonRequestBehavior.AllowGet); } string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + files.FileName; string path = Path.Combine(Server.MapPath("~/Public/images/PlacePhoto"), filename); files.SaveAs(path); Photo photo = new Photo() { PlacePhoto = filename, ListingId = place.Id }; db.Photos.Add(photo); db.SaveChanges(); return Json(new { status = 200, placeId =place.Id }, JsonRequestBehavior.AllowGet); } } return Json(new { status = 404, message = "Xəta baş verdi. Zəhmət olmasa birdə cəhd edin" }, JsonRequestBehavior.AllowGet); } //place servisleri ve hefte gunlerinin elave olunmasi [HttpPost] [Auth] public JsonResult create(int[] servis, List<vwHourWeek> WeekArr, int placeId) { if (WeekArr != null && servis.Count()>0) { foreach (var item in WeekArr) { WorkHour temp = new WorkHour(); temp.OpenHour = TimeSpan.Parse(item.OpenHour); temp.CloseHour = TimeSpan.Parse(item.CloseHour); temp.WeekNo = item.WeekNo; temp.ListingId = placeId; db.WorkHours.Add(temp); db.SaveChanges(); } foreach (var item in servis) { ListService ls = new ListService(); ls.ListingId = placeId; ls.ServiceId = item; db.ListServices.Add(ls); db.SaveChanges(); } } return Json(new { status = 200, url = "/home/index", message = "Yer əlavə olundu. Moderator təsdiq etdikdən sonra yayımlanacaq." }, JsonRequestBehavior.AllowGet); } } }
using System.Windows.Forms; namespace CleanUpCSVFiles { public class FilesHelper { public static string SelectFolder() { string res = string.Empty; using (var fbd = new FolderBrowserDialog()) { DialogResult result = fbd.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { res = fbd.SelectedPath; } } return res; } public static string SelectFile() { OpenFileDialog openFileDialog = new OpenFileDialog(); string selectedFileName = string.Empty; if (openFileDialog.ShowDialog() == DialogResult.OK) { selectedFileName = openFileDialog.FileName; } else { selectedFileName = string.Empty; } return selectedFileName; } } }
using RO; using System; using UnityEngine; [CustomLuaClass] public class FunctionSDK : Singleton<FunctionSDK> { [CustomLuaClass] public enum E_SDKType { None, XD, Any } public delegate void SDKCallback(string message); private FunctionSDK.E_SDKType m_currentType = FunctionSDK.E_SDKType.Any; private bool m_isInitialized; public FunctionSDK.E_SDKType CurrentType { get { return this.m_currentType; } } public bool IsInitialized { get { return this.m_isInitialized; } } public static FunctionSDK Instance { get { return Singleton<FunctionSDK>.ins; } } public void XDSDKInitialize(string app_id, string app_key, string secret_key, int orientation, FunctionSDK.SDKCallback on_initialize_success, FunctionSDK.SDKCallback on_initialize_fail) { LoggerUnused.Log("FunctionSDK:Initialize"); if (this.m_currentType == FunctionSDK.E_SDKType.XD) { MonoSingleton<FunctionXDSDK>.ins.Initialize(app_id, app_key, secret_key, orientation, delegate(string x) { this.m_isInitialized = true; if (on_initialize_success != null) { on_initialize_success(x); } }, delegate(string x) { this.m_isInitialized = false; if (on_initialize_fail != null) { on_initialize_fail(x); } }); } } public void AnySDKInitialize(string app_key, string app_secret, string private_key, string oauth_login_server, FunctionSDK.SDKCallback on_initialize_success, FunctionSDK.SDKCallback on_initialize_fail) { if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.Launch(); Singleton<FunctionAnySDK>.ins.Initialize(app_key, app_secret, private_key, oauth_login_server, delegate(string x) { this.m_isInitialized = true; if (on_initialize_success != null) { on_initialize_success(x); } }, delegate(string x) { this.m_isInitialized = false; if (on_initialize_fail != null) { on_initialize_fail(x); } }); Singleton<FunctionAnySDK>.ins.UserListen(); } } public void Login(FunctionSDK.SDKCallback on_login_success, FunctionSDK.SDKCallback on_login_fail, FunctionSDK.SDKCallback on_login_cancel) { LoggerUnused.Log("FunctionSDK:Login"); if (this.m_currentType == FunctionSDK.E_SDKType.XD) { MonoSingleton<FunctionXDSDK>.ins.Login(delegate(string x) { if (on_login_success != null) { on_login_success(x); } }, delegate(string x) { if (on_login_fail != null) { on_login_fail(x); } }, delegate(string x) { if (on_login_cancel != null) { on_login_cancel(x); } }); } else if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.Login(delegate(string x) { if (on_login_success != null) { on_login_success(x); } }, delegate(string x) { if (on_login_fail != null) { on_login_fail(x); } }, delegate(string x) { if (on_login_cancel != null) { on_login_cancel(x); } }); } } public void AnySDKLogin(string server_id, FunctionSDK.SDKCallback on_login_success, FunctionSDK.SDKCallback on_login_fail, FunctionSDK.SDKCallback on_login_cancel) { if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.Login(server_id, delegate(string x) { if (on_login_success != null) { on_login_success(x); } }, delegate(string x) { if (on_login_fail != null) { on_login_fail(x); } }, delegate(string x) { if (on_login_cancel != null) { on_login_cancel(x); } }); } } public void AnySDKLogin(string server_id, string oauth_login_server, FunctionSDK.SDKCallback on_login_success, FunctionSDK.SDKCallback on_login_fail, FunctionSDK.SDKCallback on_login_cancel) { if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.Login(server_id, oauth_login_server, delegate(string x) { if (on_login_success != null) { on_login_success(x); } }, delegate(string x) { if (on_login_fail != null) { on_login_fail(x); } }, delegate(string x) { if (on_login_cancel != null) { on_login_cancel(x); } }); } } public bool IsInstalledWeiXin() { bool result = false; if (this.m_currentType == FunctionSDK.E_SDKType.XD) { result = MonoSingleton<FunctionXDSDK>.ins.IsInstalledWeiXin(); } return result; } public void LoginWithWeiXin(FunctionSDK.SDKCallback on_login_success, FunctionSDK.SDKCallback on_login_fail) { if (this.m_currentType == FunctionSDK.E_SDKType.XD) { if (this.IsInstalledWeiXin()) { MonoSingleton<FunctionXDSDK>.ins.LoginWithWeiXin(delegate(string x) { if (on_login_success != null) { on_login_success(x); } }, delegate(string x) { if (on_login_fail != null) { on_login_fail(x); } }); } else { if (on_login_fail != null) { on_login_fail("No Wechat"); } Application.OpenURL("http://www.itunes.com/WeChat"); } } } public void LoginWithWeiXinForThousandPlayersTest(FunctionSDK.SDKCallback on_login_success, FunctionSDK.SDKCallback on_login_fail) { if (this.m_currentType == FunctionSDK.E_SDKType.XD) { if (!this.IsInstalledWeiXin()) { if (on_login_fail != null) { on_login_fail("No Wechat"); } Application.OpenURL("http://www.itunes.com/WeChat"); return; } MonoSingleton<FunctionXDSDK>.ins.SetCustomLogin(); this.Login(on_login_success, delegate(string x) { MonoSingleton<FunctionXDSDK>.ins.LoginWithWeiXin(delegate(string y) { if (on_login_success != null) { on_login_success(y); } }, delegate(string y) { if (on_login_fail != null) { on_login_fail(y); } }); }, null); } } public string GetAccessToken() { string result = string.Empty; if (this.m_currentType == FunctionSDK.E_SDKType.XD) { result = MonoSingleton<FunctionXDSDK>.ins.GetAccessToken(); } else if (this.m_currentType == FunctionSDK.E_SDKType.Any) { result = Singleton<VerificationOfLogin>.ins.CachedAccessToken; } return result; } public void EnterPlatform() { if (this.m_currentType == FunctionSDK.E_SDKType.XD) { MonoSingleton<FunctionXDSDK>.ins.EnterPlatform(); } else if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.EnterPlatform(); } } public bool IsLogined() { bool result = false; if (this.m_currentType == FunctionSDK.E_SDKType.XD) { result = MonoSingleton<FunctionXDSDK>.ins.IsLogined(); } else if (this.m_currentType == FunctionSDK.E_SDKType.Any) { result = Singleton<FunctionAnySDK>.ins.IsLogined(); } return result; } public void ListenLogout(FunctionSDK.SDKCallback on_logout_success, FunctionSDK.SDKCallback on_logout_fail) { if (this.m_currentType == FunctionSDK.E_SDKType.XD) { MonoSingleton<FunctionXDSDK>.ins.ListenLogout(delegate(string x) { if (on_logout_success != null) { on_logout_success(x); } }, delegate(string x) { if (on_logout_fail != null) { on_logout_fail(x); } }); } else if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.ListenLogout(delegate(string x) { if (on_logout_success != null) { on_logout_success(x); } }, delegate(string x) { if (on_logout_fail != null) { on_logout_fail(x); } }); } } public string XDSDKPay(int price, string s_id, string product_id, string product_name, string role_id, string ext, int product_count, FunctionSDK.SDKCallback on_pay_success, FunctionSDK.SDKCallback on_pay_fail, FunctionSDK.SDKCallback on_pay_timeout, FunctionSDK.SDKCallback on_pay_cancel, FunctionSDK.SDKCallback on_pay_product_illegal) { string result = string.Empty; if (this.m_currentType == FunctionSDK.E_SDKType.XD) { FunctionXDSDK.XDSDKCallback on_pay_success2 = delegate(string x) { if (on_pay_success != null) { on_pay_success(x); } }; FunctionXDSDK.XDSDKCallback on_pay_fail2 = delegate(string x) { if (on_pay_fail != null) { on_pay_fail(x); } }; FunctionXDSDK.XDSDKCallback on_pay_cancel2 = delegate(string x) { if (on_pay_timeout != null) { on_pay_timeout(x); } }; FunctionXDSDK.XDSDKCallback on_pay_timeout2 = delegate(string x) { if (on_pay_cancel != null) { on_pay_cancel(x); } }; FunctionXDSDK.XDSDKCallback on_pay_product_illegal2 = delegate(string x) { if (on_pay_product_illegal != null) { on_pay_product_illegal(x); } }; result = MonoSingleton<FunctionXDSDK>.ins.Pay(price, s_id, product_id, product_name, role_id, ext, product_count, on_pay_success2, on_pay_fail2, on_pay_cancel2, on_pay_timeout2, on_pay_product_illegal2); } return result; } public void AnySDKPay(string p_id, string p_name, float p_price, int p_count, string role_id, string role_name, int role_grade, int role_balance, string server_id, string custom_string, FunctionSDK.SDKCallback on_success, FunctionSDK.SDKCallback on_fail, FunctionSDK.SDKCallback on_timeout, FunctionSDK.SDKCallback on_cancel, FunctionSDK.SDKCallback on_product_illegal, FunctionSDK.SDKCallback on_paying) { if (this.m_currentType == FunctionSDK.E_SDKType.Any) { AnySDKCallbacks.AnySDKCallback on_success2 = delegate(string x) { if (on_success != null) { on_success(x); } }; AnySDKCallbacks.AnySDKCallback on_fail2 = delegate(string x) { if (on_fail != null) { on_fail(x); } }; AnySDKCallbacks.AnySDKCallback on_timeout2 = delegate(string x) { if (on_timeout != null) { on_timeout(x); } }; AnySDKCallbacks.AnySDKCallback on_cancel2 = delegate(string x) { if (on_cancel != null) { on_cancel(x); } }; AnySDKCallbacks.AnySDKCallback on_product_illegal2 = delegate(string x) { if (on_product_illegal != null) { on_product_illegal(x); } }; AnySDKCallbacks.AnySDKCallback on_paying2 = delegate(string x) { if (on_paying != null) { on_paying(x); } }; Singleton<FunctionAnySDK>.ins.PayForProduct(p_id, p_name, p_price, p_count, role_id, role_name, role_grade, role_balance, server_id, custom_string, on_success2, on_fail2, on_timeout2, on_cancel2, on_product_illegal2, on_paying2); Singleton<FunctionAnySDK>.ins.PayListen(); } } public string GetChannelID() { string result = string.Empty; if (this.m_currentType == FunctionSDK.E_SDKType.Any) { result = Singleton<FunctionAnySDK>.ins.GetChannelID(); } return result; } public void HideWechat() { if (this.m_currentType == FunctionSDK.E_SDKType.XD) { MonoSingleton<FunctionXDSDK>.ins.HideWechat(); } } public string GetOrderID() { string result = string.Empty; if (this.m_currentType == FunctionSDK.E_SDKType.Any) { result = Singleton<FunctionAnySDK>.ins.GetOrderID(this.GetChannelID()); } else if (this.m_currentType == FunctionSDK.E_SDKType.XD) { result = MonoSingleton<FunctionXDSDK>.ins.GetOrderID(); } return result; } public void ResetPayState() { if (this.m_currentType == FunctionSDK.E_SDKType.Any) { Singleton<FunctionAnySDK>.ins.ResetPayState(); } } }
using System; class ReverseStringInPlace { public string ReverseString(string s) { char [] charArray= s.ToCharArray(); int i=0;int j=charArray.Length-1; while (i<j) { char temp=charArray[i]; charArray[i]=charArray[j]; charArray[j]=temp; i++; j--; } return new string(charArray); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace DriveMgr.IDAL { public interface IVehicleDAL { /// <summary> /// 增加一条数据 /// </summary> bool AddVehicle(Model.VehicleModel model); /// <summary> /// 更新一条数据 /// </summary> bool UpdateVehicle(Model.VehicleModel model); /// <summary> /// 删除一条数据 /// </summary> bool DeleteVehicle(int id); /// <summary> /// 批量删除数据 /// </summary> bool DeleteVehicleList(string idlist); /// <summary> /// 得到一个对象实体 /// </summary> Model.VehicleModel GetVehicleModel(int id); /// <summary> /// 获取分页数据 /// </summary> /// <param name="tableName">表名</param> /// <param name="columns">要取的列名(逗号分开)</param> /// <param name="order">排序</param> /// <param name="pageSize">每页大小</param> /// <param name="pageIndex">当前页</param> /// <param name="where">查询条件</param> /// <param name="totalCount">总记录数</param> string GetPagerData(string tableName, string columns, string order, int pageSize, int pageIndex, string where, out int totalCount); /// <summary> /// 获取车牌号集合 /// </summary> /// <returns></returns> string GetVehicleDT(); /// <summary> /// 获得数据列表 /// </summary> DataTable GetList(string strWhere); /// <summary> /// 获取记录总数 /// </summary> int GetRecordCount(string strWhere); /// <summary> /// 记录分配车辆情况 /// </summary> /// <param name="vehicleID"></param> /// <param name="dtStudents"></param> /// <param name="operater"></param> /// <returns></returns> bool AddDistributeVehicle(int vehicleID, int subjectId, DataTable dtStudents, string operater); /// <summary> /// 修改分配车辆信息 /// </summary> /// <param name="model"></param> /// <returns></returns> bool EditDistributeStudents(Model.DistributionVehicleModel model); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 敵管理クラス /// </summary> public class EnemyManager : Scene { [SerializeField, Tooltip("ステージ内の敵設定")] private List<GameObject> m_enemyList; //ダメージの管理、死亡処理 // Use this for initialization void Start () { } // Update is called once per frame void Update () { } /// <summary> /// ダメージを与える /// </summary> /// <param name="damage">自身の攻撃力</param> /// <param name="target">ダメージを減らす相手</param> public void EnemyDamage(int damage,GameObject target /*,int num*/) { ////属性ごとに判定 //switch (num) //{ // case 0: target.GetComponent<EnemyStatus>().Damage(damage); break; // case 1: // if () { target.GetComponent<EnemyStatus>().Damage(damage); } // break; // default: break; //} //ターゲット(敵)にもintをせっていしておく //それと同じ?だったら弱点 swixh必要ないか target.GetComponent<EnemyStatus>().Damage(damage); Debug.Log("敵:ぐはっ…"); } /// <summary> /// 雑魚敵死亡時 /// </summary> /// <param name="obj">自身</param> public void EnemyDead(GameObject obj) { //敵死亡時リストから削除 m_enemyList.Remove(obj); Destroy(obj); } /// <summary> /// ゲームクリア時 /// </summary> /// <param name="boss"></param> public void GameClear(GameObject boss) { m_enemyList.Remove(boss); Destroy(boss); //リザルトへ //OnNext(); OnClear(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ArteVida.GestorWeb.ViewModels { public class ImagemViewModel { [Required] public string Titulo { get; set; } public string Alternativo { get; set; } [DataType(DataType.Html)] public string Legenda { get; set; } [DataType(DataType.Upload)] public HttpPostedFileBase ImagemUpload { get; set; } } }
using System; namespace Factory.AbstractFactory { public class TruckFactory : CarFactory { public override Car CreateCar() { return new Truck(); } public override CarTester CreateTester() { return new TruckTester(); } } }
using GCLab_23.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace GCLab_23.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Register(string email) { gccoffeeshopEntities ORM = new gccoffeeshopEntities(); //need this is every operation that takes in information User UsertoEdit = ORM.Users.Find(email); if (UsertoEdit == null) { return RedirectToAction("Index"); } ViewBag.UserToEdit = UsertoEdit; //ToDo : validation return View(); } public ActionResult SaveChanges(User newUser) { gccoffeeshopEntities ORM = new gccoffeeshopEntities(); ORM.Users.Add(newUser); ORM.SaveChanges(); return RedirectToActionPermanent("Products"); } public ActionResult Products() { gccoffeeshopEntities ORM = new gccoffeeshopEntities(); ViewBag.Items = ORM.items.ToList(); return View(); } } }
using RestSharp; using RestSharp.Authenticators; namespace Framework.REST { public class ClientFactory { public string Url { get; private set; } public string Password { get; private set; } public string UserName { get; private set; } private Settings settings; public Settings Settings { get { return settings; } } internal ClientFactory() { Settings _settings = new Settings(); this.settings = _settings; } public RestClient GetClient() { // read from settings var client = new RestClient(Settings.CurrentHost) { //Authenticator = new HttpBasicAuthenticator(Settings.UserName, Settings.Password) }; return client; } public static RestClient GetClient(string host, string userName, string password) { //host = "http://localhost"; //userName = "dostapenko"; //password = "k}6MgZ/q12"; var client = new RestClient(host); client.Authenticator = new HttpBasicAuthenticator(userName, password); return client; } } }
using System; using System.Web.Mvc; using NBTM.Logic; using NBTM.ViewModels; namespace NBTM.Controllers { #if !DEBUG [Authorize(Roles = "SalesAppAccountExecutives,SalesAppAdmins")] #endif public class BacktrackController : BaseController { // // GET: /Backtrack/ public ActionResult Index(Guid id) { ViewBag.BacktrackActions = LookupListLogic.BacktrackActions; var model = ProjectLogic.CurrentProject(id, UserContext); return View(model); } [HttpPost] public ActionResult Index(ProjectViewModel.Project model) { ViewBag.BacktrackActions = LookupListLogic.BacktrackActions; var logic = ProjectLogic.UpdateBacktrackStatus(model, UserContext); var refreshModel = ProjectLogic.CurrentProject(model.ProjectId, UserContext); return View(refreshModel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace REQFINFO.Website.Models { public class StatusVM { public int IDTab { get; set; } public string Tab1 { get; set; } public int Sequence { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace oopsconcepts { class Generics { public static void Main() { // Arthmetic.Equal("s", 10); // bool a= Arthmetic.Equal<int>(20,10); bool a = Arthmetic<int>.Equal(20, 10); Console.WriteLine(a); Console.ReadLine(); } } public class Arthmetic<T> { //public static bool Equal(string s, string m) //{ // return s == m; //} public override string ToString() { return base.ToString(); } public static bool Equal(T i, T j) { return i.Equals(j); } } }
namespace Eyefinity.PracticeManagement.Controllers.Api { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Mvc; using Castle.Core.Internal; using Eyefinity.Enterprise.Business.Admin; using Eyefinity.PracticeManagement.Business.Admin; using Eyefinity.PracticeManagement.Common; using Eyefinity.PracticeManagement.Model; using Eyefinity.PracticeManagement.Model.Admin; using Eyefinity.PracticeManagement.Model.Admin.ViewModel; using IT2.Core; public class FrameController : ApiController { /// <summary>The logger</summary> private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly FrameIt2Manager frameIt2Manager; private readonly ProductsManager productsManager; private readonly string companyId; private readonly int dataSourceId; public FrameController() { this.frameIt2Manager = new FrameIt2Manager(); this.productsManager = new ProductsManager(); var user = new AuthorizationTicketHelper().GetUserInfo(); this.companyId = user.CompanyId; this.dataSourceId = this.frameIt2Manager.LookupDataSourceIdByCompany(this.companyId); } [System.Web.Http.HttpGet] public HttpResponseMessage GetBulkPricingModel() { ////var frameCollections = this.GetAllActiveFrameCollections(); var fromPriceListTypes = this.GetFromPriceListForFramesBulkPricing(); var toPriceListTypes = this.GetToPriceListForFramesBulkPricing(); var vm = new FrameBulkPriceVm { ////FrameCollections = frameCollections.ToKeyValuePairs(), FromPriceListTypes = fromPriceListTypes.ToKeyValuePairs(), ToPriceListTypes = toPriceListTypes.ToKeyValuePairs() }; return this.Request.CreateResponse(HttpStatusCode.OK, vm); } [System.Web.Http.HttpGet] public HttpResponseMessage GetCustomFrameSetupModel() { var manufacturers = this.GetAllFrameManufacturers(); var frameEdgeTypes = this.GetAllFrameEdgeTypes(); var frameMaterialTypes = this.GetAllFrameTypes(); var frameCategories = this.GetAllFrameCategories(); var vm = new FrameSetupVm { FrameManufacturers = manufacturers.ToKeyValuePairs(), FrameEdgeTypes = frameEdgeTypes.ToKeyValuePairs(), MaterialTypes = frameMaterialTypes.ToKeyValuePairs(), FrameCategories = frameCategories.ToKeyValuePairs(), }; return this.Request.CreateResponse(HttpStatusCode.OK, vm); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetAllFrameCollections() { var collections = this.GetAllFrameCollectionsByCompany(); return collections.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameCollections(string searchtext) { var collections = this.GetFrameCollectionsByName(searchtext); return collections.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameCollectionsByManufacturer(string manufacturerId) { var collections = this.GetFrameCollectionsByManufacturerId(manufacturerId); return collections.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameManufacturers(string searchtext) { var manufacturers = this.GetFrameManufacturersByName(searchtext); return manufacturers.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameManufacturers() { var manufacturers = this.GetAllFrameManufacturers(); return manufacturers.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameEdgeTypes() { var edgetypes = this.GetAllFrameEdgeTypes(); return edgetypes.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameTypes() { var frameTypes = this.GetAllFrameTypes(); return frameTypes.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameCategories() { var categories = this.GetAllFrameCategories(); return categories.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public List<KeyValuePair<string, string>> GetFrameStyles(string collectionId) { var styles = this.GetFrameStylesByCollectionId(Convert.ToInt32(collectionId)); return styles.ToKeyValuePairs(); } [System.Web.Mvc.HttpGet] public HttpResponseMessage GetKeyFromWebConfig() { var key = System.Configuration.ConfigurationManager.AppSettings["bulkFrameSetup"]; return this.Request.CreateResponse(HttpStatusCode.OK, key == "on"); } [System.Web.Http.HttpGet] public HttpResponseMessage GetCustomFrame( string officeNumber, string frameItemId) { FrameDetails result = this.frameIt2Manager.GetCustomFrame(frameItemId, this.companyId); return this.Request.CreateResponse( HttpStatusCode.OK, result); } [System.Web.Http.HttpGet] public HttpResponseMessage GetFrameCollectionByNameByManufacturer( string officeNumber, int manufacturerId, string collectionName) { var collectionId = this.frameIt2Manager.GetFrameCollectionByNameByManufacturer(manufacturerId, collectionName.Trim(), this.dataSourceId); return this.Request.CreateResponse( HttpStatusCode.OK, collectionId); } [System.Web.Http.HttpGet] public HttpResponseMessage GetFrameModelByNameByCollection( string officeNumber, int collectionId, string modelName) { var modelId = this.frameIt2Manager.GetFrameModelByNameByCollection(collectionId, modelName.Trim(), this.dataSourceId); return this.Request.CreateResponse( HttpStatusCode.OK, modelId); } [System.Web.Http.HttpGet] public HttpResponseMessage GetCustomFrameItemsAndStyleItem( string officeNumber, int collectionId, int modelId) { var results = this.GetCustomFrameItems(this.companyId, collectionId, modelId); var style = this.frameIt2Manager.GetFrameStyleById(modelId); return this.Request.CreateResponse( HttpStatusCode.OK, new { EdgeTypeId = style.FrameEdgeType, CategoryId = style.FrameCategory.ID.ToString(CultureInfo.InvariantCulture), MaterialId = style.FrameType.ID.ToString(CultureInfo.InvariantCulture), Frames = results.ToKeyValuePairs(), style.DataSourceId }); } [System.Web.Http.HttpGet] public HttpResponseMessage GetFrameItems( string officeNumber, string collectionId, string styleId, string searchText, bool activeOnly, [FromUri]int pageSize = 20, [FromUri]int pageStart = 0, [FromUri]string sortCol = null, [FromUri]string sortDirection = null) { bool? active = null; int? frameCollectionId = null; if (!string.IsNullOrEmpty(collectionId)) { frameCollectionId = Convert.ToInt32(collectionId); } int? frameStyleId = null; if (!string.IsNullOrEmpty(styleId)) { frameStyleId = Convert.ToInt32(styleId); } if (activeOnly) { active = true; } if (frameCollectionId == null && string.IsNullOrEmpty(searchText)) { var res = new Model.PagedResult<FrameSetup> { PageSize = pageSize, CurrentPage = pageStart / pageSize, TotalCount = 0, CurrentItems = new List<FrameSetup>().ToArray() }; return this.Request.CreateResponse(HttpStatusCode.OK, new { FrameSetupItems = res, HasCustomFrame = false }); } var sortDir = "ASC"; if (!string.IsNullOrEmpty(sortDirection)) { if (sortDirection == "Descending") { sortDir = "DESC"; } } int totalRecords; var items = this.frameIt2Manager.GetFrameItems(this.companyId, frameCollectionId, frameStyleId, searchText, active.GetValueOrDefault(), out totalRecords, this.dataSourceId, pageSize, pageStart, sortCol, sortDir); var hasCustomFrame = false; if (items != null && items.Any()) { var res = new Model.PagedResult<FrameSetup> { PageSize = pageSize, CurrentPage = pageStart / pageSize, TotalCount = items.Count, CurrentItems = items.Where((t, i) => i >= pageStart && i < pageStart + pageSize).ToArray() //// items.ToArray(), }; if (items.Any(item => item.IsCustomFrame == true)) { hasCustomFrame = true; } return this.Request.CreateResponse( HttpStatusCode.OK, new { FrameSetupItems = res, HasCustomFrame = hasCustomFrame }); } var result = new Model.PagedResult<FrameSetup> { PageSize = pageSize, CurrentPage = pageStart / pageSize, TotalCount = totalRecords, CurrentItems = new List<FrameSetup>().ToArray() }; if (totalRecords != 0) { return this.Request.CreateResponse(HttpStatusCode.RequestedRangeNotSatisfiable, totalRecords.ToString(CultureInfo.InvariantCulture)); } return this.Request.CreateResponse(HttpStatusCode.OK, new { FrameSetupItems = result, HasCustomFrame = false }); } [System.Web.Http.HttpPut] public HttpResponseMessage GetBulkPricePreviewItems( [FromUri]string officeNumber, [FromUri]string fromPriceList, [FromUri]string toPriceList, [FromUri]string changeTypeValue, [FromUri]bool changeTypePercentage, [FromUri]string dollarAmount, [FromUri]bool dollarAdd, [FromUri]string rounding, [FromUri]bool activeOnly, [FromUri]bool all, List<int> collectionIds, [FromUri]int pageSize = 20, [FromUri]int pageStart = 0, [FromUri]string sortCol = null, [FromUri]string sortDirection = null) { if (string.IsNullOrEmpty(fromPriceList) || string.IsNullOrEmpty(toPriceList) || (collectionIds == null)) { return Request.CreateResponse(HttpStatusCode.ExpectationFailed); } var items = this.productsManager.GetBulkPricing( this.companyId, fromPriceList, changeTypeValue, changeTypePercentage, dollarAmount, dollarAdd, rounding, activeOnly, collectionIds, pageSize, pageStart, sortCol, sortDirection); var frameBulkPrices = items as IList<FrameBulkPrice> ?? items.ToList(); var firstOrDefault = frameBulkPrices.FirstOrDefault(); var totalCount = 0; if (firstOrDefault != null) { totalCount = firstOrDefault.TotalRowNum; } var res = new Model.PagedResult<FrameBulkPrice> { PageSize = pageSize, CurrentPage = pageStart / pageSize, TotalCount = totalCount, CurrentItems = frameBulkPrices.ToArray() }; return Request.CreateResponse( HttpStatusCode.OK, new { PreviewItems = res, }); } [System.Web.Http.HttpGet] public HttpResponseMessage GetIsOfficeFramesMapped(string officeNumber) { // ReSharper disable once RedundantNameQualifier List<Model.Lookup> officeCollections = this.frameIt2Manager.GetAllActiveFrameCollections(this.companyId); return this.Request.CreateResponse(HttpStatusCode.OK, !officeCollections.IsNullOrEmpty()); } [System.Web.Http.HttpPut] public HttpResponseMessage SaveFrameBulkPricing( [FromUri]string officeNumber, [FromUri]string fromPriceList, [FromUri]string toPriceList, [FromUri]string changeTypeValue, [FromUri]bool changeTypePercentage, [FromUri]string dollarAmount, [FromUri]bool dollarAdd, [FromUri]string rounding, [FromUri]bool activeOnly, [FromUri]bool all, List<int> collectionIds) { var message = this.productsManager.SaveBulkPricing(this.companyId, fromPriceList, changeTypeValue, changeTypePercentage, dollarAmount, dollarAdd, rounding, activeOnly, all, collectionIds); return Request.CreateResponse( HttpStatusCode.OK, new { HasZeroPrice = message }); } [System.Web.Http.HttpPut] public HttpResponseMessage SaveCustomFrame(string officeNumber, FrameDetails items) { var token = new AuthorizationTicketHelper().GetToken(); var frame = this.frameIt2Manager.SaveCustomFrameItems(items, this.companyId, this.dataSourceId, token); ////return Request.CreateResponse(HttpStatusCode.OK, frame); return Request.CreateResponse( HttpStatusCode.OK, new { ManufacturerId = frame.Style.Collection.Manufacturer.ID, CollectionId = frame.Style.Collection.ID, ModelId = frame.Style.ID, ItemId = frame.ID }); } [System.Web.Http.HttpPut] public HttpResponseMessage SaveFrameItems(string officeNumber, IEnumerable<FrameSetup> items) { var token = string.Empty; //// new AuthorizationTicketHelper().GetToken(); this.frameIt2Manager.SaveFrameItems(items, this.companyId, token); return Request.CreateResponse(HttpStatusCode.OK, "Frame Items saved."); } [System.Web.Http.HttpDelete] public HttpResponseMessage DeleteCustomFrameItem(string officeNumber, int frameItemId) { try { var token = new AuthorizationTicketHelper().GetToken(); this.frameIt2Manager.DeleteCustomFrameItem(frameItemId, this.companyId, token); return new HttpResponseMessage(HttpStatusCode.NoContent); } catch (Exception ex) { var msg = string.Format("DeleteCustomFrameItem\n {0}", ex); return HandleExceptions.LogExceptions(msg, Logger, ex); } } // DeleteCustomFramesItems [System.Web.Http.HttpGet] public HttpResponseMessage GetCountFramesByUpcCode(string officeNumber, string upcCode) { try { if (!string.IsNullOrEmpty(upcCode)) { int count = 0; var frames = this.frameIt2Manager.GetFramesByUpcCode(upcCode, this.companyId, this.dataSourceId); if (frames != null) { count = frames.Count; } return this.Request.CreateResponse(HttpStatusCode.OK, count); } return this.Request.CreateResponse(HttpStatusCode.OK, 0); } catch (Exception ex) { var msg = string.Format("GetFramesByUpcCode(upcCode: {0}, companyId: {1}, dataSourceId: {2})\n {3}", upcCode, this.companyId, this.dataSourceId, ex); return HandleExceptions.LogExceptions(msg, Logger, ex); } } // GetFramesByUpcCode public HttpResponseMessage GetEgFrameBySearchCriteria(string searchCriteria, string officeNumber) { var token = new AuthorizationTicketHelper().GetToken(); var status = string.Empty; var criteria = searchCriteria.Trim(); var frames = this.frameIt2Manager.GetEgFrameBySearchCriteria(criteria, token, this.companyId, ref status); ////Customer supplied frame if (status == string.Empty && criteria == "PatientOwnFrame") { var upcCode = frames[0].UPCCode; var frameId = frames[0].Id; var selectedFrameDisplay = this.frameIt2Manager.GetEgFrameByFrame(token, this.companyId, officeNumber, upcCode, string.Empty, frameId, 2, token); ////ALSL-8077 VSP claim submission fails when non-stock frame is oversize if (selectedFrameDisplay != null) { selectedFrameDisplay.Eye = null; } return Request.CreateResponse(HttpStatusCode.OK, selectedFrameDisplay); } return status == string.Empty ? Request.CreateResponse(HttpStatusCode.OK, frames) : Request.CreateResponse(HttpStatusCode.BadRequest, status); } public HttpResponseMessage GetEgFrameByFrame(int orderType, int frameId, string officeNumber, string upcCode, string productCode) { var token = new AuthorizationTicketHelper().GetToken(); var upcCode1 = string.Format("{0}", System.Web.HttpUtility.UrlDecode(upcCode)); var jobsonProductCode = string.Format("{0}", System.Web.HttpUtility.UrlDecode(productCode)); var selectedFrameDisplay = this.frameIt2Manager.GetEgFrameByFrame(token, this.companyId, officeNumber, upcCode1.Trim(), jobsonProductCode.Trim(), frameId, orderType, token); return selectedFrameDisplay == null ? Request.CreateResponse(HttpStatusCode.BadRequest, selectedFrameDisplay) : Request.CreateResponse(HttpStatusCode.OK, selectedFrameDisplay); } [System.Web.Http.HttpPut] public HttpResponseMessage UpdateEgFrameRetailPrice([FromBody]EyeglassOrderFrameVm frameDisplay, string officeNumber, string retailPrice) { var token = new AuthorizationTicketHelper().GetToken(); var price = Convert.ToDouble(retailPrice); var errMsg = this.frameIt2Manager.UpdateSelectedEgFrame(this.companyId, officeNumber, price, frameDisplay, token); return errMsg == string.Empty ? Request.CreateResponse(HttpStatusCode.OK, "Frame retail price saved.") : Request.CreateResponse(HttpStatusCode.BadRequest, errMsg); } #region Private functions private List<SelectListItem> GetAllFrameCollectionsByCompany() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetAllActiveFrameCollections(this.companyId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetFrameCollectionsByName(string searchText) { var result = new List<SelectListItem>(); if (string.IsNullOrEmpty(searchText)) { return result; } var lookups = this.frameIt2Manager.GetFrameCollectionsByName(searchText, this.dataSourceId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetFrameCollectionsByManufacturerId(string manufacturerId) { var result = new List<SelectListItem>(); if (string.IsNullOrEmpty(manufacturerId)) { return result; } var lookups = this.frameIt2Manager.GetFrameCollectionsByManufacturerId(Convert.ToInt32(manufacturerId), this.dataSourceId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetFrameManufacturersByName(string searchText) { var result = new List<SelectListItem>(); if (string.IsNullOrEmpty(searchText)) { return result; } var lookups = this.frameIt2Manager.GetFrameManufacturersByName(searchText); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetAllFrameManufacturers() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetAllFrameManufacturers(this.dataSourceId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetAllFrameEdgeTypes() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetAllFrameEdgeTypes(); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.KeyStr.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetAllFrameTypes() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetAllFrameTypes(); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetAllFrameCategories() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetAllFrameCategories(); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetFrameStylesByCollectionId(int collectionId) { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetFrameStylesByCollectionId(collectionId, this.dataSourceId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetFromPriceListForFramesBulkPricing() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetFromPriceListForFramesBulkPricing(this.companyId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.KeyStr.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetToPriceListForFramesBulkPricing() { var result = new List<SelectListItem>(); var lookups = this.frameIt2Manager.GetPriceListForFrames(this.companyId); lookups.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.KeyStr.ToString(CultureInfo.InvariantCulture) })); return result; } private List<SelectListItem> GetCustomFrameItems(string companyId, int collectionId, int modelId) { var result = new List<SelectListItem>(); var activeFrames = this.frameIt2Manager.GetCustomFrameItems(companyId, collectionId, modelId, true, this.dataSourceId); var inactiveFrames = this.frameIt2Manager.GetCustomFrameItems(companyId, collectionId, modelId, false, this.dataSourceId); var mergedFrames = activeFrames.Union(inactiveFrames).ToList(); mergedFrames.ForEach(l => result.Add(new SelectListItem { Selected = false, Text = l.Description, Value = l.Key.ToString(CultureInfo.InvariantCulture) })); return result; } #endregion // Private functions } }
using FastSQL.App.Events; using FastSQL.App.Interfaces; using FastSQL.Core.UI.Events; using FastSQL.Sync.Core.Settings; using Prism.Events; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace FastSQL.App.UserControls { public class UCSettingsListViewViewModel: BaseViewModel { private ObservableCollection<ISettingProvider> _settings; private ISettingProvider _selectedSetting; private readonly IEventAggregator eventAggregator; public ObservableCollection<ISettingProvider> Settings { get { return _settings; } set { _settings = value ?? new ObservableCollection<ISettingProvider>(); OnPropertyChanged(nameof(Settings)); } } public ISettingProvider SelectedSetting { get { return _selectedSetting; } set { _selectedSetting = value; OnPropertyChanged(nameof(SelectedSetting)); } } public BaseCommand SelectItemCommand => new BaseCommand(o => true, o => { var id = o.ToString(); eventAggregator.GetEvent<SelectSettingEvent>().Publish(new SelectSettingEventArgument { SettingId = id }); }); public UCSettingsListViewViewModel ( IEnumerable<ISettingProvider> settingManagers, IEventAggregator eventAggregator) { Settings = new ObservableCollection<ISettingProvider>(settingManagers); this.eventAggregator = eventAggregator; } } }
using DesignApp.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DesignApp.Views { /// <summary> /// Interaction logic for HomePage.xaml /// </summary> public partial class HomePage : Page { List<ListData> data = new List<ListData>(); public HomePage() { InitializeComponent(); FillListData(); } private void FillListData() { data.Add(new ListData { Date = "01/01/01", Lane = "1", PlateNumber = "0001", Country = "India", VehNo = "ind04", Status = "Ready", Color = "Red", BgColor = "greeen", Categorytype = "1", Type = "1" }); data.Add(new ListData { Date = "02/01/01", Lane = "2", PlateNumber = "0002", Country = "India", VehNo = "ind05", Status = "Ready", Color = "Red", BgColor = "greeen", Categorytype = "2", Type = "2" }); data.Add(new ListData { Date = "03/01/01", Lane = "3", PlateNumber = "0003", Country = "India", VehNo = "ind01", Status = "Ready", Color = "Red", BgColor = "greeen", Categorytype = "3", Type = "3" }); data.Add(new ListData { Date = "04/01/01", Lane = "4", PlateNumber = "0004", Country = "India", VehNo = "ind03", Status = "Ready", Color = "Red", BgColor = "greeen", Categorytype = "4", Type = "4" }); data.Add(new ListData { Date = "05/01/01", Lane = "5", PlateNumber = "0005", Country = "India", VehNo = "ind02", Status = "Ready", Color = "Red", BgColor = "greeen", Categorytype = "5", Type = "5" }); listDetails.ItemsSource = data; } } }
using System; using System.Collections.Generic; using FluentAssertions; using FluentAssertions.Extensions; using Xunit; namespace LeeConlin.ExtensionMethods.Tests.DateTimeExtensions { public class ToAgeInYears_Should { public static IEnumerable<object[]> TestData => new List<object[]> { // We only really care to the day. new object[] { DateTime.Now.AddYears(-12), 12 }, new object[] { DateTime.Now.AddYears(-12).AddDays(1), 11 }, new object[] { DateTime.Now.AddYears(-12).AddHours(1), 12 }, new object[] { DateTime.Now.AddYears(-12).AddMinutes(1), 12 }, new object[] { DateTime.Now.AddYears(-12).AddSeconds(1), 12 }, new object[] { DateTime.Now.AddYears(-12).AddMilliseconds(1), 12 }, new object[] { DateTime.Now.AddYears(-12).AddMicroseconds(1), 12 } }; [Theory] [MemberData(nameof(TestData))] public void Return_Age_Correctly(DateTime sut, int expected) { sut.ToAgeInYears().Should().Be(expected); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using unirest_net.http; using Xamarin; namespace YodaSpeak.Services { public class ServiceConsumer { public string CreateTranslation(string inputSentence) { string sentence = inputSentence; string translation = ""; if (sentence == "") { translation = "Silence, I translate can not. Try again you must, young padawan!"; } else { translation = GetYodaStringFromApi(sentence); } return translation; } public string GetYodaStringFromApi(string sentence) { string errorMessage = ""; try { //Log time to execute API call to Insight var handle = Insights.TrackTime("APICalltime"); handle.Start(); var response = Unirest.get("https://yoda.p.mashape.com/yoda?sentence=" + sentence) .header("X-Mashape-Key", "1qAnYqJfWWmshrB8KM9t2BSyEXwnp1rGVVXjsnpN6AKtfntGAv") .header("Accept", "text/plain") .asString(); handle.Stop(); if (response.Code == 200) { return response.Body; } //!= 200 errorMessage = "Wrong something went. HTTP errors leads to anger. Anger leads to hate. Hate leads to suffering."; return errorMessage; } catch (Exception ex) { //Log exception to insight Insights.Report(ex); errorMessage = "Wrong something went. Connected to the interwebz are you, hmm?"; return errorMessage; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Freedom_Logger { public enum LogLevel { Low = 0, Warning = 1, Error = 2, Debug = 4, Info = 8, } }
using System.ComponentModel.DataAnnotations; namespace OdeToFood2017.Entities { public enum CuisinType { None, Fastfood, Italian } public class Restaurant { public int Id { get; set; } [Required,MaxLength(80)] public string Name { get; set; } public CuisinType Cuisine { get; set; } } }
namespace SimpleMapping.Client.DTO { using System; class EmployeeDto { public string FirstName { get; set; } public string LastName { get; set; } public decimal Salary { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Roger { public partial class mainForm : Form { public mainForm() { InitializeComponent(); } private void mainForm_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.K) { mainView.DeviceBox.clearListItems(); } } } }
using System; namespace FactoryMethod.Entities.Personagens { public class SubZero : IPersonagem { public void Escolhido() { Console.Write("Sub Zero"); } } }
using System.Collections.Generic; namespace LibraryWebApp.Entities { public class Author { public int Id { get ; set; } public string Name { get; set; } public List<BookResponse> Books { get; set; } public Author(int id, string name, List<BookResponse> books) : this(id, name) { this.Books = books; } public Author(int id, string name) { this.Id = id; this.Name = name; } public Author(string name) { this.Name = name; } public Author() { } } }
/* ********************************************** * 版 权:亿水泰科(EWater) * 创建人:zhujun * 日 期:2019/5/20 16:36:04 * 描 述:RiverRepository * *********************************************/ 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 IPstatRepository : IDependency { #region 降水量累计-统计 /// <summary> /// 降水量累计-统计-多日-多日均值表 /// </summary> /// <param name="STCD">站名</param> /// <param name="sdate">开始日期</param> /// <param name="edate">结束日期</param> /// <returns>时段内单日累计</returns> IEnumerable<ST_PSTATEntity> GetDayData(string STCD, string sdate, string edate, int type, string addvcd); /// <summary> /// 降水量累计-统计-多日-实时表 /// </summary> /// <param name="STCD">站名</param> /// <param name="sdate">开始日期</param> /// <param name="edate">结束日期</param> /// <returns>时段内单日累计</returns> IEnumerable<ST_PSTATEntity> GetDayData_ByPPTN(string STCD, string sdate, string edate, int type, string addvcd); /// <summary> /// 降水量累计-统计-旬月 /// </summary> /// <param name="STCD">站名</param> /// <param name="sdate">开始日期</param> /// <param name="edate">结束日期</param> /// <returns>时段内旬月累计</returns> IEnumerable<ST_PSTATEntity> GetMonthData(string STCD, string sdate, string edate, int type, string addvcd); /// <summary> /// 降水量累计-统计-年 /// </summary> /// <param name="STCD">站名</param> /// <param name="sdate">开始日期</param> /// <param name="edate">结束日期</param> /// <returns>指定年份12个月的月累计</returns> IEnumerable<ST_PSTATEntity> GeYearData(string STCD, string sdate, string edate, int type, string addvcd); #endregion #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 GetMonthComparativeData(string STCD, string STTDRCD, string sdate, string edate, string sdate_history, string edate_history); #endregion } }
using System; namespace Shango.CommandProcessor { public interface ICommandEnvironment { void CloseEnvironment(); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using SparkAPI.Data; using SparkAPI.Models; namespace SparkAPI.Controllers { [Route("api/[controller]")] [ApiController] public class DatasetsController : ControllerBase { private readonly SparkAPIContext _context; public DatasetsController(SparkAPIContext context) { _context = context; } // GET: api/Datasets [HttpGet] public async Task<ActionResult<IEnumerable<Dataset>>> GetDataset(string path1, string path2) { ProcessStartInfo infos = new ProcessStartInfo(); infos.FileName = "cmd.exe"; infos.Arguments = @"/c cd ..\GettingData\bin\Debug\netcoreapp3.1 && dotnet build ..\..\..\GettingData.csproj && spark-submit --class org.apache.spark.deploy.dotnet.DotnetRunner --master local microsoft-spark-2.4.x-0.12.1.jar dotnet GettingData.dll " + path1 + " "+ path2; Process cmd = new Process(); cmd.StartInfo = infos; cmd.Start(); return await _context.Dataset.ToListAsync(); } // GET: api/Datasets/5 [HttpGet("{id}")] public async Task<ActionResult<Dataset>> GetDataset(long id) { var dataset = await _context.Dataset.FindAsync(id); if (dataset == null) { return NotFound(); } return dataset; } // PUT: api/Datasets/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutDataset(long id, Dataset dataset) { if (id != dataset.Id) { return BadRequest(); } _context.Entry(dataset).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DatasetExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Datasets // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<Dataset>> PostDataset(Dataset dataset) { _context.Dataset.Add(dataset); await _context.SaveChangesAsync(); return CreatedAtAction("GetDataset", new { id = dataset.Id }, dataset); } // DELETE: api/Datasets/5 [HttpDelete("{id}")] public async Task<ActionResult<Dataset>> DeleteDataset(long id) { var dataset = await _context.Dataset.FindAsync(id); if (dataset == null) { return NotFound(); } _context.Dataset.Remove(dataset); await _context.SaveChangesAsync(); return dataset; } private bool DatasetExists(long id) { return _context.Dataset.Any(e => e.Id == id); } } }
using System; using System.Collections.Generic; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.DB.Architecture; using System.Linq; namespace Lab1PlaceGroup { //获取当前选择集中包含的对象 [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] public class Class1 : IExternalCommand { public Result Execute(ExternalCommandData commandData, ref string messages, ElementSet elements) { UIDocument uiDoc = commandData.Application.ActiveUIDocument; Document doc = uiDoc.Document; //定义变量 Dictionary<string, double> floor = new Dictionary<string, double>(); // Stack<string> refuge = new Stack<string>();//用来存放避难间的标高 SortedSet<double> refuge_height = new SortedSet<double>(); double height = 0.0; double minHeight = 0.0; bool ifHigher = true;//用来判断是否小于50000mm==50m,true表示小于50m Transaction ts = new Transaction(uiDoc.Document, "level"); ts.Start(); FilteredElementCollector collector = new FilteredElementCollector(uiDoc.Document); ICollection<Element> collection = collector.OfClass(typeof(Level)).ToElements(); foreach (Element e in collection) { // TaskDialog.Show("标高", e.Name); ParameterSet parameterSet = e.Parameters; foreach (Parameter pa in parameterSet) { if (pa.Definition.Name == "立面") { double levelheight = Double.Parse(pa.AsValueString()); floor.Add(e.Name, levelheight); if (height < levelheight) { height = levelheight; } // TaskDialog.Show("立面高度:", pa.AsValueString()); break; } } } ts.Commit(); //TaskDialog.Show("建筑高度:", height.ToString()); foreach (string key in floor.Keys) { TaskDialog.Show("Floor", key + " :\n " + floor[key].ToString()); } if (height >= 100000)//如果建筑高度大于100米 { FilteredElementCollector filteredElements = new FilteredElementCollector(doc); ElementCategoryFilter roomTagFilter = new ElementCategoryFilter(BuiltInCategory.OST_Rooms); filteredElements = filteredElements.WherePasses(roomTagFilter); foreach (Room room in filteredElements) { if (room.Name.IndexOf("避难间") >= 0) { refuge_height.Add(floor[room.Level.Name]); } } double lastHeight = 0.0; foreach (double rheight in refuge_height) { //TaskDialog.Show("避难间高度", rheight.ToString()); if (minHeight > rheight) { minHeight = rheight; } if (ifHigher && rheight - lastHeight <= 50000)//不大于50m { lastHeight = rheight; } else { ifHigher = false; } } if (minHeight <= 50000 && ifHigher) { TaskDialog.Show("避难间检查结果:", "避难间设计合格"); } else if (minHeight <= 50000 && !ifHigher) { TaskDialog.Show("避难间检查结果:", "避难间设计不合格:\n+两个避难间之间的高度大于50m!"); } else if (minHeight > 50000 && ifHigher) { TaskDialog.Show("避难间检查结果:", "避难间设计不合格:\n+第一个避难层间的楼地面至灭火救援场地地面的高度大于50m!"); } else { TaskDialog.Show("避难间检查结果:", "避难间设计不合格:\n+第一个避难层间的楼地面至灭火救援场地地面的高度大于50m且两个避难间之间的高度大于50m!"); } } return Result.Succeeded; } } }
/// <summary> /// Windows Presentation Foundation translator namespace /// </summary> namespace WPFTranslator { /// <summary> /// Language class /// </summary> public class Language { /// <summary> /// Name key /// </summary> private readonly string nameKey; /// <summary> /// Culture /// </summary> public readonly string Culture; /// <summary> /// Name /// </summary> public string Name { get { return Translator.GetTranslation(nameKey); } } /// <summary> /// Language /// </summary> /// <param name="nameKey">Name key</param> /// <param name="culture">Culture</param> public Language(string nameKey, string culture) { this.nameKey = nameKey; Culture = culture; } /// <summary> /// To string /// </summary> /// <returns>String representation</returns> public override string ToString() { return Name; } } }
using System; using System.IO; using System.Net; using System.Text; namespace Customer.Until { class HttpUntil { private const String urlClient = "http://localhost:8080/api/"; private static HttpWebRequest http; private static String result; /** * get restful * path api 接口除却固定的地址外的可变虚拟目录 * token 令牌 */ public static String GetClient(String path, String token) { //以Get方式调用 http = WebRequest.Create(new Uri(urlClient + path)) as HttpWebRequest; http.Headers.Add("Authorization", token); using HttpWebResponse response = http.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } /** * get restful * path api 接口除却固定的地址外的可变虚拟目录 */ public static String GetClient(String path) { //以Get方式调用 http = WebRequest.Create(new Uri(urlClient + path)) as HttpWebRequest; using HttpWebResponse response = http.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } /** * post restful * token 令牌 * data 需要提交的参数 * path api 接口除却固定的地址外的可变虚拟目录 */ public static String PostClient(String path, StringBuilder data, String token) { //以Post方式调用 Uri address = new Uri(urlClient + path); http = WebRequest.Create(address) as HttpWebRequest; http.Method = "POST"; http.ContentType = "application/x-www-form-urlencoded"; http.Headers.Add("token", token); /**String id = "789"; String name = "test"; StringBuilder data = new StringBuilder(); //调用HttpUtility需要在.net 4.0框架下,并且添加System.web.dll引用,请自行谷歌 data.Append("id=" + System.Web.HttpUtility.UrlEncode(id)); data.Append("&name=" + System.Web.HttpUtility.UrlEncode(name));*/ byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); http.ContentLength = byteData.Length; using (Stream postStream = http.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); postStream.Close(); } using HttpWebResponse response = http.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(response.GetResponseStream()); //Console.WriteLine(reader.ReadToEnd()); result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } /** * post restful * data 需要提交的参数 * path api 接口除却固定的地址外的可变虚拟目录 */ public static String PostClient(String path, StringBuilder data) { //以Post方式调用 Uri address = new Uri(urlClient + path); http = WebRequest.Create(address) as HttpWebRequest; http.Method = "POST"; http.ContentType = "application/x-www-form-urlencoded"; byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); http.ContentLength = byteData.Length; using (Stream postStream = http.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); postStream.Close(); } using HttpWebResponse response = http.GetResponse() as HttpWebResponse; StreamReader reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } } }
using App1; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace GeneradorRFC { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PaginaRFC : ContentPage { public PaginaRFC() { InitializeComponent(); btnAtras.Clicked += (sender, e) => { Navigation.PushAsync(new MainPage()); }; } //METODO QUE GENERA EL RFC async void GenerarRFC_Clicked(object sender, EventArgs e) { if (txtNombre.Text != "" && txtPapellido.Text != "" && txtMapellido.Text != "" && txtFecha.Text != "") { string rfc = ""; bool respuesta = await DisplayAlert("GENERAR RFC:", "¿TUS DATOS SON CORRECTOS?", "SI, CONTINUAR", "NO, CORREGIR"); Console.WriteLine("Respuesta" + respuesta); if (respuesta == true) { //SE CONVIERTEN A MAYUSCULAS LOS DATOS DE LAS CAJAS DE TEXTO txtPapellido.Text = txtPapellido.Text.ToUpper(); txtMapellido.Text = txtMapellido.Text.ToUpper(); txtNombre.Text = txtNombre.Text.ToUpper(); //SE VAN ACUMULANDO LAS CADENAS EN LA VARIABLE STRING DECLARADA RFC rfc += txtPapellido.Text.Substring(0, 1); rfc += txtPapellido.Text.Substring(1, 1); rfc += txtMapellido.Text.Substring(0, 1); rfc += txtNombre.Text.Substring(0, 1); rfc += txtFecha.Text.Substring(8, 2); rfc += txtFecha.Text.Substring(3, 2); rfc += txtFecha.Text.Substring(0, 2); } //SE MUESTRA EN EL LABEL LA CADENA RFC lblMuestraRFC.Text = rfc+"1H0"; } else { lblMuestraRFC.Text = "DEBE LLENAR LOS DATOS SOLICITADOS."; } } //METODO QUE LIMPIA ENTRADAS private void btnLimpiar_Clicked(object sender, EventArgs e) { txtNombre.Text = ""; txtMapellido.Text = ""; txtPapellido.Text = ""; txtFecha.Text = ""; lblMuestraRFC.Text = ""; } } }
using System; using System.Collections.Generic; using Amazon.Lambda.ApplicationLoadBalancerEvents; using Amazon.Lambda.Core; using Epsagon.Dotnet.Core; using Newtonsoft.Json; using OpenTracing; namespace Epsagon.Dotnet.Instrumentation.Triggers { public class ElasticLoadBalancerLambda : BaseTrigger<ApplicationLoadBalancerRequest> { public ElasticLoadBalancerLambda(ApplicationLoadBalancerRequest input) : base(input) { } public override void Handle(ILambdaContext context, IScope scope) { base.Handle(context, scope); var config = Utils.CurrentConfig; scope.Span.SetTag("event.id", $"elb-{Guid.NewGuid().ToString()}"); scope.Span.SetTag("resource.type", "elastic_load_balancer"); scope.Span.SetTag("resource.name", input.Path); scope.Span.SetTag("resource.operation", input.HttpMethod); scope.Span.SetTag("aws.elb.query_string_parameters", JsonConvert.SerializeObject(input.QueryStringParameters, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); scope.Span.SetTag("aws.elb.target_group_arn", input.RequestContext.Elb.TargetGroupArn); if (!config.MetadataOnly) { scope.Span.SetTag("aws.elb.body", input.Body); scope.Span.SetTag("aws.elb.headers", JsonConvert.SerializeObject(input.Headers, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace ConASCII { class AdvancedConsoleColor { public static ConsoleColorInfluence[] ConsoleColorDictonary { get; } = new ConsoleColorInfluence[16] { new ConsoleColorInfluence(ConsoleColor.Black, Color.FromRgb(0, 0, 0), (int)Math.Floor(Math.Pow(Math.Pow(75,2) * 3,0.5))), new ConsoleColorInfluence(ConsoleColor.White, Color.FromRgb(255, 255, 255), (int)Math.Floor(Math.Pow(Math.Pow(75,2) * 3,0.5))), new ConsoleColorInfluence(ConsoleColor.Gray, Color.FromRgb(255, 255, 255), (int)Math.Floor(Math.Pow(Math.Pow(256,2) * 3,0.5))), new ConsoleColorInfluence(ConsoleColor.DarkGray, Color.FromRgb(0, 0, 0), (int)Math.Floor(Math.Pow(Math.Pow(256,2) * 3,0.5))), new ConsoleColorInfluence(ConsoleColor.DarkBlue, Color.FromRgb(0, 54, 215), 100), new ConsoleColorInfluence(ConsoleColor.DarkGreen, Color.FromRgb(19, 161, 14), 100), new ConsoleColorInfluence(ConsoleColor.DarkCyan, Color.FromRgb(54, 151, 219), 100), new ConsoleColorInfluence(ConsoleColor.DarkRed, Color.FromRgb(197, 15, 31), 75), new ConsoleColorInfluence(ConsoleColor.DarkMagenta, Color.FromRgb(134, 22, 150), 75), new ConsoleColorInfluence(ConsoleColor.DarkYellow, Color.FromRgb(193, 156, 0), 100), new ConsoleColorInfluence(ConsoleColor.Blue, Color.FromRgb(59, 118, 254), 75), new ConsoleColorInfluence(ConsoleColor.Green, Color.FromRgb(22, 198, 12), 100), new ConsoleColorInfluence(ConsoleColor.Cyan, Color.FromRgb(92, 215, 213), 75), new ConsoleColorInfluence(ConsoleColor.Red, Color.FromRgb(231, 72, 86), 75), new ConsoleColorInfluence(ConsoleColor.Magenta, Color.FromRgb(180, 0, 158), 75), new ConsoleColorInfluence(ConsoleColor.Yellow, Color.FromRgb(242, 242, 165), 25), }; } }
using System; using System.Collections.Generic; using Android.App; using Android.OS; using Android.Views; using Android.Widget; using OxyPlot.Xamarin.Android; using OxyPlot; using OxyPlot.Series; using Android.Support.V7.Widget; using JKMAndroidApp.adapter; using Android.Support.V7.Widget.Helper; using JKMPCL.Services; using JKMPCL.Model; using JKMAndroidApp.Common; namespace JKMAndroidApp.fragment { public class FragmentDashboard : Android.Support.V4.App.Fragment { public interface IItemTouchHelperAdapter { bool OnItemMove(int oldPosition, int newPosition); void OnItemDismiss(int position); } private View view; private TextView tvLeftDays; private TextView tvFromCity; private TextView tvFromAddress; private TextView tvToCity; private TextView tvToAddress; private TextView tvEndDate; private TextView tvStartDate; private TextView tvStatus; private ImageView imgViewInnerChartStatus; private ImageView imgViewStatus; private LinearLayout lnLeftDays; private RelativeLayout relativeLayoutParentDashbord; private RecyclerView recylerViewDashboard; private RelativeLayout relativeLayoutPieChart; ProgressDialog progressDialog; private MoveDataModel dtoMoveData; public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.Inflate(Resource.Layout.LayoutFragmentDashboard, container, false); dtoMoveData = DTOConsumer.dtoMoveData; UIReference(); BindMoveDataAsync(); ApplyFont(); return view; } /// Method Name : UIReference /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Find all control /// Revision : /// </summary> private void UIReference() { recylerViewDashboard = view.FindViewById<RecyclerView>(Resource.Id.recylerViewDashboard); tvLeftDays = view.FindViewById<TextView>(Resource.Id.tvLeftDays); lnLeftDays = view.FindViewById<LinearLayout>(Resource.Id.lnLeftDays); tvFromCity = view.FindViewById<TextView>(Resource.Id.tvFromCity); tvFromAddress = view.FindViewById<TextView>(Resource.Id.tvFromAddress); tvToCity = view.FindViewById<TextView>(Resource.Id.tvToCity); tvToAddress = view.FindViewById<TextView>(Resource.Id.tvToAddress); tvStartDate = view.FindViewById<TextView>(Resource.Id.tvStartDate); tvEndDate = view.FindViewById<TextView>(Resource.Id.tvEndDate); imgViewInnerChartStatus = view.FindViewById<ImageView>(Resource.Id.ImgViewInnerChartStatus); tvStatus = view.FindViewById<TextView>(Resource.Id.tvStatus); imgViewStatus = view.FindViewById<ImageView>(Resource.Id.ImgViewStatus); relativeLayoutPieChart = view.FindViewById<RelativeLayout>(Resource.Id.relativeLayoutPieChart); relativeLayoutParentDashbord = view.FindViewById<RelativeLayout>(Resource.Id.relativeLayoutParentDashbord); relativeLayoutParentDashbord.Visibility = ViewStates.Invisible; } /// <summary> /// Method Name : BindMoveData /// Author : Hiren Patel /// Creation Date : 30 Dec 2017 /// Purpose : To bind Move data with UI element /// Revision : /// </summary> private void BindMoveDataAsync() { Move move; move = new Move(); string errorMessage = string.Empty; try { progressDialog = UIHelper.SetProgressDailoge(Activity); if (dtoMoveData is null) { relativeLayoutParentDashbord.Visibility = ViewStates.Invisible; AlertMessage(StringResource.msgDashboardNotLoad); } else { if (dtoMoveData.response_status) { SetMoveData(dtoMoveData); } else { errorMessage = dtoMoveData.message; relativeLayoutParentDashbord.Visibility = ViewStates.Invisible; progressDialog.Dismiss(); } } } catch (Exception error) { progressDialog.Dismiss(); errorMessage = error.Message; } finally { if (!string.IsNullOrEmpty(errorMessage)) { AlertMessage(errorMessage); } } } /// Method Name : SetMoveData /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for move binding data and check active and inactive move /// Revision : /// </summary> private void SetMoveData(MoveDataModel dtoMoveData) { if (dtoMoveData is null) { relativeLayoutParentDashbord.Visibility = ViewStates.Invisible; progressDialog.Dismiss(); AlertMessage(StringResource.msgDashboardNotLoad); } else { progressDialog.Dismiss(); if (dtoMoveData.IsActive == "1") { relativeLayoutParentDashbord.Visibility = ViewStates.Invisible; AlertMessage(dtoMoveData.message); } else { if (!string.IsNullOrEmpty(dtoMoveData.StatusReason)) { if (dtoMoveData.StatusReason == "Invoiced" || dtoMoveData.StatusReason == "Booked" ) { PopulateChartBookAndInvoicedOrDelivered(dtoMoveData.StatusReason); } else { PopulateCharttPackedAndLoadedOrInTransit(dtoMoveData.StatusReason); } } else { relativeLayoutPieChart.Visibility = ViewStates.Invisible; } SetAdapter(dtoMoveData); SetDataToControl(dtoMoveData); } } } /// Method Name : SetDataToControl /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for move data set to control /// Revision : /// </summary> private void SetDataToControl(MoveDataModel dtoMoveData) { relativeLayoutParentDashbord.Visibility = ViewStates.Visible; tvFromCity.Text = dtoMoveData.Origin_City; tvToCity.Text = dtoMoveData.Destination_City; tvFromAddress.Text = dtoMoveData.CustomOriginAddress; tvToAddress.Text = dtoMoveData.CustomDestinationAddress; tvLeftDays.Text = dtoMoveData.daysLeft; tvStartDate.Text = dtoMoveData.MoveStartDate; tvEndDate.Text = dtoMoveData.MoveEndDate; if (string.IsNullOrEmpty(dtoMoveData.daysLeft)) { lnLeftDays.Visibility = ViewStates.Gone; } else { lnLeftDays.Visibility = ViewStates.Visible; tvLeftDays.Text = dtoMoveData.daysLeft; } if (!string.IsNullOrEmpty(dtoMoveData.CustomOriginAddress) && dtoMoveData.CustomOriginAddress.Length > 25) { tvFromAddress.Text = dtoMoveData.CustomOriginAddress.Substring(0, 25); } else { tvFromAddress.Text = dtoMoveData.CustomOriginAddress; } if (!string.IsNullOrEmpty(dtoMoveData.CustomDestinationAddress) && dtoMoveData.CustomDestinationAddress.Length > 25) { tvToAddress.Text = dtoMoveData.CustomDestinationAddress.Substring(0, 25); } else { tvToAddress.Text = dtoMoveData.CustomDestinationAddress; } } /// <summary> /// Method Name : AlertMessage /// Author : Sanket Prajapati /// Creation Date : 24 jan 2018 /// Purpose : Show alert message /// Revision : /// </summary> public void AlertMessage(String StrErrorMessage) { AlertDialog.Builder dialogue; AlertDialog alert; dialogue = new Android.App.AlertDialog.Builder(new ContextThemeWrapper(Activity, Resource.Style.AlertDialogCustom)); alert = dialogue.Create(); alert.SetMessage(StrErrorMessage); alert.SetButton(StringResource.msgOK, (c, ev) => { alert.Dispose(); }); alert.Show(); } /// Method Name : SetAdapter /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for Binding recylerView /// Revision : /// </summary> private void SetAdapter(MoveDataModel moveData) { List<ModelloadData> modelloadDataList = SetDataToCardview(moveData); if (modelloadDataList.Count > 0) { AdapterDashboard adapterDashboard = new AdapterDashboard(Activity, modelloadDataList); recylerViewDashboard.SetLayoutManager(new LinearLayoutManager(Activity)); recylerViewDashboard.SetItemAnimator(new DefaultItemAnimator()); recylerViewDashboard.NestedScrollingEnabled = false; recylerViewDashboard.HasFixedSize = false; recylerViewDashboard.SetAdapter(adapterDashboard); ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(adapterDashboard); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback); itemTouchHelper.AttachToRecyclerView(recylerViewDashboard); } } /// Method Name : SetDataToCardview /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for Binding data to card view (Myservices,valution, Whatmatermost) /// Revision : /// </summary> private List<ModelloadData> SetDataToCardview(MoveDataModel moveData) { List<ModelloadData> mModelloadDataList = new List<ModelloadData>(); //Set myservice data List<ModelloadData> mModelDummyDataServiceList = new List<ModelloadData>(); foreach (MyServicesModel myServicesmodal in moveData.MyServices) { mModelDummyDataServiceList.Add(new ModelloadData(myServicesmodal.ServicesCode, "")); } //Set valution data List<ModelloadData> mModelloadDataValuationList = new List<ModelloadData>(); mModelloadDataValuationList.Add(new ModelloadData(0, StringResource.msgDeclaredValue, moveData.ExcessValuation)); mModelloadDataValuationList.Add(new ModelloadData(1, StringResource.msgCoverage, moveData.ValuationDeductible)); mModelloadDataValuationList.Add(new ModelloadData(2, StringResource.msgCost, moveData.ValuationCost)); //Set fill cardview mModelloadDataList.Add(new ModelloadData(0, StringResource.msgMyServices, mModelDummyDataServiceList)); mModelloadDataList.Add(new ModelloadData(1, StringResource.msgWhatMattersMost, new ModelloadData(moveData.WhatMattersMost, ""))); mModelloadDataList.Add(new ModelloadData(2, StringResource.msgValuation, mModelloadDataValuationList)); return mModelloadDataList; } /// Method Name : PopulateChart /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for populate chart data /// Revision : /// </summary> private void PopulateCharttPackedAndLoadedOrInTransit(string strStatusCode) { PieSeries seriesP1; PieSeries seriesP2; PlotView plotView = view.FindViewById<PlotView>(Resource.Id.plotView1); var modelP1 = new PlotModel { Title = "" }; seriesP1 = new PieSeries { AngleSpan = 320, StartAngle = -250, InnerDiameter = 0.93, OutsideLabelFormat = "", LegendFormat = null }; seriesP2 = new PieSeries { AngleSpan = 320, StartAngle = -250, InnerDiameter = 0.6, Diameter = 0.93, OutsideLabelFormat = "", AreInsideLabelsAngled = false }; SetStatusWaysChartPackedAndLoadedOrInTransit(strStatusCode, seriesP1, seriesP2); RemovChartBorder(seriesP1, seriesP2); modelP1.Series.Add(seriesP1); modelP1.Series.Add(seriesP2); plotView.Model = modelP1; } /// Method Name : SetStatusWaysChart /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for set chart status ways /// Revision : /// </summary> private void SetStatusWaysChartPackedAndLoadedOrInTransit(string strStatusCode, PieSeries seriesP1, PieSeries seriesP2) { switch (strStatusCode) { //Booked Packed Loaded InTransit Delivered Invoiced case "Packed": imgViewStatus.SetImageResource(Resource.Drawable.icon_box); imgViewInnerChartStatus.SetImageResource(Resource.Drawable.icon_get_prepared); tvStatus.Text = "Packed"; ChartPacked(seriesP1, seriesP2); break; case "Loaded": imgViewStatus.SetImageResource(Resource.Drawable.icon_box); imgViewInnerChartStatus.SetImageResource(Resource.Drawable.icon_get_prepared); tvStatus.Text = "Loaded"; ChartLoaded(seriesP1, seriesP2); break; case "InTransit": imgViewStatus.SetImageResource(Resource.Drawable.TruckTest120); imgViewInnerChartStatus.SetImageResource(Resource.Drawable.Onrout); tvStatus.Text = "InTransit"; tvStatus.TranslationX = -10; ChartTransit(seriesP1, seriesP2); break; case "Delivered": imgViewStatus.SetImageResource(Resource.Drawable.icon_Move_Confirm_chart); imgViewInnerChartStatus.SetImageResource(Resource.Drawable.Onrout); tvStatus.Text = "Delivered"; tvStatus.TranslationX = -10; ChartDeliveredAndInvoice(seriesP1, seriesP2); break; } } /// Method Name : PopulateChart /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for populate chart data /// Revision : /// </summary> private void PopulateChartBookAndInvoicedOrDelivered(string StatusReason) { PieSeries seriesP1; PieSeries seriesP2; PlotView plotView = view.FindViewById<PlotView>(Resource.Id.plotView1); var modelP1 = new PlotModel { Title = "" }; seriesP1 = new PieSeries { AngleSpan = 340, StartAngle = -260, InnerDiameter = 0.93, OutsideLabelFormat = "", LegendFormat = null }; seriesP2 = new PieSeries { AngleSpan = 340, StartAngle = -260, InnerDiameter = 0.6, Diameter = 0.93, OutsideLabelFormat = "", AreInsideLabelsAngled = false }; tvStatus.Text = StatusReason; SetStatusBookAndInvoiceChart(StatusReason, seriesP1, seriesP2); RemovChartBorder(seriesP1, seriesP2); modelP1.Series.Add(seriesP1); modelP1.Series.Add(seriesP2); plotView.Model = modelP1; } /// Method Name : SetStatusWaysChart /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for set chart status ways /// Revision : /// </summary> private void SetStatusBookAndInvoiceChart(string strStatusCode, PieSeries seriesP1, PieSeries seriesP2) { switch (strStatusCode) { //Booked Packed Loaded InTransit Delivered Invoiced case "Booked": imgViewStatus.SetImageResource(Resource.Drawable.icon_invoice_chart); imgViewInnerChartStatus.SetImageResource(Resource.Drawable.icon_move_confirmed); tvStatus.Text = "Booked"; imgViewInnerChartStatus.TranslationX = 15; imgViewStatus.TranslationX = 2; ChartBooked(seriesP1, seriesP2); break; case "Invoiced": imgViewStatus.SetImageResource(Resource.Drawable.icon_invoice_chart); imgViewInnerChartStatus.SetImageResource(Resource.Drawable.icon_move_confirmed); imgViewInnerChartStatus.TranslationX = 15; tvStatus.Text = "Invoiced"; tvStatus.TranslationX = -5; ChartDeliveredAndInvoice(seriesP1, seriesP2); break; } } /// Method Name : RemovChartBorder /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for remove chart border /// Revision : /// </summary> private void RemovChartBorder(PieSeries seriesP1, PieSeries seriesP2) { seriesP1.OutsideLabelFormat = ""; seriesP1.TickHorizontalLength = 0; seriesP1.TickRadialLength = 0.0; seriesP1.StrokeThickness = 0.0; seriesP2.StrokeThickness = 0.0; seriesP1.TickDistance = 0; seriesP1.Stroke = OxyColors.Transparent; seriesP2.Stroke = OxyColors.Transparent; seriesP2.OutsideLabelFormat = ""; seriesP2.TickHorizontalLength = 0; seriesP2.TickRadialLength = 0; } /// Method Name : ChartLoad /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for binding chart status Load /// Revision : /// </summary> //1 Book public void ChartBooked(PieSeries seriesP1, PieSeries seriesP2) { //outer seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(236, 61, 98) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(50, 212, 212) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(202, 206, 221) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(252, 238, 233) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(225, 249, 255) }); //inner seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(232, 144, 165) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = true, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = true, Fill = OxyColor.FromRgb(227, 227, 233) }); } /// Method Name : ChartPacked /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for binding chart status Packed /// Revision : /// </summary> //2 Packed public void ChartPacked(PieSeries seriesP1, PieSeries seriesP2) { //outer seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(236, 61, 98) }); seriesP1.Slices.Add(new PieSlice("", 60) { Fill = OxyColor.FromRgb(50, 212, 212) }); seriesP1.Slices.Add(new PieSlice("", 40) { Fill = OxyColor.FromRgb(138, 219, 222) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(202, 206, 221) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(252, 238, 233) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(225, 249, 255) }); //inner seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(232, 144, 165) }); seriesP2.Slices.Add(new PieSlice("", 60) { IsExploded = false, Fill = OxyColor.FromRgb(201, 225, 233) }); seriesP2.Slices.Add(new PieSlice("", 40) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = true, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = true, Fill = OxyColor.FromRgb(227, 227, 233) }); } /// Method Name : ChartTransit /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for binding chart status Transit /// Revision : /// </summary> //3 Loaded public void ChartLoaded(PieSeries seriesP1, PieSeries seriesP2) { //outer seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(236, 61, 98) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(50, 212, 212) }); seriesP1.Slices.Add(new PieSlice("", 60) { Fill = OxyColor.FromRgb(22, 51, 99) }); seriesP1.Slices.Add(new PieSlice("", 40) { Fill = OxyColor.FromRgb(202, 206, 221) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(248, 221, 211) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(225, 249, 255) }); //inner seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(232, 144, 165) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(138, 219, 222) }); seriesP2.Slices.Add(new PieSlice("", 60) { IsExploded = false, Fill = OxyColor.FromRgb(124, 139, 166) }); seriesP2.Slices.Add(new PieSlice("", 40) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = true, Fill = OxyColor.FromRgb(227, 227, 233) }); } /// Method Name : ChartInvoiced /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for binding chart status Invoiced /// Revision : /// </summary> //4 InTransit public void ChartTransit(PieSeries seriesP1, PieSeries seriesP2) { //outer seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(236, 61, 98) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(50, 212, 212) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(22, 51, 99) }); seriesP1.Slices.Add(new PieSlice("", 60) { Fill = OxyColor.FromRgb(242, 130, 116) }); seriesP1.Slices.Add(new PieSlice("", 40) { Fill = OxyColor.FromRgb(248, 221, 211) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(225, 249, 255) }); //inner seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(232, 144, 165) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(138, 219, 222) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(124, 139, 166) }); seriesP2.Slices.Add(new PieSlice("", 60) { IsExploded = false, Fill = OxyColor.FromRgb(252, 238, 233) }); seriesP2.Slices.Add(new PieSlice("", 40) { IsExploded = false, Fill = OxyColor.FromRgb(227, 227, 233) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = true, Fill = OxyColor.FromRgb(227, 227, 233) }); } /// Method Name : ChartInvoiced /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for binding chart status Delivered /// Revision : /// </summary> //5 public void ChartDeliveredAndInvoice(PieSeries seriesP1, PieSeries seriesP2) { //outer seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(236, 61, 98) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(50, 212, 212) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(22, 51, 99) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(242, 130, 116) }); seriesP1.Slices.Add(new PieSlice("", 100) { Fill = OxyColor.FromRgb(9, 205, 255) }); //inner seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(232, 144, 165) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(138, 219, 222) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(124, 139, 166) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(241, 190, 171) }); seriesP2.Slices.Add(new PieSlice("", 100) { IsExploded = false, Fill = OxyColor.FromRgb(195, 219, 233) }); } /// Method Name : GetloadDataList /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for Get loadDataList /// Revision : /// </summary> public static List<ModelloadData> GetloadDataList() { var list = new List<ModelloadData>(); list.Add(new ModelloadData(StringResource.msgMyServices, "subtitle")); list.Add(new ModelloadData(StringResource.msgWhatMattersMost, "subtitle")); list.Add(new ModelloadData(StringResource.msgValuation, "subtitle")); return list; } /// class Name : ModelloadData /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for Card view bind /// Revision : /// </summary> public class ModelloadData { public ModelloadData(string title, string subtitle) { this.title = title; this.subTitle = subtitle; } public ModelloadData(int id, string title, string value) { this.id = id; this.title = title; this.value = value; } public ModelloadData(int id, string title, Object mObject) { this.id = id; this.title = title; this.mObject = mObject; } public string title { get; set; } public string subTitle { get; set; } public int id { get; set; } public string value { get; set; } public Object mObject { get; set; } } /// class Name : ItemTouchHelperCallback /// Author : Sanket Prajapati /// Creation Date : 23 Jan 2018 /// Purpose : Use for Card view swaping /// Revision : /// </summary> public class ItemTouchHelperCallback : ItemTouchHelper.Callback { private readonly AdapterDashboard mAdapterDashboard; public ItemTouchHelperCallback(AdapterDashboard adapterDashboard) { mAdapterDashboard = adapterDashboard; } public override bool IsItemViewSwipeEnabled => false; public override bool IsLongPressDragEnabled => true; public override int GetMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { int dragFlags = ItemTouchHelper.Up | ItemTouchHelper.Down; int swipeFlags = ItemTouchHelper.Left | ItemTouchHelper.Right; return MakeMovementFlags(dragFlags, swipeFlags); } public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { mAdapterDashboard.OnItemMove(viewHolder.AdapterPosition, target.AdapterPosition); return true; } public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction) { //Does not require implementation. Used to override / remove existing functionality of android. } } /// <summary> /// Method Name : ApplyFont /// Author : Sanket Prajapati /// Creation Date : 4 jan 2017 /// Purpose : Apply font all control /// Revision : /// </summary> public void ApplyFont() { UIHelper.SetTextViewFont(tvFromCity, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvToCity, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); UIHelper.SetTextViewFont(tvFromAddress, (int)UIHelper.LinotteFont.LinotteRegular, Activity.Assets); UIHelper.SetTextViewFont(tvToAddress, (int)UIHelper.LinotteFont.LinotteRegular, Activity.Assets); UIHelper.SetTextViewFont(tvStartDate, (int)UIHelper.LinotteFont.LinotteRegular, Activity.Assets); UIHelper.SetTextViewFont(tvEndDate, (int)UIHelper.LinotteFont.LinotteRegular, Activity.Assets); UIHelper.SetTextViewFont(tvLeftDays, (int)UIHelper.LinotteFont.LinotteSemiBold, Activity.Assets); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ScoreController : MonoBehaviour { [SerializeField] Text scoreValue; private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "Player") { AddScore(50); Destroy(gameObject); } } public void AddScore(int score) { int scoreValueInt = int.Parse(scoreValue.text); scoreValueInt += score; scoreValue.text = scoreValueInt.ToString(); } // Update is called once per frame void Update() { transform.Rotate(new Vector3(0f,2f,0f)); } }
// Copyright 2021 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. using NtApiDotNet.Ndr.Marshal; using NtApiDotNet.Win32.Net; using System; using System.Net; using System.Net.Sockets; namespace NtApiDotNet.Win32.Rpc.Transport { /// <summary> /// RPC client transport over TCP/IP; /// </summary> public sealed class RpcTcpClientTransport : RpcStreamSocketClientTransport { #region Private Members private const ushort MaxXmitFrag = 5840; private const ushort MaxRecvFrag = 5840; private static Socket CreateSocket(string hostname, int port) { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); socket.DualMode = true; // Enable no delay. socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); socket.Connect(hostname, port); return socket; } /// <summary> /// Get the server process information. /// </summary> /// <returns>The server process information.</returns> private RpcServerProcessInformation GetServerProcess() { if (!Connected) throw new InvalidOperationException("TCP/IP transport is not connected."); IPEndPoint endpoint = (IPEndPoint)_socket.RemoteEndPoint; IPAddress address = endpoint.Address; if (address.IsIPv4MappedToIPv6) { address = address.MapToIPv4(); } if (!IPAddress.IsLoopback(address)) { throw new ArgumentException("Can't get server process on a remote system."); } var listener_info = Win32NetworkUtils.GetListenerForTcpPort(address.AddressFamily, endpoint.Port); if (listener_info == null) throw new ArgumentException("Can't find local listener for port."); return new RpcServerProcessInformation(listener_info.ProcessId, 0); } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="hostname">The hostname to connect to.</param> /// <param name="port">The TCP port to connect to.</param> /// <param name="transport_security">The transport security for the connection.</param> public RpcTcpClientTransport(string hostname, int port, RpcTransportSecurity transport_security) : base(CreateSocket(hostname, port), MaxRecvFrag, MaxXmitFrag, new NdrDataRepresentation(), transport_security) { } #endregion #region Public Properties /// <summary> /// Get the transport protocol sequence. /// </summary> public override string ProtocolSequence => "ncacn_ip_tcp"; /// <summary> /// Get information about the local server process, if known. /// </summary> public override RpcServerProcessInformation ServerProcess => GetServerProcess(); #endregion } }
using NTier.Model.Model.Entities; using NTier.Service.Service.Base; using System.Collections.Generic; using System.Linq; using NTier.Core.Core.Entity.Enum; namespace NTier.Service.Service.Option { public class OrderService:BaseService<Order> { public int PendingOrderCount() => GetDefault(x => x.isConfirmed == false && (x.Status == Status.Active || x.Status == Status.Updated)).Count; public List<Order> ListPendingOrders() => GetDefault(x => x.isConfirmed == false && (x.Status == Status.Active || x.Status == Status.Updated)).OrderByDescending(x=>x.CreatedDate).ToList(); } }
using System; public class Program { public static void Main() { var a = double.Parse(Console.ReadLine()); var b = double.Parse(Console.ReadLine()); var compare = Math.Abs(a - b) < 0.000001; Console.WriteLine(compare); } }
using UnityEngine; using System.Collections; using System; using System.IO; public class MapImporter : MonoBehaviour { public LevelMakerManager LevelMakermgr; public Camera UICamera; public TextMesh text; public Transform GUIPos; public GameObject CollsPanel; public Collider2D ScrollBox; private bool Open; private bool init; private Vector2 scrollPosition; private Vector2 scrollMax; private DirectoryInfo dI; // Use this for initialization void Start() { //LevelMaker/Save 경로 에 접근 dI = null; dI = new DirectoryInfo(Application.persistentDataPath + "/LevelMaker/Save"); text.text = ""; #region Exists //만약 해당 경로가 존재하지 않으면 if (!dI.Exists) { //생성 및 접근 dI = new DirectoryInfo(Application.persistentDataPath); dI = dI.CreateSubdirectory("LevelMaker/Save"); //해당 경로에 기본 Map파일 복사 TextAsset[] bindata = Resources.LoadAll<TextAsset>("LevelMaker/Save"); foreach (TextAsset mapfile in bindata) { FileInfo file = new FileInfo(dI.FullName + "/" + mapfile.name + ".gkmap"); FileStream fs = file.Create(); BinaryWriter bw = new BinaryWriter(fs, System.Text.Encoding.UTF8); bw.Write(mapfile.bytes); bw.Close(); fs.Close(); } } #endregion Open = false; scrollPosition = new Vector2(); scrollMax = new Vector2(); CollsPanel.SetActive(Open); init = true; } public void OpenLoader() { Open = true; CollsPanel.SetActive(Open); } public void CloseLoader() { Open = false; CollsPanel.SetActive(Open); } public void SaveFile(string filename, string script) { string scr = dI.FullName + "/" + filename; FileInfo file = new FileInfo(scr + ".gkmap"); while (file.Exists) { scr += "_NEW"; file = new FileInfo(scr + ".gkmap"); } FileStream fs = file.Create(); StreamWriter sw = new StreamWriter(fs); sw.Write(script); sw.Close(); fs.Close(); } public Rect WorldToGuiRect(float x, float y, float width, float height, float Anchorx = 0.5f, float Anchory = 0.5f) { return WorldToGuiRect(new Rect(x, y, width, height), new Vector2(Anchorx, Anchory)); } public Rect WorldToGuiRect(Rect rect, Vector2 AnchorPoint) { rect.x += GUIPos.localPosition.x - (AnchorPoint.x * rect.width); rect.y += UICamera.transform.position.y + (rect.height - (AnchorPoint.y * rect.height)) + GUIPos.localPosition.y; Vector2 guiPosition = UICamera.WorldToScreenPoint(rect.position); Vector2 guiSize = UICamera.WorldToScreenPoint(rect.position + rect.size); guiSize = guiSize - guiPosition; guiPosition.y = Screen.height - guiPosition.y; return new Rect(guiPosition.x, guiPosition.y, guiSize.x, guiSize.y); } void LateUpdate() { if (!Open) return; if (scrollPosition.y < 0) scrollPosition.y = 0; if (scrollPosition.y != scrollMax.y) scrollPosition.y = scrollMax.y; } void OnGUI() { if (!Open || !init) return; int h = Screen.height; GUI.skin.box.fontSize = (int)(0.04f * h); GUI.skin.button.fontSize = (int)(0.04f * h); GUI.skin.verticalScrollbar.fixedWidth = (int)(0.07f * h); GUI.skin.verticalScrollbarThumb.fixedWidth = (int)(0.07f * h); GUI.Box(WorldToGuiRect(0, 0, 16, 8.5f), "LOAD MAP"); if (GUI.Button(WorldToGuiRect(0, 3.0f, 15, 0.8f), "종료")) CloseLoader(); GUILayout.BeginArea(WorldToGuiRect(0, -0.5f, 15, 5.5f)); scrollMax = GUILayout.BeginScrollView(scrollPosition); foreach (FileInfo item in dI.GetFiles()) { if (item.Extension == ".gkmap") { if (GUILayout.Button(new GUIContent(item.Name))) { StreamReader stream = item.OpenText(); string str = stream.ReadToEnd(); stream.Close(); LevelMakermgr.Callback_Loader_Load(str); } } } GUILayout.EndScrollView(); GUILayout.EndArea(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FinalProject.Backend { public class Oferta { public int IdOferta { get; set; } public String NoControl { get; set; } public int IdMateria { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SQLite; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Printing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Ovan_P1 { public partial class CategoryList : Form { int height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height; int width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width; Form1 mainFormGlobal = null; Panel mainPanelGlobal = null; //private Button buttonGlobal = null; private FlowLayoutPanel[] menuFlowLayoutPanelGlobal = new FlowLayoutPanel[4]; Constant constants = new Constant(); CreatePanel createPanel = new CreatePanel(); CreateLabel createLabel = new CreateLabel(); CreateCombobox createCombobox = new CreateCombobox(); CustomButton customButton = new CustomButton(); DropDownMenu dropDownMenu = new DropDownMenu(); MessageDialog messageDialog = new MessageDialog(); Panel detailPanelGlobal = null; Panel tBodyPanelGlobal = null; DetailView detailView = new DetailView(); PaperSize paperSize = new PaperSize("papersize", 500, 800);//set the paper size PrintDocument printDocument1 = new PrintDocument(); PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog(); PrintDialog printDialog1 = new PrintDialog(); int totalNumber = 0; string storeName = ""; List<int> soldoutCategoryIndex = new List<int>(); string[] categoryNameList = null; int[] categoryIDList = null; int[] categoryDisplayPositionList = null; int[] categorySoldStateList = null; int[] categoryLayoutList = null; string[] categoryBackImageList = null; string[] categoryOpenTimeList = null; List<int> stopedPrdIDArray = null; int categoryRowCount = 0; int selectedCategoryIndex = 0; SQLiteConnection sqlite_conn; DateTime now = DateTime.Now; public CategoryList(Form1 mainForm, Panel mainPanel) { InitializeComponent(); dropDownMenu.initCategoryList(this); messageDialog.initCategoryList(this); mainFormGlobal = mainForm; mainPanelGlobal = mainPanel; sqlite_conn = CreateConnection(constants.dbName); this.GetCategoryList(); if (sqlite_conn.State == ConnectionState.Closed) { sqlite_conn.Open(); } SQLiteCommand sqlite_cmd; string week = now.ToString("ddd"); string currentTime = now.ToString("HH:mm"); try { string productQuery = "SELECT count(*) FROM " + constants.tbNames[0] + ""; sqlite_cmd = sqlite_conn.CreateCommand(); sqlite_cmd.CommandText = productQuery; totalNumber = Convert.ToInt32(sqlite_cmd.ExecuteScalar()); } catch (Exception ex) { Console.WriteLine(ex); } try { string productQuery1 = "SELECT count(*) FROM " + constants.tbNames[2] + ""; sqlite_cmd = sqlite_conn.CreateCommand(); sqlite_cmd.CommandText = productQuery1; totalNumber += Convert.ToInt32(sqlite_cmd.ExecuteScalar()); } catch (Exception ex) { Console.WriteLine(ex); } SQLiteDataReader sqlite_datareader; string storeEndqurey = "SELECT * FROM " + constants.tbNames[6]; sqlite_cmd = sqlite_conn.CreateCommand(); sqlite_cmd.CommandText = storeEndqurey; sqlite_datareader = sqlite_cmd.ExecuteReader(); while (sqlite_datareader.Read()) { if (!sqlite_datareader.IsDBNull(0)) { storeName = sqlite_datareader.GetString(1); } } Panel mainPanels = createPanel.CreateSubPanel(mainPanel, 0, 0, mainPanel.Width, mainPanel.Height, BorderStyle.None, Color.Transparent); mainPanelGlobal = mainPanels; Label categoryLabel = createLabel.CreateLabelsInPanel(mainPanels, "categoryLabel", constants.categoryListTitleLabel, 50, 50, mainPanels.Width / 3, 50, Color.Transparent, Color.Black, 22, false, ContentAlignment.MiddleLeft); dropDownMenu.CreateCategoryDropDown1("categoryList", mainPanels, categoryNameList, categoryIDList, categoryDisplayPositionList, categorySoldStateList, mainPanels.Width / 3 + 50, 50, mainPanels.Width / 3, 50, mainPanels.Width / 3, 50 * (categoryRowCount + 1), mainPanels.Width / 3, 50, Color.Red, Color.White); Label categoryTimeLabel = createLabel.CreateLabelsInPanel(mainPanels, "categoryTimeLabel", constants.TimeLabel + " : ", 50, 130, mainPanels.Width / 6, 50, Color.Transparent, Color.Black, 22, false, ContentAlignment.BottomLeft); Button previewButton = customButton.CreateButtonWithImage(Image.FromFile(constants.rectGreenButton), "previewButton", constants.prevButtonLabel, mainPanelGlobal.Width - 200, mainPanels.Height * 3 / 5 + 30, 150, 50, 0, 1, 18, FontStyle.Bold, Color.White, ContentAlignment.MiddleCenter, 2); mainPanels.Controls.Add(previewButton); previewButton.Click += new EventHandler(this.PreviewSalePage); Button printButton = customButton.CreateButtonWithImage(Image.FromFile(constants.rectLightBlueButton), "categoryPrintButton", constants.printButtonLabel, mainPanelGlobal.Width - 200, mainPanels.Height * 3 / 5 + 110, 150, 50, 0, 1, 18, FontStyle.Bold, Color.White, ContentAlignment.MiddleCenter, 2); mainPanels.Controls.Add(printButton); printButton.Click += new EventHandler(messageDialog.MessageDialogInit); Button closeButton = customButton.CreateButtonWithImage(Image.FromFile(constants.rectBlueButton), "closeButton", constants.backText, mainPanelGlobal.Width - 200, mainPanels.Height * 3 / 5 + 190, 150, 50, 0, 1, 18, FontStyle.Bold, Color.White, ContentAlignment.MiddleCenter, 2); mainPanels.Controls.Add(closeButton); closeButton.Click += new EventHandler(this.BackShow); Panel detailPanel = createPanel.CreateSubPanel(mainPanels, 50, 200, mainPanelGlobal.Width * 5 / 7, mainPanelGlobal.Height - 250, BorderStyle.None, Color.Transparent); detailPanelGlobal = detailPanel; detailPanel.Padding = new Padding(0); FlowLayoutPanel tableHeaderInUpPanel = createPanel.CreateFlowLayoutPanel(detailPanel, 0, 0, detailPanel.Width, 50, Color.Transparent, new Padding(0)); tableHeaderInUpPanel.Margin = new Padding(0); Label tableHeaderLabel1 = createLabel.CreateLabels(tableHeaderInUpPanel, "tableHeaderLabel1", constants.printProductNameField, 0, 0, tableHeaderInUpPanel.Width / 2, 50, Color.FromArgb(255, 147, 184, 219), Color.Black, 16, true, ContentAlignment.MiddleCenter, new Padding(0), 1, Color.Gray); tableHeaderLabel1.Paint += new PaintEventHandler(this.set_background); Label tableHeaderLabel2 = createLabel.CreateLabels(tableHeaderInUpPanel, "tableHeaderLabel2", constants.salePriceField, tableHeaderLabel1.Right, 0, tableHeaderInUpPanel.Width / 4, 50, Color.FromArgb(255, 147, 184, 219), Color.Black, 16, true, ContentAlignment.MiddleCenter, new Padding(0), 1, Color.Gray); tableHeaderLabel2.Paint += new PaintEventHandler(this.set_background); Label tableHeaderLabel3 = createLabel.CreateLabels(tableHeaderInUpPanel, "tableHeaderLabel3", constants.saleLimitField, tableHeaderLabel2.Right, 0, tableHeaderInUpPanel.Width / 4, 50, Color.FromArgb(255, 147, 184, 219), Color.Black, 16, true, ContentAlignment.MiddleCenter, new Padding(0), 1, Color.Gray); tableHeaderLabel3.Paint += new PaintEventHandler(this.set_background); Panel tBodyPanel = createPanel.CreateSubPanel(detailPanel, 0, 50, detailPanel.Width, detailPanel.Height - 50, BorderStyle.None, Color.Transparent); tBodyPanelGlobal = tBodyPanel; tBodyPanel.Padding = new Padding(0); printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage); printDocument1.EndPrint += new PrintEventHandler(PrintEnd); ShowCategoryDetail(); } private void PrintEnd(object sender, PrintEventArgs e) { //lineNum = -1; //groupNumber = 0; //itemperpage = 0; //lineNums = -1; //groupNumbers = 0; //itemperpages = 0; } private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { PrintDocument printDocument = (PrintDocument)sender; float currentY = 0; RectangleF rect1 = new RectangleF(5, currentY, constants.categorylistPrintPaperWidth, 25); StringFormat format1 = new StringFormat(); format1.Alignment = StringAlignment.Center; e.Graphics.DrawString(constants.categoryListPrintTitle, new Font("Seri", constants.fontSizeBig, FontStyle.Bold), Brushes.Red, rect1, format1); currentY += 25; RectangleF rect2 = new RectangleF(5, currentY, constants.categorylistPrintPaperWidth, 25); StringFormat format2 = new StringFormat(); format2.Alignment = StringAlignment.Center; e.Graphics.DrawString(now.ToString("yyyy/MM/dd HH:mm:ss"), new Font("Seri", constants.fontSizeMedium, FontStyle.Bold), Brushes.Red, rect2, format2); currentY += 25; RectangleF rect3 = new RectangleF(5, currentY, constants.categorylistPrintPaperWidth, 25); StringFormat format3 = new StringFormat(); format3.Alignment = StringAlignment.Center; e.Graphics.DrawString(storeName, new Font("Seri", constants.fontSizeMedium, FontStyle.Bold), Brushes.Red, rect3, format3); currentY += 25; int k = 0; foreach (string categoryName in categoryNameList) { RectangleF rect4 = new RectangleF(5, currentY + 5, constants.categorylistPrintPaperWidth, 25); StringFormat format4 = new StringFormat(); format4.Alignment = StringAlignment.Near; e.Graphics.DrawString(constants.categoryDiplayLabel + categoryDisplayPositionList[k] + "/" + constants.categoryLabel + categoryIDList[k] + " " + categoryName, new Font("Seri", constants.fontSizeMedium, FontStyle.Bold), Brushes.Blue, rect4, format4); currentY += 25; RectangleF rect5 = new RectangleF(5, currentY, constants.categorylistPrintPaperWidth, 25); StringFormat format5 = new StringFormat(); format5.Alignment = StringAlignment.Near; e.Graphics.DrawString(constants.SaleTimeLabel + ": " + categoryOpenTimeList[k], new Font("Seri", constants.fontSizeSmall, FontStyle.Regular), Brushes.Blue, rect5, format5); currentY += 25; SQLiteDataReader sqlite_datareader; SQLiteCommand sqlite_cmd; sqlite_cmd = sqlite_conn.CreateCommand(); string queryCmd0 = "SELECT * FROM " + constants.tbNames[2] + " WHERE CategoryID=@categoryID ORDER BY CardNumber"; sqlite_cmd.CommandText = queryCmd0; sqlite_cmd.Parameters.AddWithValue("@categoryID", categoryIDList[k]); sqlite_datareader = sqlite_cmd.ExecuteReader(); int m = 0; while (sqlite_datareader.Read()) { if (!sqlite_datareader.IsDBNull(0)) { string prdName = sqlite_datareader.GetString(3); int prdPrice = sqlite_datareader.GetInt32(8); int prdLimitedCnt = sqlite_datareader.GetInt32(9); int prdID = sqlite_datareader.GetInt32(2); int rowID = sqlite_datareader.GetInt32(0); int soldFlag = sqlite_datareader.GetInt32(31); int saleAmount = 0; int restAmount = 0; SQLiteCommand sqlite_cmd1; SQLiteDataReader sqlite_datareader1; string productQuery1 = "SELECT sum(prdAmount) FROM " + constants.tbNames[3] + " WHERE prdID=@prdID and sumFlag='false'"; sqlite_cmd1 = sqlite_conn.CreateCommand(); sqlite_cmd1.CommandText = productQuery1; sqlite_cmd1.Parameters.AddWithValue("@prdID", prdID); sqlite_datareader1 = sqlite_cmd1.ExecuteReader(); while (sqlite_datareader1.Read()) { if (!sqlite_datareader1.IsDBNull(0)) { saleAmount = sqlite_datareader1.GetInt32(0); } } if (prdLimitedCnt != 0 && prdLimitedCnt >= saleAmount) { restAmount = prdLimitedCnt - saleAmount; } string saleStatus = "0"; Color fontColor = Color.Black; if (soldFlag == 0) { if (prdLimitedCnt != 0) { saleStatus = restAmount.ToString() + "/" + prdLimitedCnt.ToString(); } } else { saleStatus = constants.saleStopStatusText; fontColor = Color.Red; } RectangleF rect6 = new RectangleF(5, currentY, constants.categorylistPrintPaperWidth * 3 / 5, 20); StringFormat format6 = new StringFormat(); format6.Alignment = StringAlignment.Near; e.Graphics.DrawString(prdName, new Font("Seri", constants.fontSizeSmall, FontStyle.Regular), Brushes.Blue, rect6, format6); RectangleF rect7 = new RectangleF(5 + constants.categorylistPrintPaperWidth * 3 / 5, currentY, constants.categorylistPrintPaperWidth / 5 - 5, 20); StringFormat format7 = new StringFormat(); format7.Alignment = StringAlignment.Center; e.Graphics.DrawString(prdPrice.ToString(), new Font("Seri", constants.fontSizeSmall, FontStyle.Regular), Brushes.Blue, rect7, format7); RectangleF rect8 = new RectangleF(constants.categorylistPrintPaperWidth * 4 / 5, currentY, constants.categorylistPrintPaperWidth / 5, 20); StringFormat format8 = new StringFormat(); format8.Alignment = StringAlignment.Far; e.Graphics.DrawString(saleStatus, new Font("Seri", constants.fontSizeSmall, FontStyle.Regular), Brushes.Blue, rect8, format8); currentY += 20; e.HasMorePages = false; // set the HasMorePages property to false , so that no other page will not be added m++; } } k++; } } private void ShowCategoryDetail() { if (sqlite_conn.State == ConnectionState.Closed) { sqlite_conn.Open(); } Label categoryTimeValue = createLabel.CreateLabelsInPanel(mainPanelGlobal, "categoryTimeValue", categoryOpenTimeList[selectedCategoryIndex], mainPanelGlobal.Width / 6 + 50, 130, mainPanelGlobal.Width / 2, 50, Color.Transparent, Color.Black, 22, false, ContentAlignment.BottomLeft); categoryTimeValue.Padding = new Padding(10, 0, 0, 0); tBodyPanelGlobal.HorizontalScroll.Maximum = 0; tBodyPanelGlobal.AutoScroll = false; tBodyPanelGlobal.VerticalScroll.Visible = false; tBodyPanelGlobal.AutoScroll = true; SQLiteDataReader sqlite_datareader; SQLiteCommand sqlite_cmd; sqlite_cmd = sqlite_conn.CreateCommand(); string queryCmd0 = "SELECT * FROM " + constants.tbNames[2] + " WHERE CategoryID=@categoryID ORDER BY CardNumber"; sqlite_cmd.CommandText = queryCmd0; sqlite_cmd.Parameters.AddWithValue("@categoryID", categoryIDList[selectedCategoryIndex]); sqlite_datareader = sqlite_cmd.ExecuteReader(); stopedPrdIDArray = new List<int>(); int k = 0; while (sqlite_datareader.Read()) { if (!sqlite_datareader.IsDBNull(0)) { string prdName = sqlite_datareader.GetString(3); int prdPrice = sqlite_datareader.GetInt32(8); int prdLimitedCnt = sqlite_datareader.GetInt32(9); int prdID = sqlite_datareader.GetInt32(2); int rowID = sqlite_datareader.GetInt32(0); int soldFlag = sqlite_datareader.GetInt32(31); int saleAmount = 0; int restAmount = 0; SQLiteCommand sqlite_cmd1; SQLiteDataReader sqlite_datareader1; string productQuery1 = "SELECT sum(prdAmount) FROM " + constants.tbNames[3] + " WHERE prdID=@prdID and sumFlag='false'"; sqlite_cmd1 = sqlite_conn.CreateCommand(); sqlite_cmd1.CommandText = productQuery1; sqlite_cmd1.Parameters.AddWithValue("@prdID", prdID); sqlite_datareader1 = sqlite_cmd1.ExecuteReader(); while (sqlite_datareader1.Read()) { if (!sqlite_datareader1.IsDBNull(0)) { saleAmount = sqlite_datareader1.GetInt32(0); } } if (prdLimitedCnt != 0 && prdLimitedCnt >= saleAmount) { restAmount = prdLimitedCnt - saleAmount; } string saleStatus = "0"; Color fontColor = Color.Black; if (soldFlag == 0) { if (prdLimitedCnt != 0) { saleStatus = restAmount.ToString() + "/" + prdLimitedCnt.ToString(); } } else { saleStatus = constants.saleStopStatusText; fontColor = Color.Red; } FlowLayoutPanel tableRowPanel = createPanel.CreateFlowLayoutPanel(tBodyPanelGlobal, 0, 50 * k, tBodyPanelGlobal.Width, 50, Color.Transparent, new Padding(0)); tableRowPanel.Margin = new Padding(0); Label tdLabel1 = createLabel.CreateLabels(tableRowPanel, "tdLabel1_" + k, prdName, 0, 0, tableRowPanel.Width / 2, 50, Color.White, fontColor, 16, true, ContentAlignment.MiddleCenter, new Padding(0), 1, Color.Gray); Label tdLabel2 = createLabel.CreateLabels(tableRowPanel, "tdLabel2_" + k, prdPrice.ToString(), tdLabel1.Right, 0, tableRowPanel.Width / 4, 50, Color.White, fontColor, 16, true, ContentAlignment.MiddleCenter, new Padding(0), 1, Color.Gray); Label tdLabel3 = createLabel.CreateLabels(tableRowPanel, "tdLabel3_" + k, saleStatus, tdLabel2.Right, 0, tableRowPanel.Width / 4, 50, Color.White, fontColor, 16, true, ContentAlignment.MiddleCenter, new Padding(0), 1, Color.Gray); k++; } } } public void setVal(string categoryID) { tBodyPanelGlobal.Controls.Clear(); selectedCategoryIndex = int.Parse(categoryID); ShowCategoryDetail(); } public void BackShow(object sender, EventArgs e) { mainPanelGlobal.Controls.Clear(); MaintaneceMenu frm = new MaintaneceMenu(mainFormGlobal, mainPanelGlobal); frm.TopLevel = false; mainPanelGlobal.Controls.Add(frm); frm.FormBorderStyle = FormBorderStyle.None; frm.Dock = DockStyle.Fill; Thread.Sleep(200); frm.Show(); } public void PreviewSalePage(object sender, EventArgs e) { mainFormGlobal.Controls.Clear(); PreviewSalePage frm = new PreviewSalePage(mainFormGlobal, mainPanelGlobal, selectedCategoryIndex, categoryIDList, categoryNameList, categoryDisplayPositionList, categoryLayoutList, categoryBackImageList); frm.TopLevel = false; mainFormGlobal.Controls.Add(frm); frm.FormBorderStyle = FormBorderStyle.None; frm.Dock = DockStyle.Fill; Thread.Sleep(200); frm.Show(); } public void PrintPreview_click() { //printPreviewDialog1.Document = printDocument1; printDialog1.Document = printDocument1; ((ToolStripButton)((ToolStrip)printPreviewDialog1.Controls[1]).Items[0]).Enabled = true; paperSize = new PaperSize("papersize", constants.categorylistPrintPaperWidth, constants.categorylistPrintPaperHeight); printDocument1.DefaultPageSettings.PaperSize = paperSize; printDocument1.DefaultPageSettings.Margins = new Margins(0, 0, 0, 15); printDocument1.Print(); //printPreviewDialog1.ShowDialog(); } private void GetCategoryList() { DateTime now = DateTime.Now; string week = now.ToString("ddd"); string currentTime = now.ToString("HH:mm"); if (sqlite_conn.State == ConnectionState.Closed) { sqlite_conn.Open(); } SQLiteDataReader sqlite_datareader; SQLiteCommand sqlite_cmd; sqlite_cmd = sqlite_conn.CreateCommand(); string queryCmd0 = "SELECT COUNT(id) FROM " + constants.tbNames[0]; sqlite_cmd.CommandText = queryCmd0; categoryRowCount = Convert.ToInt32(sqlite_cmd.ExecuteScalar()); categoryNameList = new string[categoryRowCount]; categoryIDList = new int[categoryRowCount]; categoryDisplayPositionList = new int[categoryRowCount]; categoryLayoutList = new int[categoryRowCount]; categorySoldStateList = new int[categoryRowCount]; categoryOpenTimeList = new string[categoryRowCount]; categoryBackImageList = new string[categoryRowCount]; string queryCmd = "SELECT * FROM " + constants.tbNames[0] + " ORDER BY id"; sqlite_cmd.CommandText = queryCmd; sqlite_datareader = sqlite_cmd.ExecuteReader(); int k = 0; while (sqlite_datareader.Read()) { if (!sqlite_datareader.IsDBNull(0)) { categoryIDList[k] = sqlite_datareader.GetInt32(1); categoryNameList[k] = sqlite_datareader.GetString(2); categoryDisplayPositionList[k] = sqlite_datareader.GetInt32(6); categoryLayoutList[k] = sqlite_datareader.GetInt32(7); categoryBackImageList[k] = sqlite_datareader.GetString(9); bool saleFlag = false; string openTime = ""; if (week == "Sat") { openTime = sqlite_datareader.GetString(4); } else if (week == "Sun") { openTime = sqlite_datareader.GetString(5); } else { openTime = sqlite_datareader.GetString(3); } categoryOpenTimeList[k] = openTime; string[] openTimeArr = openTime.Split('/'); foreach (string openTimeArrItem in openTimeArr) { string[] openTimeSubArr = openTimeArrItem.Split('-'); if (String.Compare(openTimeSubArr[0], currentTime) <= 0 && String.Compare(openTimeSubArr[1], currentTime) >= 0) { saleFlag = true; break; } } categorySoldStateList[k] = 1; if (saleFlag == true) { categorySoldStateList[k] = 0; } } k++; } } private void set_background(Object sender, PaintEventArgs e) { Label lTemp = (Label)sender; Graphics graphics = e.Graphics; //the rectangle, the same size as our Form Rectangle gradient_rectangle = new Rectangle(0, 0, lTemp.Width, lTemp.Height); //define gradient's properties Brush b = new LinearGradientBrush(gradient_rectangle, Color.FromArgb(255, 164, 206, 235), Color.FromArgb(255, 87, 152, 199), 90f); //apply gradient graphics.FillRectangle(b, gradient_rectangle); graphics.DrawRectangle(new Pen(Brushes.Gray), gradient_rectangle); e.Graphics.DrawString(lTemp.Text, new Font("Seri", 18, FontStyle.Bold), Brushes.White, gradient_rectangle, new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center }); } static SQLiteConnection CreateConnection(string dbName) { SQLiteConnection sqlite_conn; // Create a new database connection: sqlite_conn = new SQLiteConnection("Data Source=" + dbName + ".db; Version = 3; New = True; Compress = True; "); // Open the connection: try { sqlite_conn.Open(); } catch (Exception ex) { Console.WriteLine(ex); } return sqlite_conn; } } }
using UnityEngine; using System.Collections; using UnityEngine; using MZ.LWD; using UnityEngine.Rendering; using UnityEngine.Experimental.Rendering; public class FinalBlitPass : ScriptableRenderPass { const string k_FinalBlitTag = "Final Blit Pass"; private RenderTargetHandle colorAttachmentHandle { get; set; } private RenderTextureDescriptor desc { get; set; } public void Setup(RenderTextureDescriptor baseDesc, RenderTargetHandle colorAttachmentHandle) { this.colorAttachmentHandle = colorAttachmentHandle; this.desc = baseDesc; } public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData) { Material material = renderer.GetMaterial(MaterialHandles.Blit); RenderTargetIdentifier sourceRT = colorAttachmentHandle.Identifier(); CommandBuffer cmd = commandBufferPool.Get(k_FinalBlitTag); cmd.SetGlobalTexture("_BlitTex", sourceRT); //if(!renderingData.cameraData.isDefaultViewport) cmd.Blit(colorAttachmentHandle.Identifier(), BuiltinRenderTextureType.CameraTarget, material); context.ExecuteCommandBuffer(cmd); commandBufferPool.Release(cmd); } }
using System.Collections.Generic; namespace Logic.Extensions { public static class MatrixEx { public static IEnumerable<T> GetDirations<T>(this T[][] board, int rowIndex, int columnIndex) { if (rowIndex < board.Length - 1) { yield return board[rowIndex + 1][columnIndex]; } if (rowIndex > 0) { yield return board[rowIndex - 1][columnIndex]; } if (columnIndex < board[rowIndex].Length - 1) { yield return board[rowIndex][columnIndex + 1]; } if (columnIndex > 0) { yield return board[rowIndex][columnIndex - 1]; } } } }
using Moq; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace NunitMoq.UnitTest { [TestFixture] public class MockingMethodsOutAndRefParameters { [Test] public void OutAndRefArguments() { var mock = new Mock<IFoo>(); var requiredOutput = "ok"; mock.Setup(foo => foo.TryParse("ping", out requiredOutput)).Returns(true); string result; Assert.Multiple(() => { Assert.IsTrue(mock.Object.TryParse("ping", out result)); Assert.That(result, Is.EqualTo(requiredOutput)); var thisShouldBeFalse = mock.Object.TryParse("pong", out result); Console.WriteLine(thisShouldBeFalse); ; Console.WriteLine(result); }); var bar = new Bar() { Name = "abc"}; mock.Setup(foo => foo.Submit(ref bar)).Returns(true); Assert.That(mock.Object.Submit(ref bar), Is.EqualTo(true)); var someOtherBar = new Bar() { Name = "abc" }; Assert.IsFalse(mock.Object.Submit(ref someOtherBar)); //False Here is other ref to Bar!!! } } }
/* Task 3. Write a class PokerHandsChecker (+ tests) and start implementing the IPokerHandsChecker interface. * Implement the IsValidHand(IHand). A hand is valid when it consists of exactly 5 different cards. */ /* Task 4. Implement IPokerHandsChecker.IsFlush(IHand) method. */ /* Task 5. Implement IsFourOfAKind(IHand) method. Did you test all the scenarios? */ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Poker; using System.Collections.Generic; namespace TestPoker { [TestClass] public class PokerHandsCheckerTest { [TestMethod] public void PokerHandsCheckerIsValidTestNullHand() { Hand handToTest = null; PokerHandsChecker testChecker = new PokerHandsChecker(); Assert.AreEqual(false, testChecker.IsValidHand(handToTest)); } [TestMethod] public void PokerHandsCheckerIsValidTestHighCount() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Ace, CardSuit.Diamonds), new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Ace, CardSuit.Spades), new Card(CardFace.Eight, CardSuit.Clubs), new Card(CardFace.Five, CardSuit.Clubs) }; Hand handToCheck = new Hand(cardsList); PokerHandsChecker testChecker = new PokerHandsChecker(); Assert.AreEqual(false, testChecker.IsValidHand(handToCheck)); } [TestMethod] public void PokerHandsCheckerIsValidTetstEqualCards() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Ace, CardSuit.Diamonds), new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Ace, CardSuit.Spades), new Card(CardFace.Ace, CardSuit.Clubs) }; Hand handToCheck = new Hand(cardsList); PokerHandsChecker testChecker = new PokerHandsChecker(); Assert.AreEqual(false, testChecker.IsValidHand(handToCheck)); } [TestMethod] public void PokerHandsCheckerIsvalidTestValidCards() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Ace, CardSuit.Diamonds), new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Ace, CardSuit.Spades), new Card(CardFace.Eight, CardSuit.Clubs) }; Hand handToCheck = new Hand(cardsList); PokerHandsChecker testChecker = new PokerHandsChecker(); Assert.AreEqual(true, testChecker.IsValidHand(handToCheck)); } [TestMethod] public void PokerHandsCheckerIsFlushTestInvalidCards() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Ace, CardSuit.Diamonds), new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Ace, CardSuit.Spades), new Card(CardFace.Eight, CardSuit.Clubs) }; var hand = new Hand(cardsList); var testChecker = new PokerHandsChecker(); Assert.AreEqual(false, testChecker.IsFlush(hand)); } [TestMethod] public void PokerHandsCheckerIsFlushTestValidCards() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Four, CardSuit.Clubs), new Card(CardFace.Five, CardSuit.Clubs), new Card(CardFace.Eight, CardSuit.Clubs), new Card(CardFace.Jack, CardSuit.Clubs) }; var hand = new Hand(cardsList); var testChecker = new PokerHandsChecker(); Assert.AreEqual(true, testChecker.IsFlush(hand)); } [TestMethod] public void PokerHandsCheckerIsFourOfAKindTestInvalidCards() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Four, CardSuit.Clubs), new Card(CardFace.Five, CardSuit.Clubs), new Card(CardFace.Eight, CardSuit.Clubs), new Card(CardFace.Jack, CardSuit.Clubs) }; var hand = new Hand(cardsList); var testChecker = new PokerHandsChecker(); Assert.AreEqual(false, testChecker.IsFourOfAKind(hand)); } [TestMethod] public void PokerHandsCheckerIsFourOfAKindTestValidCards() { var cardsList = new List<ICard>() { new Card(CardFace.Ace, CardSuit.Clubs), new Card(CardFace.Ace, CardSuit.Diamonds), new Card(CardFace.Ace, CardSuit.Spades), new Card(CardFace.Ace, CardSuit.Hearts), new Card(CardFace.Jack, CardSuit.Clubs) }; var hand = new Hand(cardsList); var testChecker = new PokerHandsChecker(); Assert.AreEqual(true, testChecker.IsFourOfAKind(hand)); } } }
using UnityEngine; public class HumanoidAi : MonoBehaviour { public Transform Player; private Rigidbody rb; public float distanceLimit = 0.6f; public float period = 150f; public float forceValue = 80f; private Vector3 dy = new Vector3(0.0f, 3f); private float t = 0.0f; private System.Random random; private Transform cachedTransform; private AiState aiState = AiState.Respawned; void Start() { rb = this.gameObject.GetComponent<Rigidbody>(); random = new System.Random(); cachedTransform = gameObject.transform; } void Update() { switch (aiState) { case AiState.Respawned: { JumpUp(); aiState = AiState.FollowingPlayer; break; } case AiState.FollowingPlayer: { var directionToPlayer = GetDirectionToPlayer(); FollowPlayer(directionToPlayer); if (random.Next(0, 1500) == 1000) { aiState = AiState.RandomJump; } if (cachedTransform.position.y < 0.3f) { aiState = AiState.IsFallingDown; } break; } case AiState.IsFallingDown: { JumpUp(); aiState = AiState.FollowingPlayer; break; } case AiState.RandomJump: { RandomJump(); aiState = AiState.FollowingPlayer; break; } } t++; } private Vector3 GetDirectionToPlayer() { var vectorBetweenCrabAndPlayer = (Player.position + dy) - cachedTransform.position; var directionToPlayer = vectorBetweenCrabAndPlayer.normalized; var distance = vectorBetweenCrabAndPlayer.magnitude; if (distance < distanceLimit) { directionToPlayer = -1 * directionToPlayer; } return directionToPlayer; } private void FollowPlayer(Vector3 directionToPlayer) { if (t >= period) { rb.AddForce(directionToPlayer * forceValue); t = 0; } } private void JumpUp() { rb.AddForce(Vector3.up * 30f); } private void RandomJump() { var x = random.Next(-10, 10); var y = random.Next(-10, 10); var dir = (new Vector3(x, y, 0f)).normalized; rb.AddForce(dir * 100f); } enum AiState { Respawned, FollowingPlayer, RandomJump, IsFallingDown } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /* * カメラ位置の調整と移動制限 * MainCameraにアタッチ */ public class CameraController : MonoBehaviour { [Header("プレイヤー")] private GameObject mPlayer; [Header("プレイヤーとカメラの差異")] private Vector3 mOffset; [Header("Stage(Floor)")] private StageRect mStageRect; [Header("プレイヤーまでの距離")] private float mDistance = 10f; [Header("カメラの表示領域")] private Vector3 mCameraTopL, mCameraTopR, mCameraBottomL, mCameraBottomR; [SerializeField, Header("カメラの横幅")] private float mCameraWidth; [SerializeField, Header("カメラの縦幅")] private float mCameraHeight; [Header("カメラの座標")] private Vector3 mNewPosition; [Header("移動制限座標")] private Vector3 mLimitPosition; [Header("ボス突入フラグ")] public bool mBoss; /// <summary> /// カメラの表示領域を緑ラインで表示 /// </summary> void OnDrawGizmos() { Gizmos.color = Color.green; Gizmos.DrawLine(mCameraBottomL, mCameraTopL); Gizmos.DrawLine(mCameraTopL, mCameraTopR); Gizmos.DrawLine(mCameraTopR, mCameraBottomR); Gizmos.DrawLine(mCameraBottomR, mCameraBottomL); } void Start() { //プレイヤーキャラを取得 mPlayer = GameObject.FindGameObjectWithTag("Player"); mOffset = transform.position - mPlayer.transform.position; //StageRectを取得 mStageRect = GameObject.Find("FloorBase").GetComponent<StageRect>(); } void Update() { if (!mBoss) NormaCamera(); else BossCamera(); } void NormaCamera() { Rect mRect = mStageRect.GetStageRect(); float mNewX = 0f; float mNewY = 0f; //プレイヤーキャラの位置にカメラの座標を設定する。キャラのちょっと上にする mNewPosition = mPlayer.transform.position + mOffset + Vector3.up * 3f; CameraSetting(); //カメラの稼働領域をステージ領域に制限 mNewX = Mathf.Clamp(mNewPosition.x, mRect.xMin + mCameraWidth / 2, mRect.xMax - mCameraWidth / 2); mNewY = Mathf.Clamp(mNewPosition.y, 0, mRect.yMax - mCameraHeight / 2); //座標をカメラ位置に設定 mLimitPosition = new Vector3(mNewX, mNewY, transform.position.z); transform.position = Vector3.Lerp(transform.position, mLimitPosition, 5.0f * Time.deltaTime); } void BossCamera() { Vector3 mBossPos= GameObject.Find("BossCameraPos").transform.position; mLimitPosition = new Vector3(mBossPos.x, mBossPos.y, transform.position.z); transform.position = Vector3.Lerp(transform.position, mLimitPosition, 3.0f * Time.deltaTime); } /// <summary> /// ビューポート座標をワールド座標に変換 /// </summary> void CameraSetting() { mCameraBottomL = Camera.main.ViewportToWorldPoint(new Vector3(0, 0, mDistance)); mCameraTopR = Camera.main.ViewportToWorldPoint(new Vector3(1, 1, mDistance)); mCameraTopL = new Vector3(mCameraBottomL.x, mCameraTopR.y, mCameraBottomL.z); mCameraBottomR = new Vector3(mCameraTopR.x, mCameraBottomL.y, mCameraTopR.z); mCameraWidth = Vector3.Distance(mCameraBottomL, mCameraBottomR); mCameraHeight = Vector3.Distance(mCameraBottomL, mCameraTopL); } public float GetCameraWidthSize() { return mCameraWidth; } public float GetCameraHeightSize() { return mCameraHeight; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TaskObject : MonoBehaviour { public GameObject sibling; public void Disable() { sibling.SetActive(true); gameObject.SetActive(false); } /*private void OnDisable() { sibling.SetActive(true); }*/ public void RandomizeColor() { Color color = new Color(Random.value * 0.7f + 0.15f, Random.value * 0.7f + 0.15f, Random.value * 0.7f + 0.15f); gameObject.GetComponent<Renderer>().material.color = color; sibling.GetComponent<Renderer>().material.color = color; } }
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. // VisualNovelToolkit /_/_/_/_/_/_/_/_/_/. // Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/. //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. using UnityEngine; using System.Collections; /// <summary> /// ISoundPlayer. /// </summary> public class ISoundPlayer : MonoBehaviour{ public enum Category{ BGM=0, SE, VOICE, } static private ISoundPlayer m_Instance; public static ISoundPlayer Instance { get { return m_Instance; } } static public float kMusicFadeTimeOnClickBack = 1f; // sec. static public float kPlayDelayWhenLoaded = 1f; static public float kOnLoadPlayBGMWaitSec = 2f; public bool m_PlayMusicAtStart; // check this from inspector. public string m_StartMusicName; public float m_StartMusicDelay = 0f; protected int k_BgmPoolNum = 2; protected int k_SeAndVoicePlayMax = 4; protected GameObject[] m_AudioPool; // Voice and Se0 and Se1 and Se2. protected int m_VoiceIndex = 0; void Awake(){ if( ! Application.isPlaying ){ return; } if( Instance == null ){ m_Instance = this; // gameObject.hideFlags = HideFlags.NotEditable; if( k_SeAndVoicePlayMax == 0 ){ Debug.LogWarning( "SE and Voice can't play because the k_SeAndVoicePlayMax is ZERO !" ); } else{ Transform self = transform; m_AudioPool = new GameObject[ k_SeAndVoicePlayMax ]; for( int i=0;i<k_SeAndVoicePlayMax;i++){ m_AudioPool[ i ] = new GameObject( "_AudioPool_" + i.ToString() ); m_AudioPool[ i ].AddComponent<AudioSource>(); m_AudioPool[ i ].transform.parent = self; } } OnAwake(); } else{ if( Application.isPlaying ){ Destroy( gameObject ); } } } void Start(){ OnStart(); } void OnEnable(){ // Debug.Log( "OnEnable:" + name ); m_Instance = this; } void OnDisable(){ // Debug.Log( "OnDisable:" + name ); m_Instance = null; } void OnDestroy(){ // Debug.Log( "OnDestroy:" + name ); m_Instance = null; } virtual public void OnAwake(){} virtual public void OnSave( ViNoSaveInfo info ){} virtual public void OnLoad( ViNoSaveInfo info ){} virtual public void OnStart(){} virtual public void BGMVolumeChanged( float val ){} virtual public void SEVolumeChanged( float val ){} virtual public void VoiceVolumeChanged( float val ){ } virtual public void PlayAudioClip( AudioClip clip , string resourcePath , float volume , float delay ){} virtual public void PlayMusic( Hashtable param ){} virtual public void PlayMusic( string path , bool loop , float xchbgmTime = 0f ){} virtual public void PlayMusic( string name , float volume , float delay ){} virtual public void PlayMusic( int id , float volume , float delay ){} virtual public void PlaySE( string name , float volume , float delay ){} virtual public void PlaySE( string path , bool loop , float xchbgmTime = 0f ){} virtual public void PlaySE( int id , float volume , float delay ){} virtual public void PlayVoice( string name , float volume , float delay ){} virtual public void PlayVoice( int id , float volume , float delay ){} virtual public void PlayVoice( string path , bool loop , float xchbgmTime = 0f ){} virtual public void StopMusic( float fadeTime ){} virtual public void StopSE(){} virtual public void StopSE( string name , float fadeTime ){} virtual public void StopVoice(){} virtual public void StopVoice( string name , float fadeTime ){} // This is Callback from VM. // category is Music or SE or Voice. public void PlaySoundCallback( string name , string category , float catVol , float delay ){ ViNoDebugger.Log ( "Sound" , "PlaySound Callback." ); if( category.Equals( "Music" ) ){ float realVol = ViNoConfig.prefsBgmVolume * catVol; PlayMusic( name , realVol , delay ); } else if( category.Equals( "SE" ) ){ float realVol = ViNoConfig.prefsSeVolume * catVol; PlaySE( name , realVol , delay ); } else if( category.Equals( "Voice" ) ){ float realVol = ViNoConfig.prefsVoiceVolume * catVol; PlayVoice( name , realVol , delay ); } } // This is Callback from VM. // category is Music or SE or Voice. public void StopSoundCallback( string name , string category , float fadetime ){ if( category.Equals( "Music" ) ){ StopMusic( fadetime ); } else if( category.Equals( "SE" ) ){ StopSE ( name , fadetime ); } else if( category.Equals( "Voice" ) ){ StopVoice( name , fadetime ); } } /// <param name='index'> /// Index start from 1 to 3. /// </param> public bool IsPlayingSE( int index ){ if( index >= k_SeAndVoicePlayMax ){ return false; } else{ return m_AudioPool[ index ].audio.isPlaying; } } /// <summary> /// Determines whether this instance is playing voice. /// </summary> /// <returns> /// <c>true</c> if this instance is playing voice; otherwise, <c>false</c>. /// </returns> public bool IsPlayingVoice(){ return IsPlaying( m_AudioPool[ m_VoiceIndex ].audio ); } protected bool IsPlaying( AudioSource audioSource ){ if( audioSource != null ){ return audioSource.isPlaying; } else{ return false; } } /* /// <summary> /// Get BGM GO Attached a AudioSource. /// </summary> public GameObject GetGOBGMPool(){ for( int i=0;i<k_BgmPoolNum;i++){ if( ! m_BGMAudioPool[ i ].activeInHierarchy ){ m_BGMAudioPool[ i ].gameObject.SetActive( true ); return m_BGMAudioPool[ i ].gameObject; } } return null; // Busy. } //*/ /// <summary> /// Delaies the play background. /// </summary> /// <returns> /// The play background. /// </returns> /// <param name='bgm'> /// Bgm. /// </param> IEnumerator DelayPlayBGM( string bgm ){ yield return new WaitForSeconds( kOnLoadPlayBGMWaitSec ); PlayMusic( bgm , ViNoConfig.prefsBgmVolume , kPlayDelayWhenLoaded ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace ZUS.Zeus.BikeService.Results { public static class ApiControllerExtensions { public static IHttpActionResult NotFound(this ApiController controller, string content) { return new NotFoundResult(content); } } public class NotFoundResult : IHttpActionResult { private readonly string _content; public NotFoundResult(string content) { _content = content; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound) { Content = new StringContent(_content.ToString()) }; return Task.FromResult(response); } } }
using System; using System.Windows.Media.Effects; using Microsoft.Practices.Prism.ViewModel; namespace Torshify.Radio.Framework { public class TileData : NotificationObject { #region Fields private Uri _backBackgroundImage; private object _backContent; private Uri _backgroundImage; private string _backTitle; private object _content; private Effect _effect; private bool _isLarge; private string _title; #endregion Fields #region Properties public Uri BackBackgroundImage { get { return _backBackgroundImage; } set { if (_backBackgroundImage != value) { _backBackgroundImage = value; RaisePropertyChanged("BackBackgroundImage"); } } } public object BackContent { get { return _backContent; } set { if (_backContent != value) { _backContent = value; RaisePropertyChanged("BackContent"); } } } public Uri BackgroundImage { get { return _backgroundImage; } set { if (_backgroundImage != value) { _backgroundImage = value; RaisePropertyChanged("BackgroundImage"); } } } public string BackTitle { get { return _backTitle; } set { if (_backTitle != value) { _backTitle = value; RaisePropertyChanged("BackTitle"); } } } public Effect Effect { get { return _effect; } set { if (_effect != value) { _effect = value; RaisePropertyChanged("Effect"); } } } public bool IsLarge { get { return _isLarge; } set { if (_isLarge != value) { _isLarge = value; RaisePropertyChanged("IsLarge"); } } } public object Content { get { return _content; } set { if (_content != value) { _content = value; RaisePropertyChanged("Content"); } } } public string Title { get { return _title; } set { if (_title != value) { _title = value; RaisePropertyChanged("Title"); } } } #endregion Properties } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace transGraph { public partial class Back : Form { Thread t; Global g; public Back(Global g) { this.g = g; InitializeComponent(); } private void Loading_Shown(object sender, EventArgs e) { t = new Thread(new ThreadStart(delegate { g.backup.DoIt(); this.Invoke(new ThreadStart(delegate { this.Close(); })); })); t.Start(); } private void Loading_FormClosing(object sender, FormClosingEventArgs e) { this.t.Abort(); } } }
using SFML.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LD30 { abstract class GameObject { protected Game game; public virtual float Depth { get { return 0f; } } public virtual FloatRect? VisibleRect { get { return null; } } public World MyWorld = null; private bool enabled = true; public virtual bool Enabled { get { return enabled; } set { enabled = value; } } public GameObject(Game game) { this.game = game; } public virtual void Update(float dt) { } public virtual void Draw(RenderTarget target) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NPCAnimation : MonoBehaviour { private Animator anim; private void Awake() { anim = GetComponent<Animator>(); } public void FaceDirection(NPCSetting.Direction direction) { switch (direction) { case NPCSetting.Direction.Up: anim.SetFloat("moveX", 0f); anim.SetFloat("moveY", 1f); break; case NPCSetting.Direction.Down: anim.SetFloat("moveX", 0f); anim.SetFloat("moveY", -1f); break; case NPCSetting.Direction.Left: anim.SetFloat("moveX", -1f); anim.SetFloat("moveY", 0f); break; case NPCSetting.Direction.Right: anim.SetFloat("moveX", 1f); anim.SetFloat("moveY", 0f); break; default: anim.SetFloat("moveX", 0f); anim.SetFloat("moveY", -1f); break; } } public void PlayWalk(float x, float y) { anim.SetFloat("moveX", x); anim.SetFloat("moveY", y); anim.Play("Walk"); } public void PlayIdle() { anim.Play("Idle"); } }
using Coding.Dojo.Abtraction; using Coding.Dojo.Wpf.ViewModels; using Microsoft.Win32; using RestSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Media; namespace Coding.Dojo.Wpf { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } #region [ Events ] private void ImportarClientesClick(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "Json files (*.json)|*.json", InitialDirectory = @"C:\Temp\" }; // Faz a Procura por um arquivo que atenda ao Fitro configurado acima! if (openFileDialog.ShowDialog() == true) { var json = File.ReadAllText(openFileDialog.FileName); if (!string.IsNullOrWhiteSpace(json)) { // Chama os Métodos para: // Converter o Json em um (Lista de Objetos) var clientes = ConvertJson(json); // Preencher a DataGrid com a (Lista dos Objetos) if (clientes.Any()) { LoadDataGrid(clientes); } } } } private void ValidarClientesClick(object sender, RoutedEventArgs e) { // Pegar os dados que estão dentro da DataGrid e Repopula-los somente com os Adultos var clientes = new List<ClienteViewModel>((IEnumerable<ClienteViewModel>)DadosImportados.ItemsSource); if (!clientes.Any()) return; var idadeAdulta = DateTime.Now.AddYears(-18).Date; var clientesAdultos = clientes .Where(c => c.DataNascimento >= idadeAdulta) .Select(c => { c.ConsideradoAdulto = true; return c; }); DadosImportados.ItemsSource = clientesAdultos; // Modifica o Estilo da DataGrid para sabermos que foi atualizada DadosImportados.Background = Brushes.LightGray; DadosImportados.RowBackground = Brushes.LightYellow; DadosImportados.AlternatingRowBackground = Brushes.LightBlue; } #endregion [ Events ] #region [ Helpers ] private IEnumerable<Cliente> ConvertJson(string json) { if (string.IsNullOrWhiteSpace(json)) return null; // Instancia o Manager var manager = new Managers.ClienteManager(); // Deserializa o Json var result = manager.Deserialize<List<Cliente>>(json); if (result == null) return null; return result; } private void LoadDataGrid(IEnumerable<Cliente> clientes) { DadosImportados.ItemsSource = clientes.Select(c => { return new ClienteViewModel(c); }).ToList(); // Limpa o Estilo da Grid DadosImportados.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFF0F0F0")); //DadosImportados.Background = Brushes.White; DadosImportados.RowBackground = null; DadosImportados.AlternatingRowBackground = null; } private void PegarClientesClick(object sender, RoutedEventArgs e) { var baseUrl = $"https://my.api.mockaroo.com/codingdojo.json?key=beda91c0"; var restClient = new RestClient(baseUrl); var request = new RestRequest(Method.GET); request.AddHeader("Content-Type", "application/json"); var response = restClient.Execute(request); if (response != null && response.Content != null && response.StatusCode == System.Net.HttpStatusCode.OK) { var json = response.Content; // Chama os Métodos para: // Converter o Json em um (Lista de Objetos) var clientes = ConvertJson(json); // Preencher a DataGrid com a (Lista dos Objetos) if (clientes.Any()) { LoadDataGrid(clientes); } } else { MessageBox.Show($"Não foi possível Recuperar os dados da Url informada:\n {baseUrl}"," Ops...", MessageBoxButton.OK, MessageBoxImage.Error); } } #endregion [ Helpers ] } }
using DataModel; using Nancy; using Nancy.ModelBinding; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Nancy.Authentication.Forms; using Nancy.Security; using Nancy.Extensions; using WebMarket.Models.Request; namespace WebMarket.Module { public class LetterModule : NancyModule { public LetterModule() { Get["/AddLetter"] = _ => { return View["Letter/AddLetter"]; }; Get["/EditLetter/{letter}"] = parameters => { var c = parameters.letter; var model = new { Letter = c}; return View["Letter/EditLetter", model]; }; Get["/ListLetter"] = _ => { return View["Letter/ListLetter"]; }; } } }
using HINVenture.Shared.Data; using HINVenture.Shared.Models.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HINVenture.Shared.Models { public class MessageRepository : IRepository<Message> { private readonly ApplicationDbContext _db; public MessageRepository(ApplicationDbContext db) { this._db = db; } public async Task Create(Message p) { _db.Messages.Add(p); await _db.SaveChangesAsync(); } public Task<Message> Get(int id) { throw new NotImplementedException(); } public IQueryable<Message> GetAll() { return _db.Messages; } public Task Remove(Message entity) { throw new NotImplementedException(); } public Task Update(Message entity) { throw new NotImplementedException(); } } }
using System; using System.IO; using System.Collections.Generic; using SprintFour.Blocks; using System.Text; using SprintFour.Utilities; namespace SprintFour.Levels { public static class BoggusLoader { public static List<string> QuoteList; public static string AlphaQuote; public static void LoadQuotes(string filename) { QuoteList = new List<string>(); Boggus.BoggusBlockCounter = 0; try { StreamReader fileIn = new StreamReader(filename); string nextLine = fileIn.ReadLine(); AlphaQuote = FormatQuote(nextLine); while ((nextLine = fileIn.ReadLine()) != null) { if (!nextLine.Trim().Equals("")) QuoteList.Add(FormatQuote(nextLine)); } Random rand = new Random(); QuoteList.Sort((x, y) => rand.NextDouble() < 0.5 ? -1 : 1); } catch (Exception e) { Console.WriteLine(e.ToString()); QuoteList.Clear(); QuoteList.Add("Error!"); } } private static string FormatQuote(string oldString) { StringBuilder newString = new StringBuilder(); int visibleChars = oldString.Replace("|", "").Length; while (visibleChars > Utility.BOGGUS_QUOTE_WIDTH) { int split = oldString.Substring(0,Utility.BOGGUS_QUOTE_WIDTH).LastIndexOf(' '); if (split < 0) { split = Utility.BOGGUS_QUOTE_WIDTH; oldString = oldString.Insert(Utility.BOGGUS_QUOTE_WIDTH, " "); } newString.Append(oldString.Substring(0, split)).Append("\n"); oldString = oldString.Substring(split + 1); visibleChars = oldString.Replace("|", "").Length; } newString.Append(oldString); return newString.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task13 { class Program { static void Main(string[] args) { //Implement the ADT queue as dynamic linked list. //Use generics (LinkedQueue<T>)to allow storing different data types in the queue. LinkedQueue<int> queue = new LinkedQueue<int>(); Console.WriteLine("Add 1,2,3 in the queue"); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); Console.WriteLine("Dequeue the values"); Console.WriteLine(queue.Dequeue()); Console.WriteLine(queue.Dequeue()); Console.WriteLine(queue.Dequeue()); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace JoveZhao.Framework.DDD { public class DDDConfigurationElement : ConfigurationElement { [ConfigurationProperty("unitOfWork")] public UnitOfWorkConfigurationElement UnitOfWork { get { return (UnitOfWorkConfigurationElement)base["unitOfWork"]; } set { base["unitOfWork"] = value; } } [ConfigurationProperty("repositories")] public RepositoryElementCollection Repositories { get { return (RepositoryElementCollection)base["repositories"]; } set { base["repositories"] = value; } } [ConfigurationProperty("events")] public EventElementCollection Events { get { return (EventElementCollection)base["events"]; } set { base["events"] = value; } } } public class UnitOfWorkConfigurationElement : ConfigurationElement { [ConfigurationProperty("unitOfWorkProvider")] public string UnitOfWorkProvider { get { return (string)base["unitOfWorkProvider"]; } set { base["unitOfWorkProvider"] = value; } } public Type UnitOfWorkType { get { return Type.GetType(UnitOfWorkProvider); } } [ConfigurationProperty("repositoryProvider")] public string RepositoryProvider { get { return (string)base["repositoryProvider"]; } set { base["repositoryProvider"] = value; } } public Type RepositoryType { get { return Type.GetType(RepositoryProvider); } } } public class IocConfigurationElement : ConfigurationElement { [ConfigurationProperty("name")] public string Name { get { return (string)base["name"]; } set { base["name"] = value; } } [ConfigurationProperty("forProvider")] public string ForProvider { get { return (string)base["forProvider"]; } set { base["forProvider"] = value; } } public Type ForType { get { return Type.GetType(ForProvider); } } [ConfigurationProperty("useProvider")] public string UseProvider { get { return (string)base["useProvider"]; } set { base["useProvider"] = value; } } public Type UseType { get { return Type.GetType(UseProvider); } } } public class RepositoryElementCollection : BaseElementCollection<IocConfigurationElement> { protected override object GetKey(IocConfigurationElement t) { return t.Name; } protected override string ItemName { get { return "repository"; } } } public class EventElementCollection : BaseElementCollection<IocConfigurationElement> { protected override object GetKey(IocConfigurationElement t) { return t.Name; } protected override string ItemName { get { return "event"; } } } }
using System; using DevExpress.Mvvm.DataAnnotations; using DevExpress.Mvvm; using System.Collections.Generic; using DevExpress.Mvvm.POCO; using System.ComponentModel.DataAnnotations; namespace SimpleDemo.UI.ViewModels { [POCOViewModel] public class SettingManageViewModel { public List<ModuleInfo> Menu { get; set; } [Required] protected virtual ICurrentWindowService CurrentWindowService { get { return null; } } protected virtual ISplashScreenService SplashScreenService { get { return this.GetService<ISplashScreenService>(); } } public SettingManageViewModel() { Menu = new List<ModuleInfo>() { ViewModelSource.Create(()=>new ModuleInfo("SettingBasicView",this,"基本信息")).SetIcon("setting"), ViewModelSource.Create(()=>new ModuleInfo("SettingTimeView",this,"时间参数")).SetIcon("time"), ViewModelSource.Create(()=>new ModuleInfo("SettingPortView",this,"串口设置")).SetIcon("port"), ViewModelSource.Create(()=>new ModuleInfo("SettingLineView",this,"通道管理")).SetIcon("line"), }; } } }
using KekManager.Domain; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace KekManager.Api.Interfaces { public interface ISubjectBl { Task<IList<Subject>> GetAll(); Task<Subject> SetSupervisor(int subjectId, int? supervisorId); } }
using System.Collections.Generic; using UnityEngine; [CreateAssetMenu] public class ComponentAdder : EntityTank { public List<ComponentDatabase> componentDBs; public override void MyOperation (Entity entity) { foreach (var cDB in componentDBs) { cDB.AddComponent(entity.id); } } }
using System; using System.Net.Sockets; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using NAudio.Wave; using System.Threading; using System.Net; namespace CallsUdp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); //создаем поток для записи нашей речи input = new WaveIn(); //определяем его формат - частота дискретизации 8000 Гц, ширина сэмпла - 16 бит, 1 канал - моно input.WaveFormat = new WaveFormat(8000, 16, 1); //добавляем код обработки нашего голоса, поступающего на микрофон input.DataAvailable += VoiceInput; //создаем поток для прослушивания входящего звука output = new WaveOut(); //создаем поток для буферного потока и определяем у него такой же формат как и потока с микрофона bufferStream = new BufferedWaveProvider(new WaveFormat(8000, 16, 1)); //привязываем поток входящего звука к буферному потоку output.Init(bufferStream); //сокет для отправки звука client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); connected = true; listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //создаем поток для прослушивания in_thread = new Thread(new ThreadStart(Listening)); //запускаем его in_thread.Start(); EnableStartCalling(); } //Подключены ли мы private bool connected; //сокет отправитель Socket client; //поток для нашей речи WaveIn input; //поток для речи собеседника WaveOut output; //буфферный поток для передачи через сеть BufferedWaveProvider bufferStream; //поток для прослушивания входящих сообщений Thread in_thread; //сокет для приема (протокол UDP) Socket listeningSocket; //Обработка нашего голоса private void VoiceInput(object sender, WaveInEventArgs e) { try { //Подключаемся к удаленному адресу IPEndPoint remote_point = new IPEndPoint(IPAddress.Parse(destinationIp.Text), 5555); //посылаем байты, полученные с микрофона на удаленный адрес client.SendTo(e.Buffer, remote_point); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } //Прослушивание входящих подключений private void Listening() { //Прослушиваем по адресу IPEndPoint localIP = new IPEndPoint(GetLocalIpAddress(), 5555); listeningSocket.Bind(localIP); //начинаем воспроизводить входящий звук output.Play(); //адрес, с которого пришли данные EndPoint remoteIp = new IPEndPoint(IPAddress.Any, 0); //бесконечный цикл while (connected == true) { try { //промежуточный буфер byte[] data = new byte[65535]; //получено данных int received = listeningSocket.ReceiveFrom(data, ref remoteIp); //добавляем данные в буфер, откуда output будет воспроизводить звук bufferStream.AddSamples(data, 0, received); } catch (SocketException ex) { return; } } } private void AppClosing(object sender, System.ComponentModel.CancelEventArgs e) { input.StopRecording(); connected = false; listeningSocket.Close(); listeningSocket.Dispose(); client.Close(); client.Dispose(); if (output != null) { output.Stop(); output.Dispose(); output = null; } if (input != null) { input.Dispose(); input = null; } bufferStream = null; } private void StopCalling() { input.StopRecording(); output.Stop(); } private void Start(object sender, RoutedEventArgs e) { IPAddress temp; if (!IPAddress.TryParse(destinationIp.Text, out temp)) { MessageBox.Show("Введены неверные данные!"); return; } DisableStartCalling(); input.StartRecording(); } private IPAddress GetLocalIpAddress() { System.Net.IPAddress ip = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[1]; return ip; } private void Stop(object sender, RoutedEventArgs e) { StopCalling(); EnableStartCalling(); } private void EnableStartCalling() { destinationIp.IsEnabled = true; startButton.IsEnabled = true; stopButton.IsEnabled = false; } private void DisableStartCalling() { destinationIp.IsEnabled = false; startButton.IsEnabled = false; stopButton.IsEnabled = true; } } }
using UnityEngine; namespace VectorExtension { [System.Serializable] public struct Distribution { public float mean, stdDev; public Range range; public Distribution(float mean = 0f, float stdDev = 1f, float min = -5f, float max = 5f) { this.mean = mean; this.stdDev = stdDev; this.range.min = (min > mean - stdDev) ? mean - stdDev : min; this.range.max = (max < mean + stdDev) ? mean + stdDev : max; } } }
namespace TrafficDissector.PortScanning { internal enum ScanMessage { PortClosed, PortOpened, Timeout, Unknown } }
using Godot; using System; using static Lib; public class GrayWTower : WTower { public override void _Ready() { base._Ready(); wizard = WAR_WIZARD; } }
using System; using System.Linq; using System.Net; using System.Web.Mvc; using Grubber.Web.Data; using Grubber.Web.Models; using Grubber.Web.ViewModels; namespace Grubber.Web.Controllers { public class StoreMenuController : Controller { private readonly IGrubberRepository _repository; public StoreMenuController(IGrubberRepository repository) { _repository = repository; } // GET: StoreMenu/Create (obsolete) [Authorize] [Route("StoreMenu/Create/{storeId:int?}")] //[Route("Store/{storeId:int?}/StoreMenu/Create/", Name = "CreateStoreMenu")] public ActionResult Create(int? storeId) { if (storeId == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreById(storeId.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel { StoreId = storeId.Value }; return View(model); } // POST: StoreMenu/Create (obsolete) // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize] [ValidateAntiForgeryToken] [Route("StoreMenu/Create/{storeId:int}")] //[Route("Store/{storeId:int}/StoreMenu/Create/")] public ActionResult Create([Bind(Include = "StoreId,Name")] StoreMenuViewModel model) { if (ModelState.IsValid) { var storeMenu = new StoreMenu { Name = model.Name, RowGuid = Guid.NewGuid(), //Store = _repository.GetStoreById(model.StoreId), StoreId = model.StoreId }; _repository.InsertStoreMenu(storeMenu); _repository.Save(); return RedirectToAction("Details", "Store", new { storeId = model.StoreId }); } return View(model); } [Authorize] [ChildActionOnly] public ActionResult CreateStoreMenuPartial(StoreMenuItemViewModel model) { if (TempData["ViewData"] != null) { ViewData = (ViewDataDictionary)TempData["ViewData"]; } return PartialView("_CreateStoreMenuPartial", model); } // GET: StoreMenu/Edit/5 [Authorize] public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreMenuById(id.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel(id.Value); return View(model); } // POST: StoreMenu/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Name,StoreId")] StoreMenuViewModel model) { if (ModelState.IsValid) { var storeMenu = _repository.GetStoreMenuById(model.Id); storeMenu.Name = model.Name; _repository.UpdateStoreMenu(storeMenu); _repository.Save(); var storeId = model.StoreId; return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId }); } return View(model); } // GET: StoreMenu/UnlistAllItems/5 [Authorize] public ActionResult UnlistAllItems(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreMenuById(id.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel(id.Value); return View(model); } // POST: StoreMenu/UnlistAllItems/5 [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult UnlistAllItems(int id) { var storeId = _repository.GetStoreByMenuId(id).Id; var menuItems = _repository.GetMenuItemsByStoreMenuId(id); foreach (var menuItem in menuItems) { menuItem.StoreMenuId = null; _repository.UpdateMenuItem(menuItem); } _repository.Save(); return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId }); } // GET: StoreMenu/DeleteAndUnlistAllItems/5 [Authorize] public ActionResult DeleteAndUnlistAllItems(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreMenuById(id.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel(id.Value); return View(model); } // POST: StoreMenu/DeleteAndUnlistAllItems/5 [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult DeleteAndUnlistAllItems(int id) { var menuItems = _repository.GetMenuItemsByStoreMenuId(id); foreach (var menuItem in menuItems) { menuItem.StoreMenuId = null; _repository.UpdateMenuItem(menuItem); } _repository.Save(); var storeMenu = _repository.GetStoreMenuById(id); var storeId = storeMenu.StoreId; _repository.DeleteStoreMenu(storeMenu); _repository.Save(); return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId }); } // GET: StoreMenu/DeleteAndDeleteAllItems/5 [Authorize] public ActionResult DeleteAndDeleteAllItems(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreMenuById(id.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel(id.Value); return View(model); } // POST: StoreMenu/DeleteAndDeleteAllItems/5 [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult DeleteAndDeleteAllItems(int id) { var menuItems = _repository.GetMenuItemsByStoreMenuId(id); _repository.DeleteMenuItems(menuItems); _repository.Save(); var storeMenu = _repository.GetStoreMenuById(id); var storeId = storeMenu.StoreId; _repository.DeleteStoreMenu(storeMenu); _repository.Save(); return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId }); } // GET: StoreMenu/DeleteAllItems/5 [Authorize] public ActionResult DeleteAllItems(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreMenuById(id.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel(id.Value); return View(model); } // POST: StoreMenu/DeleteAllItems/5 [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult DeleteAllItems(int id) { var storeId = _repository.GetStoreByMenuId(id).Id; var menuItems = _repository.GetMenuItemsByStoreMenuId(id); //foreach (var menuItem in menuItems) //{ // menuItem.StoreMenuId = null; // _repository.UpdateMenuItem(menuItem); //} _repository.DeleteMenuItems(menuItems); _repository.Save(); return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId }); } [Authorize] // GET: StoreMenu/DeleteAllUnlistedItems/5 public ActionResult DeleteAllUnlistedItems(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreById(id.Value) == null) { return HttpNotFound(); } var model = new StoreViewModel(id.Value); return View(model); } // POST: StoreMenu/DeleteAllUnlistedItems/5 [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult DeleteAllUnlistedItems(int id) { var menuItems = _repository.GetMenuItemsByStoreId(id) .Where(mi => mi.StoreMenuId == null); //foreach (var menuItem in menuItems) //{ // menuItem.StoreMenuId = null; // _repository.UpdateMenuItem(menuItem); //} _repository.DeleteMenuItems(menuItems); _repository.Save(); return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId = id }); } // GET: StoreMenu/Delete/5 [Authorize] public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (_repository.GetStoreMenuById(id.Value) == null) { return HttpNotFound(); } var model = new StoreMenuViewModel(id.Value); return View(model); } // POST: StoreMenu/Delete/5 [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult Delete(int id) { var storeMenu = _repository.GetStoreMenuById(id); var storeId = storeMenu.StoreId; _repository.DeleteStoreMenu(storeMenu); _repository.Save(); return RedirectToAction("CreateStoreMenuItem", "Store", new { storeId }); } protected override void Dispose(bool disposing) { if (disposing) { _repository.Dispose(); } base.Dispose(disposing); } } }
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public interface IPartialResultParams { /// <summary> /// An optional token that a server can use to report partial results (e.g. streaming) to /// the client. /// </summary> [Optional] ProgressToken? PartialResultToken { get; init; } } }
using System; using System.Collections; using UnityEngine; namespace VavilichevGD.GameServices.Purchasing { public class BankService : GameServiceBase { #region EVENTS public override event Action OnInitializedEvent; public event BankCurrencyHandler OnSoftCurrencyValueChangedEvent; public event BankCurrencyHandler OnHardCurrencyValueChangedEvent; #endregion public int softCurrency { get => this.state.softCurrency; private set => this.state.softCurrency = value; } public int hardCurrency { get => this.state.hardCurrency; private set => this.state.hardCurrency = value; } private BankState state { get; set; } public BankService(BankState state) { this.state = state; this.PrintLog($"BANK SERVICE: State loaded. Soft: {this.softCurrency}, Hard: {this.hardCurrency}"); } public BankService() { } #region INITIALIZE protected override IEnumerator InitializeAsyncRoutine() { this.LoadState(); this.InitFasade(); this.OnInitializedEvent?.Invoke(); yield break; } private void LoadState() { if (this.state != null) return; this.state = new BankState(); this.PrintLog($"BANK SERVICE: State loaded. Soft: {this.softCurrency}, Hard: {this.hardCurrency}"); } private void InitFasade() { Bank.Initialize(this); this.PrintLog($"BANK SERVICE: Fasade Initialized (Bank.cs)"); } #endregion public void AddSoftCurrency(object sender, int value) { var oldValue = this.softCurrency; var newValue = oldValue + value; this.softCurrency = newValue; this.PrintLog($"BANK SERVICE: Soft currency changed. Old value: {oldValue}, new Value: {newValue}. Initiator: {sender.GetType().Name}"); this.OnSoftCurrencyValueChangedEvent?.Invoke(sender, oldValue, newValue); } public void SpendSoftCurrency(object sender, int value) { var oldValue = this.softCurrency; var newValue = oldValue - value; this.softCurrency = newValue; this.PrintLog($"BANK SERVICE: Soft currency changed. Old value: {oldValue}, new Value: {newValue}. Initiator: {sender.GetType().Name}"); this.OnSoftCurrencyValueChangedEvent?.Invoke(sender, oldValue, newValue); } public bool IsEnoughSoftCurrency(int value) { return this.softCurrency >= value; } public void AddHardCurrency(object sender, int value) { var oldValue = this.hardCurrency; var newValue = oldValue + value; this.hardCurrency = newValue; this.PrintLog($"BANK SERVICE: Hard currency changed. Old value: {oldValue}, new Value: {newValue}. Initiator: {sender.GetType().Name}"); this.OnHardCurrencyValueChangedEvent?.Invoke(sender, oldValue, newValue); } public void SpendHardCurrency(object sender, int value) { var oldValue = this.hardCurrency; var newValue = oldValue - value; this.hardCurrency = newValue; this.PrintLog($"BANK SERVICE: Hard currency changed. Old value: {oldValue}, new Value: {newValue}. Initiator: {sender.GetType().Name}"); this.OnHardCurrencyValueChangedEvent?.Invoke(sender, oldValue, newValue); } public bool IsEnoughHardCurrency(int value) { return this.hardCurrency >= value; } private void PrintLog(string text) { if (this.isLoggingEnabled) Debug.Log(text); } } }
using LuaInterface; using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; namespace SLua { public class LuaObject { private delegate void PushVarDelegate(IntPtr l, object o); private const string DelgateTable = "__LuaDelegate"; internal const int VersionNumber = 4113; protected static LuaCSFunction lua_gc = new LuaCSFunction(LuaObject.luaGC); protected static LuaCSFunction lua_add = new LuaCSFunction(LuaObject.luaAdd); protected static LuaCSFunction lua_sub = new LuaCSFunction(LuaObject.luaSub); protected static LuaCSFunction lua_mul = new LuaCSFunction(LuaObject.luaMul); protected static LuaCSFunction lua_div = new LuaCSFunction(LuaObject.luaDiv); protected static LuaCSFunction lua_unm = new LuaCSFunction(LuaObject.luaUnm); protected static LuaCSFunction lua_eq = new LuaCSFunction(LuaObject.luaEq); protected static LuaCSFunction lua_lt = new LuaCSFunction(LuaObject.luaLt); protected static LuaCSFunction lua_le = new LuaCSFunction(LuaObject.luaLe); protected static LuaCSFunction lua_tostring = new LuaCSFunction(LuaObject.ToString); protected static LuaFunction newindex_func; protected static LuaFunction index_func; private static Dictionary<Type, LuaObject.PushVarDelegate> typePushMap = new Dictionary<Type, LuaObject.PushVarDelegate>(); private static Type MonoType = typeof(Type).GetType(); public static void init(IntPtr l) { string str = "\n\nlocal getmetatable=getmetatable\nlocal rawget=rawget\nlocal error=error\nlocal type=type\nlocal function newindex(ud,k,v)\n local t=getmetatable(ud)\n repeat\n local h=rawget(t,k)\n if h then\n\t\t\tif h[2] then\n\t\t\t\th[2](ud,v)\n\t return\n\t\t\telse\n\t\t\t\terror('property '..k..' is read only')\n\t\t\tend\n end\n t=rawget(t,'__parent')\n until t==nil\n error('can not find '..k)\nend\n\nreturn newindex\n"; string str2 = "\nlocal type=type\nlocal error=error\nlocal rawget=rawget\nlocal getmetatable=getmetatable\nlocal function index(ud,k)\n local t=getmetatable(ud)\n repeat\n local fun=rawget(t,k)\n local tp=type(fun)\t\n if tp=='function' then \n return fun \n elseif tp=='table' then\n\t\t\tlocal f=fun[1]\n\t\t\tif f then\n\t\t\t\treturn f(ud)\n\t\t\telse\n\t\t\t\terror('property '..k..' is write only')\n\t\t\tend\n end\n t = rawget(t,'__parent')\n until t==nil\n error('Can not find '..k)\nend\n\nreturn index\n"; LuaState luaState = LuaState.get(l); LuaObject.newindex_func = (LuaFunction)luaState.doString(str); LuaObject.index_func = (LuaFunction)luaState.doString(str2); LuaDLL.lua_createtable(l, 0, 4); LuaObject.addMember(l, new LuaCSFunction(LuaObject.ToString)); LuaObject.addMember(l, new LuaCSFunction(LuaObject.GetHashCode)); LuaObject.addMember(l, new LuaCSFunction(LuaObject.Equals)); LuaObject.addMember(l, new LuaCSFunction(LuaObject.GetType)); LuaDLL.lua_setfield(l, LuaIndexes.LUA_REGISTRYINDEX, "__luabaseobject"); LuaArray.init(l); LuaVarObject.init(l); LuaDLL.lua_newtable(l); LuaDLL.lua_setglobal(l, "__LuaDelegate"); LuaObject.setupPushVar(); } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int ToString(IntPtr l) { int result; try { object obj = LuaObject.checkVar(l, 1); LuaObject.pushValue(l, true); LuaObject.pushValue(l, obj.ToString()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetHashCode(IntPtr l) { int result; try { object obj = LuaObject.checkVar(l, 1); LuaObject.pushValue(l, true); LuaObject.pushValue(l, obj.GetHashCode()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Equals(IntPtr l) { int result; try { object obj = LuaObject.checkVar(l, 1); object obj2 = LuaObject.checkVar(l, 2); LuaObject.pushValue(l, true); LuaObject.pushValue(l, obj.Equals(obj2)); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetType(IntPtr l) { int result; try { object obj = LuaObject.checkVar(l, 1); LuaObject.pushValue(l, true); LuaObject.pushObject(l, obj.GetType()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } private static void setupPushVar() { LuaObject.typePushMap.set_Item(typeof(float), delegate(IntPtr L, object o) { LuaDLL.lua_pushnumber(L, (double)((float)o)); }); LuaObject.typePushMap.set_Item(typeof(double), delegate(IntPtr L, object o) { LuaDLL.lua_pushnumber(L, (double)o); }); LuaObject.typePushMap.set_Item(typeof(int), delegate(IntPtr L, object o) { LuaDLL.lua_pushinteger(L, (long)((int)o)); }); LuaObject.typePushMap.set_Item(typeof(uint), delegate(IntPtr L, object o) { LuaDLL.lua_pushnumber(L, Convert.ToUInt32(o)); }); LuaObject.typePushMap.set_Item(typeof(short), delegate(IntPtr L, object o) { LuaDLL.lua_pushinteger(L, (long)((short)o)); }); LuaObject.typePushMap.set_Item(typeof(ushort), delegate(IntPtr L, object o) { LuaDLL.lua_pushinteger(L, (long)((ushort)o)); }); LuaObject.typePushMap.set_Item(typeof(sbyte), delegate(IntPtr L, object o) { LuaDLL.lua_pushinteger(L, (long)((sbyte)o)); }); LuaObject.typePushMap.set_Item(typeof(byte), delegate(IntPtr L, object o) { LuaDLL.lua_pushinteger(L, (long)((byte)o)); }); Dictionary<Type, LuaObject.PushVarDelegate> arg_1CB_0 = LuaObject.typePushMap; Type arg_1CB_1 = typeof(long); LuaObject.PushVarDelegate pushVarDelegate = delegate(IntPtr L, object o) { LuaDLL.lua_pushinteger(L, (long)o); }; LuaObject.typePushMap.set_Item(typeof(ulong), pushVarDelegate); arg_1CB_0.set_Item(arg_1CB_1, pushVarDelegate); LuaObject.typePushMap.set_Item(typeof(string), delegate(IntPtr L, object o) { LuaDLL.lua_pushstring(L, (string)o); }); LuaObject.typePushMap.set_Item(typeof(bool), delegate(IntPtr L, object o) { LuaDLL.lua_pushboolean(L, (bool)o); }); Dictionary<Type, LuaObject.PushVarDelegate> arg_28C_0 = LuaObject.typePushMap; Type arg_28C_1 = typeof(LuaTable); pushVarDelegate = delegate(IntPtr L, object o) { ((LuaVar)o).push(L); }; LuaObject.typePushMap.set_Item(typeof(LuaThread), pushVarDelegate); pushVarDelegate = pushVarDelegate; LuaObject.typePushMap.set_Item(typeof(LuaFunction), pushVarDelegate); arg_28C_0.set_Item(arg_28C_1, pushVarDelegate); LuaObject.typePushMap.set_Item(typeof(Vector3), delegate(IntPtr L, object o) { LuaObject.pushValue(L, (Vector3)o); }); LuaObject.typePushMap.set_Item(typeof(Vector2), delegate(IntPtr L, object o) { LuaObject.pushValue(L, (Vector2)o); }); LuaObject.typePushMap.set_Item(typeof(Vector4), delegate(IntPtr L, object o) { LuaObject.pushValue(L, (Vector4)o); }); LuaObject.typePushMap.set_Item(typeof(Quaternion), delegate(IntPtr L, object o) { LuaObject.pushValue(L, (Quaternion)o); }); LuaObject.typePushMap.set_Item(typeof(Color), delegate(IntPtr L, object o) { LuaObject.pushValue(L, (Color)o); }); LuaObject.typePushMap.set_Item(typeof(LuaCSFunction), delegate(IntPtr L, object o) { LuaObject.pushValue(L, (LuaCSFunction)o); }); } private static int getOpFunction(IntPtr l, string f, string tip) { int result = LuaObject.pushTry(l); LuaObject.checkLuaObject(l, 1); while (!LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_getfield(l, -1, f); if (!LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_remove(l, -2); break; } LuaDLL.lua_pop(l, 1); LuaDLL.lua_getfield(l, -1, "__parent"); LuaDLL.lua_remove(l, -2); } if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); throw new Exception(string.Format("No {0} operator", tip)); } return result; } private static int luaOp(IntPtr l, string f, string tip) { int opFunction = LuaObject.getOpFunction(l, f, tip); LuaDLL.lua_pushvalue(l, 1); LuaDLL.lua_pushvalue(l, 2); if (LuaDLL.lua_pcall(l, 2, 1, opFunction) != 0) { LuaDLL.lua_pop(l, 1); } LuaDLL.lua_remove(l, opFunction); LuaObject.pushValue(l, true); LuaDLL.lua_insert(l, -2); return 2; } private static int luaUnaryOp(IntPtr l, string f, string tip) { int opFunction = LuaObject.getOpFunction(l, f, tip); LuaDLL.lua_pushvalue(l, 1); if (LuaDLL.lua_pcall(l, 1, 1, opFunction) != 0) { LuaDLL.lua_pop(l, 1); } LuaDLL.lua_remove(l, opFunction); LuaObject.pushValue(l, true); LuaDLL.lua_insert(l, -2); return 2; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaAdd(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_Addition", "add"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaSub(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_Subtraction", "sub"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaMul(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_Multiply", "mul"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaDiv(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_Division", "div"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaUnm(IntPtr l) { int result; try { result = LuaObject.luaUnaryOp(l, "op_UnaryNegation", "unm"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaEq(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_Equality", "eq"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaLt(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_LessThan", "lt"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaLe(IntPtr l) { int result; try { result = LuaObject.luaOp(l, "op_LessThanOrEqual", "le"); } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void getEnumTable(IntPtr l, string t) { LuaObject.newTypeTable(l, t); } public static void getTypeTable(IntPtr l, string t) { LuaObject.newTypeTable(l, t); LuaDLL.lua_newtable(l); LuaDLL.lua_newtable(l); } public static void newTypeTable(IntPtr l, string name) { string[] array = name.Split(new char[] { '.' }); LuaDLL.lua_pushglobaltable(l); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string str = array2[i]; LuaDLL.lua_pushstring(l, str); LuaDLL.lua_rawget(l, -2); if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); LuaDLL.lua_createtable(l, 0, 0); LuaDLL.lua_pushstring(l, str); LuaDLL.lua_pushvalue(l, -2); LuaDLL.lua_rawset(l, -4); } LuaDLL.lua_remove(l, -2); } } public static void createTypeMetatable(IntPtr l, Type self) { LuaObject.createTypeMetatable(l, null, self, null); } public static void createTypeMetatable(IntPtr l, LuaCSFunction con, Type self) { LuaObject.createTypeMetatable(l, con, self, null); } private static void checkMethodValid(LuaCSFunction f) { } public static void createTypeMetatable(IntPtr l, LuaCSFunction con, Type self, Type parent) { LuaObject.checkMethodValid(con); if (parent != null && parent != typeof(object) && parent != typeof(ValueType)) { LuaDLL.lua_pushstring(l, "__parent"); LuaDLL.luaL_getmetatable(l, ObjectCache.getAQName(parent)); LuaDLL.lua_rawset(l, -3); LuaDLL.lua_pushstring(l, "__parent"); LuaDLL.luaL_getmetatable(l, parent.get_FullName()); LuaDLL.lua_rawset(l, -4); } else { LuaDLL.lua_pushstring(l, "__parent"); LuaDLL.luaL_getmetatable(l, "__luabaseobject"); LuaDLL.lua_rawset(l, -3); } LuaObject.completeInstanceMeta(l, self); LuaObject.completeTypeMeta(l, con, self); LuaDLL.lua_pop(l, 1); } private static void completeTypeMeta(IntPtr l, LuaCSFunction con, Type self) { LuaDLL.lua_pushstring(l, ObjectCache.getAQName(self)); LuaDLL.lua_setfield(l, -3, "__fullname"); LuaObject.index_func.push(l); LuaDLL.lua_setfield(l, -2, "__index"); LuaObject.newindex_func.push(l); LuaDLL.lua_setfield(l, -2, "__newindex"); if (con == null) { con = new LuaCSFunction(LuaObject.noConstructor); } LuaObject.pushValue(l, con); LuaDLL.lua_setfield(l, -2, "__call"); LuaDLL.lua_pushcfunction(l, new LuaCSFunction(LuaObject.typeToString)); LuaDLL.lua_setfield(l, -2, "__tostring"); LuaDLL.lua_pushvalue(l, -1); LuaDLL.lua_setmetatable(l, -3); LuaDLL.lua_setfield(l, LuaIndexes.LUA_REGISTRYINDEX, self.get_FullName()); } private static void completeInstanceMeta(IntPtr l, Type self) { LuaDLL.lua_pushstring(l, "__typename"); LuaDLL.lua_pushstring(l, self.get_Name()); LuaDLL.lua_rawset(l, -3); LuaObject.index_func.push(l); LuaDLL.lua_setfield(l, -2, "__index"); LuaObject.newindex_func.push(l); LuaDLL.lua_setfield(l, -2, "__newindex"); LuaObject.pushValue(l, LuaObject.lua_add); LuaDLL.lua_setfield(l, -2, "__add"); LuaObject.pushValue(l, LuaObject.lua_sub); LuaDLL.lua_setfield(l, -2, "__sub"); LuaObject.pushValue(l, LuaObject.lua_mul); LuaDLL.lua_setfield(l, -2, "__mul"); LuaObject.pushValue(l, LuaObject.lua_div); LuaDLL.lua_setfield(l, -2, "__div"); LuaObject.pushValue(l, LuaObject.lua_unm); LuaDLL.lua_setfield(l, -2, "__unm"); LuaObject.pushValue(l, LuaObject.lua_eq); LuaDLL.lua_setfield(l, -2, "__eq"); LuaObject.pushValue(l, LuaObject.lua_le); LuaDLL.lua_setfield(l, -2, "__le"); LuaObject.pushValue(l, LuaObject.lua_lt); LuaDLL.lua_setfield(l, -2, "__lt"); LuaObject.pushValue(l, LuaObject.lua_tostring); LuaDLL.lua_setfield(l, -2, "__tostring"); LuaDLL.lua_pushcfunction(l, LuaObject.lua_gc); LuaDLL.lua_setfield(l, -2, "__gc"); if (self.get_IsValueType() && LuaObject.isImplByLua(self)) { LuaDLL.lua_pushvalue(l, -1); LuaDLL.lua_setglobal(l, self.get_FullName() + ".Instance"); } LuaDLL.lua_setfield(l, LuaIndexes.LUA_REGISTRYINDEX, ObjectCache.getAQName(self)); } public static bool isImplByLua(Type t) { return t == typeof(Color) || t == typeof(Vector2) || t == typeof(Vector3) || t == typeof(Vector4) || t == typeof(Quaternion); } public static void reg(IntPtr l, LuaCSFunction func, string ns) { LuaObject.checkMethodValid(func); LuaObject.newTypeTable(l, ns); LuaObject.pushValue(l, func); LuaDLL.lua_setfield(l, -2, func.get_Method().get_Name()); LuaDLL.lua_pop(l, 1); } protected static void addMember(IntPtr l, LuaCSFunction func) { LuaObject.checkMethodValid(func); LuaObject.pushValue(l, func); string text = func.get_Method().get_Name(); if (text.EndsWith("_s")) { text = text.Substring(0, text.get_Length() - 2); LuaDLL.lua_setfield(l, -3, text); } else { LuaDLL.lua_setfield(l, -2, text); } } protected static void addMember(IntPtr l, LuaCSFunction func, bool instance) { LuaObject.checkMethodValid(func); LuaObject.pushValue(l, func); string name = func.get_Method().get_Name(); LuaDLL.lua_setfield(l, (!instance) ? -3 : -2, name); } protected static void addMember(IntPtr l, string name, LuaCSFunction get, LuaCSFunction set, bool instance) { LuaObject.checkMethodValid(get); LuaObject.checkMethodValid(set); int stackPos = (!instance) ? -3 : -2; LuaDLL.lua_createtable(l, 2, 0); if (get == null) { LuaDLL.lua_pushnil(l); } else { LuaObject.pushValue(l, get); } LuaDLL.lua_rawseti(l, -2, 1L); if (set == null) { LuaDLL.lua_pushnil(l); } else { LuaObject.pushValue(l, set); } LuaDLL.lua_rawseti(l, -2, 2L); LuaDLL.lua_setfield(l, stackPos, name); } protected static void addMember(IntPtr l, int v, string name) { LuaDLL.lua_pushinteger(l, (long)v); LuaDLL.lua_setfield(l, -2, name); } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int luaGC(IntPtr l) { int num = LuaDLL.luaS_rawnetobj(l, 1); if (num > 0) { ObjectCache objectCache = ObjectCache.get(l); objectCache.gc(num); } return 0; } internal static void gc(IntPtr l, int p, Object o) { LuaDLL.lua_pushnil(l); LuaDLL.lua_setmetatable(l, p); ObjectCache objectCache = ObjectCache.get(l); objectCache.gc(o); } public static void checkLuaObject(IntPtr l, int p) { LuaDLL.lua_getmetatable(l, p); if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); throw new Exception("expect luaobject as first argument"); } } public static void pushObject(IntPtr l, object o) { ObjectCache objectCache = ObjectCache.get(l); objectCache.push(l, o); } public static void pushObject(IntPtr l, Array o) { ObjectCache objectCache = ObjectCache.get(l); objectCache.push(l, o); } public static void pushLightObject(IntPtr l, object t) { ObjectCache objectCache = ObjectCache.get(l); objectCache.push(l, t, false, false); } public static int pushTry(IntPtr l) { if (!LuaState.get(l).isMainThread()) { SluaLogger.LogError("Can't call lua function in bg thread"); return 0; } LuaDLL.lua_pushcfunction(l, LuaState.errorFunc); return LuaDLL.lua_gettop(l); } public static bool matchType(IntPtr l, int p, LuaTypes lt, Type t) { if (t == typeof(object)) { return true; } if (t == typeof(Type) && LuaObject.isTypeTable(l, p)) { return true; } if (t == typeof(char[]) || t == typeof(byte[])) { return lt == LuaTypes.LUA_TSTRING; } switch (lt) { case LuaTypes.LUA_TNIL: return !t.get_IsValueType() && !t.get_IsPrimitive(); case LuaTypes.LUA_TBOOLEAN: return t == typeof(bool); case LuaTypes.LUA_TNUMBER: return t.get_IsPrimitive() || t.get_IsEnum(); case LuaTypes.LUA_TSTRING: return t == typeof(string); case LuaTypes.LUA_TTABLE: if (t == typeof(LuaTable) || t.get_IsArray()) { return true; } if (t.get_IsValueType()) { return LuaObject.luaTypeCheck(l, p, t.get_Name()); } return LuaDLL.luaS_subclassof(l, p, t.get_Name()) == 1; case LuaTypes.LUA_TFUNCTION: return t == typeof(LuaFunction) || t.get_BaseType() == typeof(MulticastDelegate); case LuaTypes.LUA_TUSERDATA: { object obj = LuaObject.checkObj(l, p); Type type = obj.GetType(); return type == t || type.IsSubclassOf(t); } case LuaTypes.LUA_TTHREAD: return t == typeof(LuaThread); } return false; } public static bool isTypeTable(IntPtr l, int p) { if (LuaDLL.lua_type(l, p) != LuaTypes.LUA_TTABLE) { return false; } LuaDLL.lua_pushstring(l, "__fullname"); LuaDLL.lua_rawget(l, p); if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); return false; } return true; } public static bool isLuaClass(IntPtr l, int p) { return LuaDLL.luaS_subclassof(l, p, null) == 1; } private static bool isLuaValueType(IntPtr l, int p) { return LuaDLL.luaS_checkluatype(l, p, null) == 1; } public static bool matchType(IntPtr l, int p, Type t1) { LuaTypes lt = LuaDLL.lua_type(l, p); return LuaObject.matchType(l, p, lt, t1); } public static bool matchType(IntPtr l, int total, int from, Type t1) { return total - from + 1 == 1 && LuaObject.matchType(l, from, t1); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2) { return total - from + 1 == 2 && LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3) { return total - from + 1 == 3 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2)) && LuaObject.matchType(l, from + 2, t3); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4) { return total - from + 1 == 4 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3)) && LuaObject.matchType(l, from + 3, t4); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5) { return total - from + 1 == 5 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3) && LuaObject.matchType(l, from + 3, t4)) && LuaObject.matchType(l, from + 4, t5); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5, Type t6) { return total - from + 1 == 6 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3) && LuaObject.matchType(l, from + 3, t4) && LuaObject.matchType(l, from + 4, t5)) && LuaObject.matchType(l, from + 5, t6); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5, Type t6, Type t7) { return total - from + 1 == 7 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3) && LuaObject.matchType(l, from + 3, t4) && LuaObject.matchType(l, from + 4, t5) && LuaObject.matchType(l, from + 5, t6)) && LuaObject.matchType(l, from + 6, t7); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5, Type t6, Type t7, Type t8) { return total - from + 1 == 8 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3) && LuaObject.matchType(l, from + 3, t4) && LuaObject.matchType(l, from + 4, t5) && LuaObject.matchType(l, from + 5, t6) && LuaObject.matchType(l, from + 6, t7)) && LuaObject.matchType(l, from + 7, t8); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5, Type t6, Type t7, Type t8, Type t9) { return total - from + 1 == 9 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3) && LuaObject.matchType(l, from + 3, t4) && LuaObject.matchType(l, from + 4, t5) && LuaObject.matchType(l, from + 5, t6) && LuaObject.matchType(l, from + 6, t7) && LuaObject.matchType(l, from + 7, t8)) && LuaObject.matchType(l, from + 8, t9); } public static bool matchType(IntPtr l, int total, int from, Type t1, Type t2, Type t3, Type t4, Type t5, Type t6, Type t7, Type t8, Type t9, Type t10) { return total - from + 1 == 10 && (LuaObject.matchType(l, from, t1) && LuaObject.matchType(l, from + 1, t2) && LuaObject.matchType(l, from + 2, t3) && LuaObject.matchType(l, from + 3, t4) && LuaObject.matchType(l, from + 4, t5) && LuaObject.matchType(l, from + 5, t6) && LuaObject.matchType(l, from + 6, t7) && LuaObject.matchType(l, from + 7, t8) && LuaObject.matchType(l, from + 8, t9)) && LuaObject.matchType(l, from + 9, t10); } public static bool matchType(IntPtr l, int total, int from, ParameterInfo[] pars) { if (total - from + 1 != pars.Length) { return false; } for (int i = 0; i < pars.Length; i++) { int num = i + from; LuaTypes lt = LuaDLL.lua_type(l, num); if (!LuaObject.matchType(l, num, lt, pars[i].get_ParameterType())) { return false; } } return true; } public static bool luaTypeCheck(IntPtr l, int p, string t) { return LuaDLL.luaS_checkluatype(l, p, t) != 0; } private static LuaDelegate newDelegate(IntPtr l, int p) { LuaState luaState = LuaState.get(l); LuaDLL.lua_pushvalue(l, p); int num = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX); LuaDelegate luaDelegate = new LuaDelegate(l, num); LuaDLL.lua_pushvalue(l, p); LuaDLL.lua_pushinteger(l, (long)num); LuaDLL.lua_settable(l, -3); luaState.delgateMap[num] = luaDelegate; return luaDelegate; } public static void removeDelgate(IntPtr l, int r) { LuaDLL.lua_getglobal(l, "__LuaDelegate"); LuaDLL.lua_getref(l, r); LuaDLL.lua_pushnil(l); LuaDLL.lua_settable(l, -3); LuaDLL.lua_pop(l, 1); } public static object checkObj(IntPtr l, int p) { ObjectCache objectCache = ObjectCache.get(l); return objectCache.get(l, p); } public static bool checkArray<T>(IntPtr l, int p, out T[] ta) { if (LuaDLL.lua_type(l, p) == LuaTypes.LUA_TTABLE) { int num = LuaDLL.lua_rawlen(l, p); ta = new T[num]; for (int i = 0; i < num; i++) { LuaDLL.lua_rawgeti(l, p, (long)(i + 1)); ta[i] = (T)((object)Convert.ChangeType(LuaObject.checkVar(l, -1), typeof(T))); LuaDLL.lua_pop(l, 1); } return true; } Array array = LuaObject.checkObj(l, p) as Array; ta = (array as T[]); return ta != null; } public static bool checkParams<T>(IntPtr l, int p, out T[] pars) where T : class { int num = LuaDLL.lua_gettop(l); if (num - p >= 0) { pars = new T[num - p + 1]; int i = p; int num2 = 0; while (i <= num) { LuaObject.checkType<T>(l, i, out pars[num2]); i++; num2++; } return true; } pars = new T[0]; return true; } public static bool checkValueParams<T>(IntPtr l, int p, out T[] pars) where T : struct { int num = LuaDLL.lua_gettop(l); if (num - p >= 0) { pars = new T[num - p + 1]; int i = p; int num2 = 0; while (i <= num) { LuaObject.checkValueType<T>(l, i, out pars[num2]); i++; num2++; } return true; } pars = new T[0]; return true; } public static bool checkParams(IntPtr l, int p, out float[] pars) { int num = LuaDLL.lua_gettop(l); if (num - p >= 0) { pars = new float[num - p + 1]; int i = p; int num2 = 0; while (i <= num) { LuaObject.checkType(l, i, out pars[num2]); i++; num2++; } return true; } pars = new float[0]; return true; } public static bool checkParams(IntPtr l, int p, out int[] pars) { int num = LuaDLL.lua_gettop(l); if (num - p >= 0) { pars = new int[num - p + 1]; int i = p; int num2 = 0; while (i <= num) { LuaObject.checkType(l, i, out pars[num2]); i++; num2++; } return true; } pars = new int[0]; return true; } public static bool checkParams(IntPtr l, int p, out string[] pars) { int num = LuaDLL.lua_gettop(l); if (num - p >= 0) { pars = new string[num - p + 1]; int i = p; int num2 = 0; while (i <= num) { LuaObject.checkType(l, i, out pars[num2]); i++; num2++; } return true; } pars = new string[0]; return true; } public static bool checkParams(IntPtr l, int p, out char[] pars) { LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TSTRING); string text; LuaObject.checkType(l, p, out text); pars = text.ToCharArray(); return true; } public static object checkVar(IntPtr l, int p, Type t) { object obj = LuaObject.checkVar(l, p); object result; try { result = ((obj != null) ? Convert.ChangeType(obj, t) : null); } catch (Exception) { throw new Exception(string.Format("parameter {0} expected {1}, got {2}", p, t.get_Name(), (obj != null) ? obj.GetType().get_Name() : "null")); } return result; } public static object checkVar(IntPtr l, int p) { switch (LuaDLL.lua_type(l, p)) { case LuaTypes.LUA_TBOOLEAN: return LuaDLL.lua_toboolean(l, p); case LuaTypes.LUA_TNUMBER: return LuaDLL.lua_tonumber(l, p); case LuaTypes.LUA_TSTRING: return LuaDLL.lua_tostring(l, p); case LuaTypes.LUA_TTABLE: if (LuaObject.isLuaValueType(l, p)) { if (LuaObject.luaTypeCheck(l, p, "Vector2")) { Vector2 vector; LuaObject.checkType(l, p, out vector); return vector; } if (LuaObject.luaTypeCheck(l, p, "Vector3")) { Vector3 vector2; LuaObject.checkType(l, p, out vector2); return vector2; } if (LuaObject.luaTypeCheck(l, p, "Vector4")) { Vector4 vector3; LuaObject.checkType(l, p, out vector3); return vector3; } if (LuaObject.luaTypeCheck(l, p, "Quaternion")) { Quaternion quaternion; LuaObject.checkType(l, p, out quaternion); return quaternion; } if (LuaObject.luaTypeCheck(l, p, "Color")) { Color color; LuaObject.checkType(l, p, out color); return color; } SluaLogger.LogError("unknown lua value type"); return null; } else { if (LuaObject.isLuaClass(l, p)) { return LuaObject.checkObj(l, p); } LuaTable result; LuaObject.checkType(l, p, out result); return result; } break; case LuaTypes.LUA_TFUNCTION: { LuaFunction result2; LuaObject.checkType(l, p, out result2); return result2; } case LuaTypes.LUA_TUSERDATA: return LuaObject.checkObj(l, p); case LuaTypes.LUA_TTHREAD: { LuaThread result3; LuaObject.checkType(l, p, out result3); return result3; } } return null; } public static void pushValue(IntPtr l, object o) { LuaObject.pushVar(l, o); } public static void pushValue(IntPtr l, Object[] o) { if (o == null) { LuaDLL.lua_pushnil(l); return; } LuaDLL.lua_newtable(l); for (int i = 0; i < o.Length; i++) { LuaObject.pushValue(l, o[i]); LuaDLL.lua_rawseti(l, -2, (long)(i + 1)); } } public static void pushVar(IntPtr l, object o) { if (o == null) { LuaDLL.lua_pushnil(l); return; } Type type = o.GetType(); LuaObject.PushVarDelegate pushVarDelegate; if (LuaObject.typePushMap.TryGetValue(type, ref pushVarDelegate)) { pushVarDelegate(l, o); } else if (type.get_IsEnum()) { LuaObject.pushEnum(l, Convert.ToInt32(o)); } else if (type.get_IsArray()) { LuaObject.pushObject(l, (Array)o); } else { LuaObject.pushObject(l, o); } } public static T checkSelf<T>(IntPtr l) { object obj = LuaObject.checkObj(l, 1); if (obj != null) { return (T)((object)obj); } throw new Exception("arg 1 expect self, but get null"); } public static object checkSelf(IntPtr l) { object obj = LuaObject.checkObj(l, 1); if (obj == null) { throw new Exception("expect self, but get null"); } return obj; } public static void setBack(IntPtr l, object o) { ObjectCache objectCache = ObjectCache.get(l); objectCache.setBack(l, 1, o); } public static void setBack(IntPtr l, Vector3 v) { LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, v.z, float.NaN); } public static void setBack(IntPtr l, Vector2 v) { LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, float.NaN, float.NaN); } public static void setBack(IntPtr l, Vector4 v) { LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, v.z, v.w); } public static void setBack(IntPtr l, Quaternion v) { LuaDLL.luaS_setDataVec(l, 1, v.x, v.y, v.z, v.w); } public static void setBack(IntPtr l, Color v) { LuaDLL.luaS_setDataVec(l, 1, v.r, v.g, v.b, v.a); } public static int extractFunction(IntPtr l, int p) { int result = 0; switch (LuaDLL.lua_type(l, p)) { case LuaTypes.LUA_TNIL: case LuaTypes.LUA_TUSERDATA: result = 0; return result; case LuaTypes.LUA_TTABLE: LuaDLL.lua_rawgeti(l, p, 1L); LuaDLL.lua_pushstring(l, "+="); if (LuaDLL.lua_rawequal(l, -1, -2) == 1) { result = 1; } else { result = 2; } LuaDLL.lua_pop(l, 2); LuaDLL.lua_rawgeti(l, p, 2L); return result; case LuaTypes.LUA_TFUNCTION: LuaDLL.lua_pushvalue(l, p); return result; } throw new Exception("expect valid Delegate"); } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int noConstructor(IntPtr l) { return LuaObject.error(l, "Can't new this object"); } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int typeToString(IntPtr l) { LuaDLL.lua_pushstring(l, "__fullname"); LuaDLL.lua_rawget(l, -2); return 1; } public static int error(IntPtr l, Exception e) { LuaDLL.lua_pushboolean(l, false); LuaDLL.lua_pushstring(l, e.ToString()); return 2; } public static int error(IntPtr l, string err) { LuaDLL.lua_pushboolean(l, false); LuaDLL.lua_pushstring(l, err); return 2; } public static int error(IntPtr l, string err, params object[] args) { err = string.Format(err, args); LuaDLL.lua_pushboolean(l, false); LuaDLL.lua_pushstring(l, err); return 2; } public static int ok(IntPtr l) { LuaDLL.lua_pushboolean(l, true); return 1; } public static int ok(IntPtr l, int retCount) { LuaDLL.lua_pushboolean(l, true); LuaDLL.lua_insert(l, -(retCount + 1)); return retCount + 1; } public static void assert(bool cond, string err) { if (!cond) { throw new Exception(err); } } public static bool checkEnum<T>(IntPtr l, int p, out T o) where T : struct { int num = (int)LuaDLL.luaL_checkinteger(l, p); o = (T)((object)Enum.ToObject(typeof(T), num)); return true; } public static void pushEnum(IntPtr l, int e) { LuaObject.pushValue(l, e); } public static bool checkType(IntPtr l, int p, out sbyte v) { v = (sbyte)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, sbyte v) { LuaDLL.lua_pushinteger(l, (long)v); } public static bool checkType(IntPtr l, int p, out byte v) { v = (byte)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, byte i) { LuaDLL.lua_pushinteger(l, (long)i); } public static bool checkType(IntPtr l, int p, out char c) { c = (char)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, char v) { LuaDLL.lua_pushinteger(l, (long)v); } public static bool checkArray(IntPtr l, int p, out char[] pars) { LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TSTRING); string text; LuaObject.checkType(l, p, out text); pars = text.ToCharArray(); return true; } public static bool checkType(IntPtr l, int p, out short v) { v = (short)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, short i) { LuaDLL.lua_pushinteger(l, (long)i); } public static bool checkType(IntPtr l, int p, out ushort v) { v = (ushort)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, ushort v) { LuaDLL.lua_pushinteger(l, (long)v); } public static bool checkType(IntPtr l, int p, out int v) { v = (int)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, int i) { LuaDLL.lua_pushinteger(l, (long)i); } public static bool checkType(IntPtr l, int p, out uint v) { v = (uint)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, uint o) { LuaDLL.lua_pushinteger(l, (long)((ulong)o)); } public static bool checkType(IntPtr l, int p, out long v) { v = LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, long i) { LuaDLL.lua_pushinteger(l, i); } public static bool checkType(IntPtr l, int p, out ulong v) { v = (ulong)LuaDLL.luaL_checkinteger(l, p); return true; } public static void pushValue(IntPtr l, ulong o) { LuaDLL.lua_pushinteger(l, (long)o); } public static bool checkType(IntPtr l, int p, out float v) { v = (float)LuaDLL.luaL_checknumber(l, p); return true; } public static void pushValue(IntPtr l, float o) { LuaDLL.lua_pushnumber(l, (double)o); } public static bool checkType(IntPtr l, int p, out double v) { v = LuaDLL.luaL_checknumber(l, p); return true; } public static void pushValue(IntPtr l, double d) { LuaDLL.lua_pushnumber(l, d); } public static bool checkType(IntPtr l, int p, out bool v) { LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TBOOLEAN); v = LuaDLL.lua_toboolean(l, p); return true; } public static void pushValue(IntPtr l, bool b) { LuaDLL.lua_pushboolean(l, b); } public static bool checkType(IntPtr l, int p, out string v) { if (LuaDLL.lua_isuserdata(l, p) > 0) { object obj = LuaObject.checkObj(l, p); if (obj is string) { v = (obj as string); return true; } } else if (LuaDLL.lua_isstring(l, p)) { v = LuaDLL.lua_tostring(l, p); return true; } v = null; return false; } public static bool checkBinaryString(IntPtr l, int p, out byte[] bytes) { if (LuaDLL.lua_isstring(l, p)) { bytes = LuaDLL.lua_tobytes(l, p); return true; } bytes = null; return false; } public static void pushValue(IntPtr l, string s) { LuaDLL.lua_pushstring(l, s); } public static bool checkType(IntPtr l, int p, out IntPtr v) { v = LuaDLL.lua_touserdata(l, p); return true; } public static bool checkType(IntPtr l, int p, out LuaDelegate f) { LuaState luaState = LuaState.get(l); p = LuaDLL.lua_absindex(l, p); LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION); LuaDLL.lua_getglobal(l, "__LuaDelegate"); LuaDLL.lua_pushvalue(l, p); LuaDLL.lua_gettable(l, -2); if (LuaDLL.lua_isnil(l, -1)) { LuaDLL.lua_pop(l, 1); f = LuaObject.newDelegate(l, p); } else { int key = LuaDLL.lua_tointeger(l, -1); LuaDLL.lua_pop(l, 1); f = luaState.delgateMap[key]; if (f == null) { f = LuaObject.newDelegate(l, p); } } LuaDLL.lua_pop(l, 1); return true; } public static bool checkType(IntPtr l, int p, out LuaThread lt) { if (LuaDLL.lua_isnil(l, p)) { lt = null; return true; } LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TTHREAD); LuaDLL.lua_pushvalue(l, p); int r = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX); lt = new LuaThread(l, r); return true; } public static bool checkType(IntPtr l, int p, out LuaFunction f) { if (LuaDLL.lua_isnil(l, p)) { f = null; return true; } LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TFUNCTION); LuaDLL.lua_pushvalue(l, p); int r = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX); f = new LuaFunction(l, r); return true; } public static bool checkType(IntPtr l, int p, out LuaTable t) { if (LuaDLL.lua_isnil(l, p)) { t = null; return true; } LuaDLL.luaL_checktype(l, p, LuaTypes.LUA_TTABLE); LuaDLL.lua_pushvalue(l, p); int r = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX); t = new LuaTable(l, r); return true; } public static void pushValue(IntPtr l, LuaCSFunction f) { LuaState.pushcsfunction(l, f); } public static void pushValue(IntPtr l, LuaTable t) { if (t == null) { LuaDLL.lua_pushnil(l); } else { t.push(l); } } public static Type FindType(string qualifiedTypeName) { Type type = Type.GetType(qualifiedTypeName); if (type != null) { return type; } Assembly[] assemblies = AppDomain.get_CurrentDomain().GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Assembly assembly = assemblies[i]; type = assembly.GetType(qualifiedTypeName); if (type != null) { return type; } } return null; } public static bool checkType(IntPtr l, int p, out Type t) { string text = null; LuaTypes luaTypes = LuaDLL.lua_type(l, p); switch (luaTypes) { case LuaTypes.LUA_TSTRING: LuaObject.checkType(l, p, out text); break; case LuaTypes.LUA_TTABLE: LuaDLL.lua_pushstring(l, "__type"); LuaDLL.lua_rawget(l, p); if (!LuaDLL.lua_isnil(l, -1)) { t = (Type)LuaObject.checkObj(l, -1); LuaDLL.lua_pop(l, 1); return true; } LuaDLL.lua_pushstring(l, "__fullname"); LuaDLL.lua_rawget(l, p); text = LuaDLL.lua_tostring(l, -1); LuaDLL.lua_pop(l, 2); break; case LuaTypes.LUA_TUSERDATA: { object obj = LuaObject.checkObj(l, p); if (obj.GetType() != LuaObject.MonoType) { throw new Exception(string.Format("{0} expect Type, got {1}", p, obj.GetType().get_Name())); } t = (Type)obj; return true; } } if (text == null) { throw new Exception("expect string or type table"); } t = LuaObject.FindType(text); if (t != null && luaTypes == LuaTypes.LUA_TTABLE) { LuaDLL.lua_pushstring(l, "__type"); LuaObject.pushLightObject(l, t); LuaDLL.lua_rawset(l, p); } return t != null; } public static bool checkValueType<T>(IntPtr l, int p, out T v) where T : struct { v = (T)((object)LuaObject.checkObj(l, p)); return true; } public static bool checkNullable<T>(IntPtr l, int p, out T? v) where T : struct { if (LuaDLL.lua_isnil(l, p)) { v = default(T?); } else { object obj = LuaObject.checkVar(l, p, typeof(T)); if (obj == null) { v = default(T?); } else { v = new T?((T)((object)obj)); } } return true; } public static bool checkType<T>(IntPtr l, int p, out T o) where T : class { object obj = LuaObject.checkVar(l, p); if (obj == null) { o = (T)((object)null); return true; } o = (obj as T); if (o == null) { throw new Exception(string.Format("arg {0} is not type of {1}", p, typeof(T).get_Name())); } return true; } public static bool checkType(IntPtr l, int p, out Vector4 v) { float num; float num2; float num3; float num4; if (LuaDLL.luaS_checkVector4(l, p, out num, out num2, out num3, out num4) != 0) { throw new Exception(string.Format("Invalid vector4 argument at {0}", p)); } v = new Vector4(num, num2, num3, num4); return true; } public static bool checkType(IntPtr l, int p, out Vector3 v) { float num; float num2; float num3; if (LuaDLL.luaS_checkVector3(l, p, out num, out num2, out num3) != 0) { throw new Exception(string.Format("Invalid vector3 argument at {0}", p)); } v = new Vector3(num, num2, num3); return true; } public static bool checkType(IntPtr l, int p, out Vector2 v) { float num; float num2; if (LuaDLL.luaS_checkVector2(l, p, out num, out num2) != 0) { throw new Exception(string.Format("Invalid vector2 argument at {0}", p)); } v = new Vector2(num, num2); return true; } public static bool checkType(IntPtr l, int p, out Quaternion q) { float num; float num2; float num3; float num4; if (LuaDLL.luaS_checkQuaternion(l, p, out num, out num2, out num3, out num4) != 0) { throw new Exception(string.Format("Invalid quaternion argument at {0}", p)); } q = new Quaternion(num, num2, num3, num4); return true; } public static bool checkType(IntPtr l, int p, out Color c) { float num; float num2; float num3; float num4; if (LuaDLL.luaS_checkColor(l, p, out num, out num2, out num3, out num4) != 0) { throw new Exception(string.Format("Invalid color argument at {0}", p)); } c = new Color(num, num2, num3, num4); return true; } public static bool checkType(IntPtr l, int p, out LayerMask lm) { int num; LuaObject.checkType(l, p, out num); lm = num; return true; } public static bool checkParams(IntPtr l, int p, out Vector2[] pars) { int num = LuaDLL.lua_gettop(l); if (num - p >= 0) { pars = new Vector2[num - p + 1]; int i = p; int num2 = 0; while (i <= num) { LuaObject.checkType(l, i, out pars[num2]); i++; num2++; } return true; } pars = new Vector2[0]; return true; } public static void pushValue(IntPtr l, RaycastHit2D r) { LuaObject.pushObject(l, r); } public static void pushValue(IntPtr l, RaycastHit r) { LuaObject.pushObject(l, r); } public static void pushValue(IntPtr l, AnimationState o) { if (o == null) { LuaDLL.lua_pushnil(l); } else { LuaObject.pushObject(l, o); } } public static void pushValue(IntPtr l, Object o) { if (o == null) { LuaDLL.lua_pushnil(l); } else { LuaObject.pushObject(l, o); } } public static void pushValue(IntPtr l, Quaternion o) { LuaDLL.luaS_pushQuaternion(l, o.x, o.y, o.z, o.w); } public static void pushValue(IntPtr l, Vector2 o) { LuaDLL.luaS_pushVector2(l, o.x, o.y); } public static void pushValue(IntPtr l, Vector3 o) { LuaDLL.luaS_pushVector3(l, o.x, o.y, o.z); } public static void pushValue(IntPtr l, Vector4 o) { LuaDLL.luaS_pushVector4(l, o.x, o.y, o.z, o.w); } public static void pushValue(IntPtr l, Color o) { LuaDLL.luaS_pushColor(l, o.r, o.g, o.b, o.a); } } }
using EPiServer.Events; namespace HansKindberg.EPiServer.Events.Providers { public interface IEventMessageReceiver { #region Methods void ReceiveMessage(EventMessage message); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoinBazaar.Infrastructure.MessageQueue { public interface IConnection:IDisposable { IChannel CreateChannel(); } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using TableTopCrucible.Domain.Models.Sources; using TableTopCrucible.Domain.Models.ValueTypes; using TableTopCrucible.Domain.Models.ValueTypes.IDs; namespace TableTopCrucible.Data.SaveFile.DataTransferObjects { [DataContract] public class DirectorySetupDTO : EntityDtoBase { [DataMember] public Uri Path { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Description { get; set; } public DirectorySetupDTO(DirectorySetup source) : base(source) { this.Path = source.Path; this.Name = (string)source.Name; this.Description = (string)source.Description; } public DirectorySetupDTO() { } public DirectorySetup ToEntity() => new DirectorySetup( Path, (DirectorySetupName)Name, (Description)Description, (DirectorySetupId)Id, Created, LastChange); } }
using PDV.DAO.Atributos; namespace PDV.DAO.Entidades.NFe { public class Finalidade { [CampoTabela("IDFINALIDADE")] public decimal IDFinalidade { get; set; } = -1; [CampoTabela("CODIGO")] public string Codigo { get; set; } [CampoTabela("DESCRICAO")] public string Descricao { get; set; } public Finalidade() { } } }
namespace GetMinionNames { using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { SqlConnection connection = new SqlConnection(@"Server = (localdb)\MSSQLLocalDB; Database = MinionsDB; Integrated Security = true;"); connection.Open(); Console.Write("Enter vilainId: "); int vilainId = int.Parse(Console.ReadLine()); string query = @"SELECT v.Name,m.Name FROM Viliains AS v INNER JOIN VillainsMinions AS vm ON v.Id = vm.VillainId INNER JOIN Minions AS m ON vm.MinionId = m.Id WHERE v.Id = @VilianId"; SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@VilianId", vilainId); using (connection) { var reader = command.ExecuteReader(); if(!reader.HasRows) { Console.WriteLine($"No viliain with ID {vilainId} exist in the database."); return; } else { reader.Read(); string villainName = reader[0].ToString(); Console.WriteLine($"Villain: {villainName}"); while(reader.Read()) { Console.WriteLine(reader[1]); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ljc.Com.CjzfNews.UI.Entity { public class RunconfigEntity { public const string TBName = "RunconfigEntity"; public const string DefaultConfig = "defaultset"; public string ConfigName { get; set; } public string ConfigValue { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CoreComponents.Text { public static class StringCopier { //public StringCopier() //{ //} public static void Copy(string StringFrom, out string StringTo) { StringTo = new string(StringFrom.ToCharArray()); } public static void Copy(string StringFrom, int StartIndex, out string StringTo) { StringTo = new string(StringFrom.ToCharArray(StartIndex, StringFrom.Length - (StartIndex + 1))); } public static void Copy(string StringFrom, int StartIndex, int Length, out string StringTo) { StringTo = new string(StringFrom.ToCharArray(StartIndex, Length)); } public static string Clone(string StringFrom) { return new string(StringFrom.ToCharArray()); } public static string CastClone(string StringFrom) { return (string)StringFrom.Clone(); } } }