text
stringlengths
13
6.01M
using System; using StardewValley; namespace FollowerNPC.Buffs { class ShaneBuff : CompanionBuff { public ShaneBuff(Farmer farmer, NPC npc, CompanionsManager manager) : base(farmer, npc, manager) { buff = new Buff(0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 30, "", ""); buff.description = "Shane may shun organic ingredients in favor of frozen pizza, but he's still good with chickens."+ Environment.NewLine+ "You gain +3 farming with Shane."; statBuffs = new Buff[1]; statBuffs[0] = new Buff(3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, "", ""); statBuffs[0].description = "+3 Farming" + Environment.NewLine + "Source: Shane"; } } }
using System; using System.Globalization; using System.Linq; using System.Windows.Data; namespace SylphyHorn.UI.Converters { public class ArrayToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return string.Join(parameter as string ?? ", ", value as object[]); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using System.Web.Mvc; using chat.Sources.Main; namespace chat.Controllers { [Authorize] public class FriendsController : Controller { [HttpGet] public ActionResult List() { return View(); } [HttpGet] public ActionResult Grid() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Search(FormCollection Collection) { return View(_Friends.SearchFriends(Collection)); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Add() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Remove() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Effigy.Entity.DBContext; namespace Effigy.Entity.DBContext { public class CityMapper : BaseEntity { public int Cityid { get; set; } public int StateId { get; set; } public string StateName { get; set; } public string CityName { get; set; } public string CountryName { get; set; } public bool IsActive { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; using RimWorld; using HarmonyLib; namespace Replace_Stuff.Utilities { public static class RemoveThingFromStatWorkerCache { //class StatDef { //private StatWorker workerInt; public static AccessTools.FieldRef<StatDef, StatWorker> workerInt = AccessTools.FieldRefAccess<StatDef, StatWorker>("workerInt"); //class StatWorker { //private Dictionary<Thing, StatCacheEntry> temporaryStatCache; //private Dictionary<Thing, float> immutableStatCache; public static AccessTools.FieldRef<StatWorker, Dictionary<Thing, StatCacheEntry>> temporaryStatCache = AccessTools.FieldRefAccess<StatWorker, Dictionary<Thing, StatCacheEntry>>("temporaryStatCache"); public static AccessTools.FieldRef<StatWorker, Dictionary<Thing, float>> immutableStatCache = AccessTools.FieldRefAccess<StatWorker, Dictionary<Thing, float>>("immutableStatCache"); public static void RemoveFromStatWorkerCaches(this Thing thing) { foreach (StatDef statDef in DefDatabase<StatDef>.AllDefsListForReading) { if (workerInt(statDef) is StatWorker worker) { if (temporaryStatCache(worker) is Dictionary<Thing, StatCacheEntry> tempCache) tempCache.Remove(thing); if (immutableStatCache(worker) is Dictionary<Thing, float> immuCache) immuCache.Remove(thing); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CGun : MonoBehaviour { public GameObject _originBullet = null; public ParticleSystem _muzzleParticle = null; //! 총알을 발사한다 public void ShootBullet(float power) { var bullet = Function.CreateCopiedGameObject<CBullet>("Bullet", _originBullet, CSceneManager.ObjectRoot); var direction = Quaternion.LookRotation(transform.right, transform.up); _muzzleParticle.Play(); bullet.transform.position = _muzzleParticle.transform.position; bullet.transform.rotation = direction; bullet.ShootBullet(power); } }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using RSS.WebApi.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static RSS.WebApi.Extensions.GarbageCollectorHealthCheck; namespace RSS.WebApi.Configurations { public static class HealthCheckConfig { public static IHealthChecksBuilder AddHealthChecksConfiguration(this IHealthChecksBuilder builder, IConfiguration configuration, HealthStatus? failureStatus = null, IEnumerable<string> tags = null, long? thresholdInBytes = null) { builder.AddCheck<GarbageCollectorHealthCheck>("Garbage Collector", failureStatus ?? HealthStatus.Degraded, tags); builder.AddCheck("HasProductsInDatabase", new SqlServerHealthCheck(configuration.GetConnectionString("DefaultConnection"))); builder.AddCheck<SystemMemoryHealthCheck>("MemoryCheck"); builder.AddSqlServer(configuration.GetConnectionString("DefaultConnection"), name: "BancoSQL"); if (thresholdInBytes.HasValue) { builder.Services.Configure<GCInfoOptions>("Garbage Collector", options => { options.Threshold = thresholdInBytes.Value; }); } return builder; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Word = DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using Model = DocGen.ObjectModel; namespace DocGen.OOXML { /// <summary> /// Responsible for adding relevent style parts to the docx package. /// </summary> public class StyleCreator { private static int numberingId = 0; /// <summary> /// Add styles needed for chapter headings /// </summary> public static void AddStylePart() { StyleDefinitionsPart part = DocumentPackager.GetInstance().GetStylePart(); AddNewStyle(part, "Heading1" ,"Heading1"); } /// <summary> /// Adds the style for provided heading type if it's not already added. /// </summary> /// <param name="headingType"></param> public static void AddHeadingStyle(Model.HeadingType headingType) { if (IsStylePresent(StyleIds.GetStyleId(headingType))) { return; } int outlineLevel; switch (headingType) { case DocGen.ObjectModel.HeadingType.H1: outlineLevel = 0; break; case DocGen.ObjectModel.HeadingType.H2: outlineLevel = 1; break; case DocGen.ObjectModel.HeadingType.H3: outlineLevel = 2; break; case DocGen.ObjectModel.HeadingType.H4: outlineLevel = 3; break; case DocGen.ObjectModel.HeadingType.H5: outlineLevel = 4; break; case DocGen.ObjectModel.HeadingType.H6: outlineLevel = 5; break; default: throw new NotImplementedException(headingType + ": Enum value not added"); } Word.Styles styles = DocumentPackager.GetInstance().GetStylePart().Styles; Word.Style style1 = new Word.Style() { Type = Word.StyleValues.Paragraph, StyleId = StyleIds.GetStyleId(headingType) }; Word.BasedOn basedOn1 = new Word.BasedOn() { Val = "Normal" }; Word.StyleParagraphProperties styleParagraphProperties1 = new Word.StyleParagraphProperties(); Word.KeepNext keepNext1 = new Word.KeepNext(); Word.KeepLines keepLines1 = new Word.KeepLines(); Word.SpacingBetweenLines spacingBetweenLines1 = new Word.SpacingBetweenLines() { Before = "480", After = "0" }; Word.OutlineLevel outlineLevel1 = new Word.OutlineLevel() { Val = outlineLevel }; styleParagraphProperties1.Append(keepNext1); styleParagraphProperties1.Append(keepLines1); styleParagraphProperties1.Append(spacingBetweenLines1); styleParagraphProperties1.Append(outlineLevel1); style1.Append(basedOn1); style1.Append(styleParagraphProperties1); // Add the style to the styles part. styles.Append(style1); } public static int AddNumberingStyle(bool ordered, String symbol) { numberingId++; //TODO:Check numbering style existance before adding new one Word.Numbering numbering = DocumentPackager.GetInstance().GetNumberingPart().Numbering; numbering.Append(GenerateAbstractNum(numberingId, ordered, symbol)); numbering.Append(GenerateNumberingInstance(numberingId)); return numberingId; } private static void AddNewStyle(StyleDefinitionsPart styleDefinitionsPart, string styleid, string stylename) { // Get access to the root element of the styles part. Word.Styles styles = styleDefinitionsPart.Styles; Word.Style style1 = new Word.Style() { Type = Word.StyleValues.Paragraph, StyleId = "Heading1" }; Word.StyleName styleName1 = new Word.StyleName() { Val = "heading 1" }; Word.BasedOn basedOn1 = new Word.BasedOn() { Val = "Normal" }; Word.StyleParagraphProperties styleParagraphProperties1 = new Word.StyleParagraphProperties(); Word.KeepNext keepNext1 = new Word.KeepNext(); Word.KeepLines keepLines1 = new Word.KeepLines(); Word.SpacingBetweenLines spacingBetweenLines1 = new Word.SpacingBetweenLines() { Before = "480", After = "0" }; Word.OutlineLevel outlineLevel1 = new Word.OutlineLevel() { Val = 0 }; styleParagraphProperties1.Append(keepNext1); styleParagraphProperties1.Append(keepLines1); styleParagraphProperties1.Append(spacingBetweenLines1); styleParagraphProperties1.Append(outlineLevel1); style1.Append(styleName1); style1.Append(basedOn1); style1.Append(styleParagraphProperties1); // Add the style to the styles part. styles.Append(style1); } private static bool IsStylePresent(String styleId) { // Get access to the Styles element for this document. Styles s = DocumentPackager.GetInstance().GetStylePart().Styles; // Check that there are styles and how many. int n = s.Elements<Style>().Count(); if (n == 0) return false; // Look for a match on styleid. Style style = s.Elements<Style>() .Where(st => (st.StyleId == styleId) && (st.Type == StyleValues.Paragraph)) .FirstOrDefault(); if (style == null) return false; return true; } private static string GetStyleIDFromName(string styleName) { StyleDefinitionsPart stylePart = DocumentPackager.GetInstance().GetStylePart(); string styleId = stylePart.Styles.Descendants<StyleName>() .Where(s => s.Val.Value.Equals(styleName) && (((Style)s.Parent).Type == StyleValues.Paragraph)) .Select(n => ((Style)n.Parent).StyleId).FirstOrDefault(); return styleId; } private static AbstractNum GenerateAbstractNum(int id, bool ordered, String symbol) { AbstractNum abstractNum1 = new AbstractNum() { AbstractNumberId = id }; Nsid nsid1 = new Nsid() { Val = "1FAB1E90" }; MultiLevelType multiLevelType1 = new MultiLevelType() { Val = MultiLevelValues.SingleLevel }; TemplateCode templateCode1 = new TemplateCode() { Val = "5BB0F638" }; Level level1 = new Level() { LevelIndex = 0, TemplateCode = "04090001" }; StartNumberingValue startNumberingValue1 = new StartNumberingValue() { Val = 1 }; NumberingFormat numberingFormat1 = new NumberingFormat(); LevelText levelText1 = new LevelText(); if (ordered) { numberingFormat1.Val = NumberFormatValues.Decimal; if (symbol == null) symbol = "."; levelText1.Val = "%1" + symbol; }else { numberingFormat1.Val = NumberFormatValues.Bullet; if (symbol == null) symbol = "-"; levelText1.Val = symbol; } LevelJustification levelJustification1 = new LevelJustification() { Val = LevelJustificationValues.Left }; PreviousParagraphProperties previousParagraphProperties1 = new PreviousParagraphProperties(); Indentation indentation1 = new Indentation() { Left = "720", Hanging = "360" }; previousParagraphProperties1.Append(indentation1); NumberingSymbolRunProperties numberingSymbolRunProperties1 = new NumberingSymbolRunProperties(); //RunFonts runFonts1 = new RunFonts() { Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" }; //numberingSymbolRunProperties1.Append(runFonts1); level1.Append(startNumberingValue1); level1.Append(numberingFormat1); level1.Append(levelText1); level1.Append(levelJustification1); level1.Append(previousParagraphProperties1); level1.Append(numberingSymbolRunProperties1); abstractNum1.Append(nsid1); abstractNum1.Append(multiLevelType1); abstractNum1.Append(templateCode1); abstractNum1.Append(level1); return abstractNum1; } private static NumberingInstance GenerateNumberingInstance(int id) { NumberingInstance numberingInstance1 = new NumberingInstance() { NumberID = id }; AbstractNumId abstractNumId1 = new AbstractNumId() { Val = id }; numberingInstance1.Append(abstractNumId1); return numberingInstance1; } } }
namespace Console.Logger { public class WebServiceException : Exception { #region Internal private static readonly Dictionary<WSCodError, ItemError> Errores; private class ItemError { public HttpStatusCode Estado { get; set; } public string Novedad { get; set; } } static WSException() { Errores = new Dictionary<WSCodError, ItemError>(); Errores.Add(WSCodError.ParametroObligatorio, new ItemError { Estado = HttpStatusCode.BadRequest, Novedad = "Parámetro {0} obligatorio" }); Errores.Add(WSCodError.ParametroInvalido, new ItemError { Estado = HttpStatusCode.BadRequest, Novedad = "Parámetro {0} inválido" }); Errores.Add(WSCodError.ErrorInternoEnWeb, new ItemError { Estado = HttpStatusCode.InternalServerError, Novedad = "Error interno. Ref={0}" }); Errores.Add(WSCodError.ErrorInternoEnMotor, new ItemError { Estado = HttpStatusCode.InternalServerError, Novedad = "Error interno. Ref={0}" }); Errores.Add(WSCodError.CredencialesInvalidas, new ItemError { Estado = HttpStatusCode.Unauthorized, Novedad = "Credenciales inválidas" }); Errores.Add(WSCodError.AmbienteNoAutorizado, new ItemError { Estado = HttpStatusCode.Forbidden, Novedad = "Ambiente no autorizado" }); Errores.Add(WSCodError.ProtocoloNoAutorizado, new ItemError { Estado = HttpStatusCode.Forbidden, Novedad = "Protocolo {0} no autorizado" }); Errores.Add(WSCodError.EndpointNoAutorizado, new ItemError { Estado = HttpStatusCode.Forbidden, Novedad = "Acceso {0} no autorizado" }); Errores.Add(WSCodError.ServicioDeshabilitado, new ItemError { Estado = HttpStatusCode.Forbidden, Novedad = "Servicio {0} no autorizado" }); Errores.Add(WSCodError.IPNoAutorizada, new ItemError { Estado = HttpStatusCode.Forbidden, Novedad = "Origen no autorizado" }); Errores.Add(WSCodError.LimiteExcedido, new ItemError { Estado = HttpStatusCode.Forbidden, Novedad = "Límite de concurrencia excedido" }); } private static string FormatearNovedadInterna(WSCodError codError, params object[] args) { var item = Errores[codError]; var sb = new StringBuilder(); sb.AppendFormat("(E{0:00}) ", (int)codError); sb.AppendFormat(item.Novedad, args); return sb.ToString(); } private static string FormatearNovedad(WSCodError codError, string novedad) { var sb = new StringBuilder(); sb.AppendFormat("(E{0:00}) ", (int)codError); sb.AppendFormat(novedad); return sb.ToString(); } #endregion /// <summary> /// Devuelve el estado que se informa al WebService /// Referente al status code de HTTP /// </summary> public HttpStatusCode Estado { get; private set; } /// <summary> /// Devuelve la novedad que se informa al WebService. /// Incluye el código de error formateado como (EXX) /// </summary> public string Novedad { get; private set; } /// <summary> /// Devuelve el código de referencia (GUID) para identificar errores internos /// </summary> public string Referencia { get; private set; } /// <summary> /// Constructor privado usado para helper de creación /// </summary> private WSException(HttpStatusCode estado, string novedad) : base(novedad) { this.Estado = estado; this.Novedad = novedad; } /// <summary> /// Constructor general para todos los códigos de error (excepto los errores internos) /// </summary> public WSException(WSCodError codError, params object[] args) : base(FormatearNovedadInterna(codError, args)) { var item = Errores[codError]; this.Estado = item.Estado; this.Novedad = FormatearNovedadInterna(codError, args); } /// <summary> /// Helper de creación para los errores internos /// </summary> public static WSException CrearErrorInterno(WSCodError codError) { var referencia = Guid.NewGuid().ToString(); var novedad = FormatearNovedadInterna((WSCodError)codError, referencia); return new WSException(HttpStatusCode.InternalServerError, novedad) { Referencia = referencia }; } /// <summary> /// Helper de creación para los errores de validación de negocio /// </summary> public static WSException CrearErrorNegocio(int codError, string mensaje, params object[] args) { var mensajeFormateado = string.Format(mensaje, args); var novedad = FormatearNovedad((WSCodError)codError, mensajeFormateado); return new WSException((HttpStatusCode)422, novedad); } } /// <summary> /// Códigos de error /// </summary> public enum WSCodError { /// <summary> /// 400 BAD REQUEST - Parámetro obligatorio /// </summary> ParametroObligatorio = 1, /// <summary> /// 400 BAD REQUEST - Parámetro inválido /// </summary> ParametroInvalido = 2, /// <summary> /// 401 UNAUTHORIZED - Usuario o clave inválidos /// </summary> CredencialesInvalidas = 10, /// <summary> /// 403 FORBIDDEN - El cliente no tiene permiso para acceder al servicio /// </summary> UsuarioNoAutorizado = 11, /// <summary> /// 403 FORBIDDEN - El cliente tiene configurado restricciones de IP /// </summary> IPNoAutorizada = 12, /// <summary> /// 403 FORBIDDEN - El cliente está intentando ingresar a un ambiente productivo con credenciales de desarrollo /// </summary> AmbienteNoAutorizado = 13, /// <summary> /// 403 FORBIDDEN - No implementado /// </summary> ProtocoloNoAutorizado = 14, /// <summary> /// 403 FORBIDDEN - No implementado /// </summary> EndpointNoAutorizado = 15, /// <summary> /// 403 FORBIDDEN - Servicio no habilitado /// </summary> ServicioDeshabilitado = 16, /// <summary> /// 429 TOO MANY REQUESTS - Límite de concurrencia excedido /// </summary> LimiteExcedido = 19, /// <summary> /// 422 UNPROCESSABLE ENTITY - No puede ser procesado por regla de negocio. /// </summary> EntidadSinProcesar = 20, /// <summary> /// 500 INTERNAL ERROR - Excepción no controlada en el webservice /// </summary> ErrorInternoEnWeb = 90, /// <summary> /// 500 INTERNAL ERROR - Excepción no controlada en el backend (motor) /// </summary> ErrorInternoEnMotor = 91, } }
using System; using System.Collections.Generic; using System.Text; namespace EmberKernel.Services.Command.Attributes { [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class CommandDescriptionAttribute : Attribute { public string Description { get; } public CommandDescriptionAttribute(string description) { this.Description = description; } } }
namespace FPGADeveloperTools.FIRDesigner.Model { public enum WindowType { Rectangular, Triangular, Welch, Sine, Hann, Hamming, Blackman, Nuttall, BlackmanNuttall, BlackmanHarris, FlatTop } }
using System; using System.Collections.Generic; using System.Linq; namespace Cirit_path { class Program { static char[] COLON = { ':' }; static char[] SEMI_COLON = { ';' }; static char[] COMMA = { ',' }; static char[] BRACE = { ']' }; public static string GetInput() { Console.WriteLine("enter number of tasks"); String input = ""; int counter = int.Parse(Console.ReadLine()); for (int i = 0; i < counter; i++) { Console.WriteLine("\t\t\t TASK {0}", (i + 1)); Console.Write("Activity Name : "); input += Console.ReadLine(); input += ':'; Console.Write("Duration for this tack : "); input += Console.ReadLine(); Console.WriteLine("Preceding for this tack \n # NOTE : FOR MORE THAN ONE PRECEDING ADD ',' BETWEEN ACTIVITY NAME LIKE A,B , "); string t = Console.ReadLine(); input += (t == "" ? "]" : (";" + t + "]")); Console.WriteLine("------------------------------------"); } return input; } static void Main(string[] args) { int step = 0; List<Activity> i = new List<Activity>(); Console.Write("Enter input: "); //string s = Console.ReadLine().Replace("[", null); string s = GetInput(); foreach (string x in s.Split(BRACE, StringSplitOptions.RemoveEmptyEntries)) { string[] y = x.Split(SEMI_COLON); Activity n = new Activity(x.Split(COLON)[0], Int32.Parse(y[0].Split(COLON)[1])); n.Name = x.Split(COLON)[0]; n.Dependencies = (y.Length > 1) ? y[1].Split(COMMA).ToList() : new List<string>(); i.Add(n); } do { List<string> d = i.Where(x => x.Done()).Select(y => y.Name).ToList(); foreach (Activity working in i.Where(x => x.Dependencies.Except(d).Count() == 0 && !x.Done())) working.Step(step); step++; } while (i.Count(x => !x.Done()) > 0); foreach (Activity a in i) { Activity next = i.OrderBy(x => x.EFinish).Where(x => x.Dependencies.Contains(a.Name)).FirstOrDefault(); a.LFinish = (next == null) ? a.EFinish : next.EStart; a.LStart = a.LFinish - a.Duration; } Console.WriteLine(" TASK | DEPENDENCIES | DURATION | EF | LF | SLACK | critical"); Console.WriteLine("------+--------------+----------+------------+-------------+-------+---------"); foreach (Activity a in i) { Console.Write(a.Name.PadLeft(5) + " |"); Console.Write("".PadLeft(14-a.Dependencies.Count*2)); foreach (var dep in a.Dependencies) { Console.Write(dep+','); } Console.Write("|"); Console.Write(a.Duration.ToString().PadLeft(10) + " |"); Console.Write(a.EFinish.ToString().PadLeft(10) + " |"); Console.Write(a.LFinish.ToString().PadLeft(10) + " |"); Console.Write((a.LFinish - a.EFinish).ToString().PadLeft(7) + " |"); string critical = (a.LFinish - a.EFinish == 0 && a.LStart - a.EStart == 0) ? "Y" : "N"; Console.WriteLine(critical.PadLeft(9)); } Console.WriteLine("Hit any key to exit."); Console.ReadKey(); } } class Activity { public string Name { get; set; } public int Duration { get; set; } public List<string> Dependencies { get; set; } public int EStart { get; set; } public int EFinish { get; set; } public int LStart { get; set; } public int LFinish { get; set; } private int steps = 0; public Activity(string name, int time) { EStart = -1; EFinish = 0; LStart = 0; LFinish = 0; Name = name; Duration = time; steps = time; } public void Step(int count) { EStart = (EStart == -1) ? count : EStart; if (--steps == 0) EFinish = count + 1; } public bool Done() { return steps == 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GSVM.Constructs.DataTypes { public static class Int { public static uint8_t UInt8 { get { return new uint8_t(); } } public static int8_t Int8 { get { return new int8_t(); } } public static uint16_t UInt16 { get { return new uint16_t(); } } public static int16_t Int16 { get { return new int16_t(); } } public static uint32_t UInt32 { get { return new uint32_t(); } } public static int32_t Int32 { get { return new int32_t(); } } public static uint64_t UInt64 { get { return new uint64_t(); } } public static int64_t Int64 { get { return new int64_t(); } } public static T Pointer<T>(uint address) where T : IDataType { T value = Activator.CreateInstance<T>(); value.Address = address; return value; } public static IIntegral BestFit(int size, bool signed = false) { if (size <= 1) { if (signed) return Int8; else return UInt8; } else if (size <= 2) { if (signed) return Int16; else return UInt16; } else if (size <= 4) { if (signed) return Int32; else return UInt32; } else { if (signed) return Int64; else return UInt64; } } } public abstract class Integral<T> : IIntegral<T> { protected SmartPointer ptr; public SmartPointer Pointer { get { return ptr; } } protected T value; public T Value { get { return value; } set { this.value = value; } } public uint Address { get { return ptr.Address; } set { ptr.Address = value; } } public uint Length { get { return ptr.Length; } } object IIntegral.Value { get { return value; } } public abstract void FromBinary(byte[] value); public abstract byte[] ToBinary(); public override string ToString() { return value.ToString(); } public TOut CastTo<TOut>() where TOut : IIntegral { TOut result = default(TOut); byte[] value = new byte[result.Length]; byte[] bin = ToBinary(); for (int i = 0; i < result.Length; i++) { if (i < bin.Length) value[i] = bin[i]; else value[i] = 0; } result.FromBinary(value); return result; } public IIntegral CastTo(IIntegral tout) { IIntegral result = tout; byte[] value = new byte[result.Length]; byte[] bin = ToBinary(); for (int i = 0; i < result.Length; i++) { if (i < bin.Length) value[i] = bin[i]; else value[i] = 0; } result.FromBinary(value); return result; } } public class int8_t : Integral<sbyte> { public int8_t() : this(0) { } public int8_t(sbyte value, uint address) { this.value = value; ptr = new SmartPointer(address, 1); } public int8_t(sbyte value) : this(value, 0) { } public int8_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { unchecked { return new byte[] { (byte)value }; } } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); unchecked { Value = (sbyte)value[0]; } } public static implicit operator sbyte(int8_t value) { return value.Value; } public static implicit operator int8_t(sbyte value) { return new int8_t(value); } } public class uint8_t : Integral<byte> { public uint8_t() : this(0) { } public uint8_t(byte value, uint address) { this.value = value; ptr = new SmartPointer(address, 1); } public uint8_t(byte value) : this(value, 0) { } public uint8_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return new byte[] { value }; } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); this.value = value[0]; } public static implicit operator byte(uint8_t value) { return value.Value; } public static implicit operator uint8_t(byte value) { return new uint8_t(value); } } public class int16_t : Integral<Int16> { public int16_t() : this(0) { } public int16_t(Int16 value, uint address) { this.value = value; ptr = new SmartPointer(address, 2); } public int16_t(Int16 value) : this(value, 0) { } public int16_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = BitConverter.ToInt16(val, 0); } public static implicit operator Int16(int16_t value) { return value.Value; } public static implicit operator int16_t(Int16 value) { return new int16_t(value); } } public class uint16_t : Integral<UInt16> { public uint16_t() : this(0) { } public uint16_t(UInt16 value, uint address) { this.value = value; ptr = new SmartPointer(address, 2); } public uint16_t(UInt16 value) : this(value, 0) { } public uint16_t(uint address) : this(0, address) { } public uint16_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = BitConverter.ToUInt16(val, 0); } public static implicit operator UInt16(uint16_t value) { return value.Value; } public static implicit operator uint16_t(UInt16 value) { return new uint16_t(value); } } public class int32_t : Integral<Int32> { public int32_t() : this(0) { } public int32_t(Int32 value, uint address) { this.value = value; ptr = new SmartPointer(address, 4); } public int32_t(Int32 value) : this(value, 0) { } public int32_t(uint address) : this(0, address) { } public int32_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = BitConverter.ToInt32(val, 0); } public static implicit operator Int32(int32_t value) { return value.Value; } public static implicit operator int32_t(Int32 value) { return new int32_t(value); } } public class uint32_t : Integral<UInt32> { public uint32_t() : this(0) { } public uint32_t(UInt32 value, uint address) { this.value = value; ptr = new SmartPointer(address, 4); } public uint32_t(UInt32 value) : this(value, 0) { } public uint32_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = BitConverter.ToUInt32(val, 0); } public static implicit operator UInt32(uint32_t value) { return value.Value; } public static implicit operator uint32_t(UInt32 value) { return new uint32_t(value); } } public class int64_t : Integral<Int64> { public int64_t() : this(0) { } public int64_t(Int64 value, uint address) { this.value = value; ptr = new SmartPointer(address, 8); } public int64_t(Int64 value) : this(value, 0) { } public int64_t(uint address) : this(0, address) { } public int64_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = BitConverter.ToInt64(val, 0); } public static implicit operator Int64(int64_t value) { return value.Value; } public static implicit operator int64_t(Int64 value) { return new int64_t(value); } } public class uint64_t : Integral<UInt64> { public uint64_t() : this(0) { } public uint64_t(UInt64 value, uint address) { this.value = value; ptr = new SmartPointer(address, 8); } public uint64_t(UInt64 value) : this(value, 0) { } public uint64_t(uint address) : this(0, address) { } public uint64_t(byte[] value) : this() { FromBinary(value); } public override byte[] ToBinary() { return BitConverter.GetBytes(value); } public override void FromBinary(byte[] value) { if (value.Length > Pointer.Length) throw new IndexOutOfRangeException(); byte[] val = new byte[Pointer.Length]; Array.Copy(value, val, value.Length); this.value = BitConverter.ToUInt64(val, 0); } public static implicit operator UInt64(uint64_t value) { return value.Value; } public static implicit operator uint64_t(UInt64 value) { return new uint64_t(value); } } }
using UnityEngine; using System.Collections; public class lightning : MonoBehaviour { // Use this for initialization void Start () { animated = false; counter = 0f; } // public float y; void startAnimated(){ //setOriginPos (); animated = true; } void stopAnimated(){ animated = false; gameObject.GetComponent<SpriteRenderer> ().enabled = false; gameObject.GetComponent<BoxCollider2D> ().enabled = false; } bool animated; //void set //-3.61 //-2.33 // Update is called once per frame //public float coba; float counter; void Update () { //coba = transform.localPosition.y - originPos.y; //if (animated && transform.localPosition.y-originPos.y>-1.28f) { // transform.Translate(0,-10f*Time.deltaTime,0); //} if (animated) { counter += Time.deltaTime; if (counter > 0.3f){ stopAnimated(); counter = 0; } } } }
using System.Globalization; using System.Linq; using System.Net; using System.Net.Cache; using System.Text.RegularExpressions; using System.Xml; namespace FirstMvcApp.Utils { public class CurrencyInfoProvider { private readonly WebClient m_webClient; public enum Services { Google, Yahoo } public CurrencyInfoProvider(Services service = Services.Google) { m_webClient = new WebClient { CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default) }; switch (service) { case Services.Google: m_webClient.BaseAddress = "http://www.google.com/"; break; case Services.Yahoo: m_webClient.BaseAddress = "http://finance.yahoo.com/"; break; } m_webClient.Headers.Add(HttpRequestHeader.CacheControl, "private,max-age=18000"); //m_webClient.QueryString.Add("q", "CURRENCY%3aUSD" + userCurrencyCode); } public decimal GetGoogleFinanceRate(string userCurrencyCode) { decimal rate = 1; m_webClient.QueryString["q"] = "CURRENCY%3aUSD" + userCurrencyCode; var resp = m_webClient.DownloadString("finance/info"); //.DownloadString("http://www.google.com/finance/info?q=CURRENCY%3aUSD" + userCurrencyCode); var rPattern = new Regex("\"\\d+.\\d+\""); var rateMatch = rPattern.Match(resp.Substring(0, resp.IndexOf("l_fix"))); decimal.TryParse(rateMatch.Value.Trim('\"'), NumberStyles.AllowDecimalPoint, new NumberFormatInfo {CurrencyDecimalSeparator = "."}, out rate); return rate; } public decimal GetYahooFinanceRate(string userCurrencyCode) { decimal rate = 1; var resp = m_webClient.DownloadString("webservice/v1/symbols/allcurrencies/quote"); var doc = new XmlDocument(); doc.LoadXml(resp); //var nodeList = doc.SelectNodes("//resources/resource/field[.='USD/"+userCurrencyCode+"']/parent::node()"); var node = doc.SelectSingleNode("//resources/resource/field[.='USD/" + userCurrencyCode + "']/parent::node()"); if (node != null) { decimal.TryParse(node.ChildNodes[1].InnerText, NumberStyles.AllowDecimalPoint, new NumberFormatInfo {CurrencyDecimalSeparator = "."}, out rate); } return rate; } } }
using System; using System.Collections.Generic; using System.Text; namespace HBPonto.Kernel.Interfaces.Services { public interface ICalcWorklogService { double CalcPorcentForIssue(int totalEstimated, int estimated); int GetSecondsForIssue(double porcentForIssue, int timeWorklogInformed); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace SDI_LCS { public class Shutter_Info { Form1 Main; public int InPut_Open_Sensor = 0; public int InPut_Close_Sensor = 0; public int OutPut_Open_Sensor = 0; public int OutPut_Close_Sensor = 0; public int HeartBit = 0; public Shutter_Info() { } public Shutter_Info(Form1 CS_Main) { Main = CS_Main; } } }
using System; using Pe.Stracon.SGC.Infraestructura.CommandModel.Base; namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual { /// <summary> /// Clase que representa la entidad Contrato Bien /// </summary> /// <remarks> /// Creación : GMD 20150511 <br /> /// Modificación : <br /> /// </remarks> public class ContratoBienEntity : Entity { /// <summary> /// Codigo de Contrato de Bien /// </summary> public Guid CodigoContratoBien { get; set; } /// <summary> /// Codigo de Contrato /// </summary> public Guid CodigoContrato { get; set; } /// <summary> /// Codigo de Bien /// </summary> public Guid CodigoBien { get; set; } //INICIO: Agregado por Julio Carrera - Norma Contable /// <summary> /// Codigo tarifa /// </summary> public string CodigoTipoTarifa { get; set; } /// <summary> /// Codigo periodo /// </summary> public string CodigoTipoPeriodo { get; set; } /// <summary> /// Horas Minimas /// </summary> public int? HorasMinimas { get; set; } /// <summary> /// Tarifa /// </summary> public decimal Tarifa { get; set; } /// <summary> /// Es mayor o Menor /// </summary> public string MayorMenor { get; set; } //FIN: Agregado por Julio Carrera - Norma Contable } }
using System; using Zesty.Core.Entities; namespace Zesty.Core.Api.System.Admin.User { public class Authorize : ApiHandlerBase { public override ApiHandlerOutput Process(ApiInputHandler input) { AuthorizeRequest request = GetEntity<AuthorizeRequest>(input); Business.User.Authorize( new Entities.User() { Id = Guid.Parse(request.User) }, new Entities.Authorization() { Domain = new Entities.Domain() { Id = Guid.Parse(request.Domain) }, Role = new Entities.Role() { Id = Guid.Parse(request.Role) } }); return GetOutput(); } } public class AuthorizeRequest { [Required] public string User { get; set; } [Required] public string Domain { get; set; } [Required] public string Role { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleCalcC { public class classSymbol { string _Symbol; int _Prioritet; BaseOperation _Operation; public string Symbol { get { return _Symbol; } } public int Prioritet { get { return _Prioritet; } } public classSymbol(string Symbol, int Prioritet) { _Symbol = Symbol; _Prioritet = Prioritet; } public classSymbol(string Symbol, int Prioritet, BaseOperation Operation) { _Symbol = Symbol; _Prioritet = Prioritet; _Operation = Operation; } public float Calc(float x, float y) { return _Operation.Result(x, y); } } }
using System; using System.Collections.Generic; using System.Threading; namespace evolution { class Program { public int AttemptCount { get; private set; } public int RejectionCount { get; private set; } public int CurrentMatchIndex { get; private set; } public int MatchIndexThreshold { get; set; } = 5; public List<KeyValuePair<int,int>> history=new List<KeyValuePair<int,int>>(); public void Start() { Organism org = new Organism(); int[] terrain = Organism.CreateShape(); AttemptCount=0; RejectionCount = 0; do { CurrentMatchIndex = org.GetMatchIndex(terrain); int[] newShape = org.Shape.Clone() as int[]; Reshape(newShape); AttemptCount++; var clone = new Organism(newShape); if(clone.GetMatchIndex(terrain)>CurrentMatchIndex) { RejectionCount++; } else { org = clone; history.Add(new KeyValuePair<int, int>(AttemptCount, CurrentMatchIndex)); } Thread.Sleep(50); } while(org.GetMatchIndex(terrain) > MatchIndexThreshold); Console.WriteLine("{0} attempts, {1} rejections", AttemptCount, RejectionCount); } private static void Reshape(int[] newShape) { Random random = new Random(); for (int j = 0; j < newShape.Length; j++) { var fact = random.NextDouble(); int add = 0; if (fact > 0.666) { add = 1; } else if (fact < 0.333) { add = -1; } newShape[j] += add; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using _7DRL_2021.Behaviors; using Microsoft.Xna.Framework; namespace _7DRL_2021.Cards { class CardNemesis : Card { public CardNemesis(int deckAmount) : base("nemesis", deckAmount) { Sprite = SpriteLoader.Instance.AddSprite("content/card_nemesis"); Name = $"Omicron"; Description = (textBuilder) => { textBuilder.AppendText("Nemesis becomes killable and must be killed next level. This is the final challenge."); }; Value = 2000; } public override void Apply(SceneGame world, Vector2 cardPos) { Behavior.Apply(new BehaviorOmicron(world.PlayerCurio)); } public override bool CanDestroy(SceneGame world) { throw new NotImplementedException(); } public override void Destroy(SceneGame world, Vector2 cardPos) { throw new NotImplementedException(); } public override bool IsValid(SceneGame world) { return !world.PlayerCurio.HasBehaviors<BehaviorOmicron>(); } } class CardWraith : Card { public CardWraith(int deckAmount) : base("wraith", deckAmount) { Sprite = SpriteLoader.Instance.AddSprite("content/card_bell"); Name = $"Doom"; Description = (textBuilder) => { textBuilder.AppendText("The Bell Wraiths are summoned instantly next level. Hearts give 500% score."); }; Value = 2000; } public override void Apply(SceneGame world, Vector2 cardPos) { Behavior.Apply(new BehaviorDoom(world.PlayerCurio, 5)); } public override bool CanDestroy(SceneGame world) { throw new NotImplementedException(); } public override void Destroy(SceneGame world, Vector2 cardPos) { throw new NotImplementedException(); } public override bool IsValid(SceneGame world) { return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using PunchOutAPI; using PunchOutAPI.Models; namespace PunchOutAPI.Business { public interface IBusinessManager { IEnumerable<URLInfo> GetAllURL(); int PostAllURL(URLInfo issue); } }
using Cottle.Functions; using Cottle.Stores; using System; namespace EddiSpeechResponder.Service { public interface ICustomFunction { string name { get; } FunctionCategory Category { get; } string description { get; } Type ReturnType { get; } NativeFunction function { get; } } public enum FunctionCategory { Details, Dynamic, Galnet, Hidden, Phonetic, Tempo, Utility, Voice } public abstract class ResolverInstance<T1, T2> { protected ScriptResolver resolver { get; } protected BuiltinStore store { get; } protected ResolverInstance(T1 parameter1, T2 parameter2) { if (parameter1 is ScriptResolver resolverParameter) { resolver = resolverParameter; } if (parameter2 is BuiltinStore storeParameter) { store = storeParameter; } } } }
using System.Composition; using Amazon.S3.Model; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System; using Amazon.S3; namespace Assign02_AWS_Movies.Classes { public class MyBucket { public static async Task FileDeleteAsync( string KeyName, string BucketName, IAmazonS3 client) { try { var deleteObjectRequest = new DeleteObjectRequest { BucketName = BucketName, Key = KeyName }; Console.WriteLine("Deleting an object"); await client.DeleteObjectAsync(deleteObjectRequest); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lab8_task2 { class BlackWhitePhone : ButtonPhone { public bool display = true; public override void Call() { Console.WriteLine("Hi-hi! Personally I can call to someone using display!"); } public override void RingTone() { Console.WriteLine("*plays Nokia 3310 ringtone*"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Threading; using DevExpress.XtraEditors; using IRAP.Global; using IRAP.Client.Global; using IRAP.Client.User; using IRAP.Client.SubSystem; using IRAP.Entities.MES; using IRAP.Entities.MDM; using IRAP.Entity.Kanban; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.MESPDC.Dialogs { public partial class frmRepairItemEditor : IRAP.Client.Global.frmCustomBase { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private Global.Enums.EditStatus editStatus; private string caption = ""; private string cultureName = ""; private DataTable dtSymbols = null; private List<FailureMode> failureModes = null; private List<DefectRootCause> defectRootCauses = null; private List<LeafSetEx> failureNatures = null; private List<LeafSetEx> failureDuties = null; private List<ProductRepairMode> repairModes = null; private List<TSFormCtrl> colRepairItems = null; private SubWIPIDCode_TSItem item = new SubWIPIDCode_TSItem() { SKUID1 = "", SKUID2 = "", }; private string wipCode = ""; public frmRepairItemEditor() { InitializeComponent(); cultureName = Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2).ToUpper(); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") caption = "System tips"; else caption = "系统信息"; } public frmRepairItemEditor(Global.Enums.EditStatus editStatus) : this() { this.editStatus = editStatus; sccMain.Panel1.Text = string.Format( sccMain.Panel1.Text, EnumHelper.GetDescription(editStatus)); } public List<TSFormCtrl> RepairItemColumns { get { return colRepairItems; } set { colRepairItems = value; foreach (TSFormCtrl column in colRepairItems) { switch (column.Ordinal) { case 0: lblSymbol.Text = column.CtrlName; lblSymbol.Visible = column.IsValid; cboSymbol.Visible = column.IsValid; break; case 1: lblT118LeafID.Text = column.CtrlName; lblT118LeafID.Visible = column.IsValid; cboT118LeafID.Visible = column.IsValid; break; case 2: lblFailurePointCount.Text = column.CtrlName; lblFailurePointCount.Visible = column.IsValid; edtFailurePointCount.Visible = column.IsValid; break; case 3: lblT216LeafID.Text = column.CtrlName; lblT216LeafID.Visible = column.IsValid; cboT216LeafID.Visible = column.IsValid; break; case 4: lblT183LeafID.Text = column.CtrlName; lblT183LeafID.Visible = column.IsValid; cboT183LeafID.Visible = column.IsValid; break; case 5: lblT184LeafID.Text = column.CtrlName; lblT184LeafID.Visible = column.IsValid; cboT184LeafID.Visible = column.IsValid; break; case 6: lblT119LeafID.Text = column.CtrlName; lblT119LeafID.Visible = column.IsValid; cboT119LeafID.Visible = column.IsValid; break; case 7: lblTrackReferenceValue.Text = column.CtrlName; lblTrackReferenceValue.Visible = column.IsValid; edtTrackReferenceValue.Visible = column.IsValid; break; } } } } /// <summary> /// 子在制品代码 /// </summary> public string WIPCode { get { return wipCode; } set { wipCode = value; } } /// <summary> /// 器件位号列表和物料列表 /// </summary> public DataTable Symbols { get { return dtSymbols; } set { dtSymbols = value; cboSymbol.Properties.Items.Clear(); foreach (DataRow dr in dtSymbols.Rows) { if (dr["ItemName"].ToString() != "") cboSymbol.Properties.Items.Add(dr["ItemName"].ToString()); } } } /// <summary> /// 失效模式列表 /// </summary> public List<FailureMode> FailureModes { get { return failureModes; } set { failureModes = value; foreach (FailureMode mode in failureModes) { cboT118LeafID.Properties.Items.Add( string.Format( "[{0}]{1}", mode.FailureCode, mode.FailureName)); } if (failureModes.Count == 1) { cboT118LeafID.SelectedIndex = 0; lblT118Name.Text = failureModes[0].FailureName; item.T118LeafID = failureModes[0].FailureLeaf; cboT118LeafID.Enabled = false; } } } /// <summary> /// 根源工序列表 /// </summary> public List<DefectRootCause> DefectRootCauses { get { return defectRootCauses; } set { defectRootCauses = value; /* 下拉选择框中只显示代码,不显示名称 foreach (DefectRootCause cause in defectRootCauses) { cboT216LeafID.Properties.Items.Add(cause.OperationCode); } if (defectRootCauses.Count == 1) { cboT216LeafID.Text = defectRootCauses[0].OperationCode; lblT216Name.Text = defectRootCauses[0].OperationName; item.T216LeafID = defectRootCauses[0].OperationLeaf; cboT216LeafID.Enabled = false; } */ foreach (DefectRootCause cause in defectRootCauses) { cboT216LeafID.Properties.Items.Add(cause); } if (defectRootCauses.Count == 1) { cboT216LeafID.SelectedIndex = 0; lblT216Name.Text = defectRootCauses[0].OperationName; item.T216LeafID = defectRootCauses[0].OperationLeaf; cboT216LeafID.Enabled = false; } } } /// <summary> /// 失效性质列表 /// </summary> public List<LeafSetEx> FailureNatures { get { return failureNatures; } set { failureNatures = value; foreach (LeafSetEx item in value) { cboT183LeafID.Properties.Items.Add( string.Format( "[{0}]{1}", item.Code, item.LeafName)); } if (failureNatures.Count == 1) { cboT183LeafID.SelectedIndex = 0; lblT183Name.Text = failureNatures[0].LeafName; item.T183LeafID = failureNatures[0].LeafID; cboT183LeafID.Enabled = false; } } } /// <summary> /// 失效责任列表 /// </summary> public List<LeafSetEx> FailureDuties { get { return failureDuties; } set { failureDuties = value; foreach (LeafSetEx item in value) { cboT184LeafID.Properties.Items.Add( string.Format( "[{0}]{1}", item.Code, item.LeafName)); } if (failureDuties.Count == 1) { cboT184LeafID.SelectedIndex = 0; lblT184Name.Text = failureDuties[0].LeafName; item.T184LeafID = failureDuties[0].LeafID; cboT184LeafID.Enabled = false; } } } /// <summary> /// 维修代码 /// </summary> public List<ProductRepairMode> RepairModes { get { return repairModes; } set { repairModes = value; foreach (ProductRepairMode item in value) { cboT119LeafID.Properties.Items.Add( string.Format( "[{0}]{1}", item.Code, item.LeafName)); } } } public SubWIPIDCode_TSItem RepairItem { get { return item; } set { item = value; InitValue(item); } } private string GetCode(string text) { string rlt = ""; for (int i = 0; i < text.Length; i++) { char tempChar = text[i]; if (tempChar != '[') { if (tempChar == ']') { break; } else { rlt += tempChar; } } } return rlt; } private void InitValue(SubWIPIDCode_TSItem item) { #region 设置“器件位号/物料编号” if (item.T110LeafID != 0) { foreach (DataRow dr in dtSymbols.Rows) { if ((int)dr["ItemType"] == 110) if ((int)dr["ItemLeaf"] == item.T110LeafID) { cboSymbol.Text = dr["ItemName"].ToString(); lblSymbolText.Text = dr["ItemName"].ToString(); break; } } } if (item.T101LeafID != 0) { foreach (DataRow dr in dtSymbols.Rows) { if ((int)dr["ItemType"] == 101) if ((int)dr["ItemLeaf"] == item.T101LeafID) { cboSymbol.Text = dr["ItemName"].ToString(); lblSymbolText.Text = dr["ItemName"].ToString(); break; } } } #endregion #region 设置“失效模式” foreach (FailureMode mode in failureModes) { if (mode.FailureLeaf == item.T118LeafID) { cboT118LeafID.Text = string.Format( "[{0}]{1}", mode.FailureCode, mode.FailureName); lblT118Name.Text = mode.FailureName; break; } } #endregion #region 设置“失效点数” edtFailurePointCount.Text = item.FailurePointCount.ToString(); #endregion #region 设置“根源工序” foreach (DefectRootCause cause in defectRootCauses) { if (cause.OperationLeaf == item.T216LeafID) { /* cboT216LeafID.Text = cause.OperationCode; */ cboT216LeafID.SelectedItem = cause; lblT216Name.Text = cause.OperationName; break; } } #endregion #region 设置“失效性质” foreach (LeafSetEx leaf in failureNatures) { if (leaf.LeafID == item.T183LeafID) { cboT183LeafID.Text = string.Format( "[{0}]{1}", leaf.Code, leaf.LeafName); lblT183Name.Text = leaf.LeafName; break; } } #endregion #region 设置“失效责任” foreach (LeafSetEx leaf in failureDuties) { if (leaf.LeafID == item.T184LeafID) { cboT184LeafID.Text = string.Format( "[{0}]{1}", leaf.Code, leaf.LeafName); lblT184Name.Text = leaf.LeafName; break; } } #endregion #region 设置“维修代码” foreach (ProductRepairMode leaf in repairModes) { if (leaf.LeafID == item.T119LeafID) { cboT119LeafID.Text = string.Format( "[{0}]{1}", leaf.Code, leaf.LeafName); lblT119Name.Text = leaf.LeafName; break; } } #endregion #region 设置“追溯参考值” edtTrackReferenceValue.Text = item.TrackReferenceValue; #endregion } private void frmRepairItemEditor_Load(object sender, EventArgs e) { switch (IRAPUser.Instance.CommunityID) { case 60006: lblFailurePointCount.Visible = false; edtFailurePointCount.Visible = false; lblT216LeafID.Visible = false; cboT216LeafID.Visible = false; lblT183LeafID.Visible = false; cboT183LeafID.Visible = false; lblT184LeafID.Visible = false; cboT184LeafID.Visible = false; lblTrackReferenceValue.Visible = false; edtTrackReferenceValue.Visible = false; break; case 60013: lblT118LeafID.Text = "不良现象"; lblT216LeafID.Visible = false; lblT183LeafID.Text = "责任区分"; lblT184LeafID.Text = "责任部门"; lblTrackReferenceValue.Visible = false; break; } } private void edtSymbol_Enter(object sender, EventArgs e) { ((TextEdit)sender).SelectAll(); } private void edtSymbol_Validating(object sender, CancelEventArgs e) { if (cboSymbol.Text.Trim() == "") { lblSymbolText.Text = ""; item.T110LeafID = 0; item.T101LeafID = 0; e.Cancel = false; return; } if (dtSymbols == null || dtSymbols.Rows.Count == 0) { cboSymbol.Text = ""; lblSymbolText.Text = "系统未配置当前产品的器件位号列表和物料列表!"; lblSymbolText.ForeColor = Color.Red; item.T110LeafID = 0; item.T101LeafID = 0; e.Cancel = false; return; } foreach (DataRow dr in dtSymbols.Rows) { if (dr["ItemName"].ToString() == cboSymbol.Text) { switch ((int)dr["ItemType"]) { case 110: item.T110LeafID = (int)dr["ItemLeaf"]; break; default: item.T101LeafID = (int)dr["ItemLeaf"]; break; } lblSymbolText.Text = dr["ItemName"].ToString(); lblSymbolText.ForeColor = Color.Blue; e.Cancel = false; return; } } IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "没有找到[{0}]的器件位号或者物料号!", cboSymbol.Text), caption); cboSymbol.Text = ""; lblSymbolText.Text = ""; e.Cancel = true; } private void edtT118LeafID_Validating(object sender, CancelEventArgs e) { if (cboT118LeafID.Text.Trim() == "") { lblT118Name.Text = ""; item.T118LeafID = 0; e.Cancel = false; return; } if (failureModes.Count == 0) { cboT118LeafID.Text = ""; lblT118Name.Text = string.Format("未配置{0}!", lblT118LeafID.Text); lblT118Name.ForeColor = Color.Red; item.T118LeafID = 0; e.Cancel = false; return; } string t118Code = GetCode(cboT118LeafID.Text); foreach (FailureMode failure in failureModes) { if (failure.FailureCode == t118Code) { cboT118LeafID.Text = string.Format( "[{0}]{1}", failure.FailureCode, failure.FailureName); item.T118LeafID = failure.FailureLeaf; lblT118Name.Text = failure.FailureName; lblT118Name.ForeColor = Color.Blue; e.Cancel = false; return; } } IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "没有找到[{0}]{1}代码", cboT118LeafID.Text, lblT118LeafID.Text), caption); cboT118LeafID.Text = ""; lblT118Name.Text = ""; e.Cancel = true; } private void edtFailurePointCount_Validating(object sender, CancelEventArgs e) { if (edtFailurePointCount.Text.Trim() == "") { edtFailurePointCount.Text = "0"; item.FailurePointCount = 0; e.Cancel = false; return; } int failPointCount = 0; if (int.TryParse(edtFailurePointCount.Text, out failPointCount)) { item.FailurePointCount = failPointCount; e.Cancel = false; } else { item.FailurePointCount = 0; edtFailurePointCount.Text = "0"; e.Cancel = true; } } private void edtT216LeafID_Validating(object sender, CancelEventArgs e) { if (cboT216LeafID.Text.Trim() == "") { lblT216Name.Text = ""; item.T216LeafID = 0; e.Cancel = false; return; } if (DefectRootCauses.Count == 0) { /* cboT216LeafID.Text = ""; */ cboT216LeafID.SelectedItem = null; lblT216Name.Text = string.Format("未配置{0}!", lblT216LeafID.Text); lblT216Name.ForeColor = Color.Red; item.T216LeafID = 0; e.Cancel = false; return; } string t216Code = GetCode(cboT216LeafID.Text); foreach (DefectRootCause rootCause in defectRootCauses) { if (rootCause.OperationCode == t216Code) { cboT216LeafID.SelectedItem = rootCause; item.T216LeafID = rootCause.OperationLeaf; lblT216Name.Text = rootCause.OperationName; lblT216Name.ForeColor = Color.Blue; e.Cancel = false; return; } } IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "没有找到[{0}]{1}代码", cboT216LeafID.Text, lblT216LeafID.Text), caption); cboT216LeafID.Text = ""; lblT216Name.Text = ""; e.Cancel = true; } private void edtT183LeafID_Validating(object sender, CancelEventArgs e) { if (cboT183LeafID.Text.Trim() == "") { lblT183Name.Text = ""; item.T183LeafID = 0; e.Cancel = false; return; } if (failureNatures.Count == 0) { cboT183LeafID.Text = ""; lblT183Name.Text = string.Format("未配置{0}!", lblT183LeafID.Text); lblT183Name.ForeColor = Color.Red; item.T183LeafID = 0; e.Cancel = false; return; } string t183Code = GetCode(cboT183LeafID.Text); foreach (LeafSetEx nature in failureNatures) { if (nature.Code == t183Code) { cboT183LeafID.Text = string.Format( "[{0}]{1}", nature.Code, nature.LeafName); item.T183LeafID = nature.LeafID; lblT183Name.Text = nature.LeafName; lblT183Name.ForeColor = Color.Blue; e.Cancel = false; return; } } IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "没有找到[{0}]{1}代码", cboT183LeafID.Text, lblT183LeafID.Text), caption); cboT183LeafID.Text = ""; lblT183Name.Text = ""; e.Cancel = true; } private void edtT184LeafID_Validating(object sender, CancelEventArgs e) { if (cboT184LeafID.Text.Trim() == "") { lblT184Name.Text = ""; item.T184LeafID = 0; e.Cancel = false; return; } if (failureNatures.Count == 0) { cboT184LeafID.Text = ""; lblT184Name.Text = string.Format("未配置{0}!", lblT184LeafID.Text); lblT184Name.ForeColor = Color.Red; item.T184LeafID = 0; e.Cancel = false; return; } string t184Code = GetCode(cboT184LeafID.Text); foreach (LeafSetEx duty in failureDuties) { if (duty.Code == t184Code) { cboT184LeafID.Text = string.Format( "[{0}]{1}", duty.Code, duty.LeafName); item.T184LeafID = duty.LeafID; lblT184Name.Text = duty.LeafName; lblT184Name.ForeColor = Color.Blue; e.Cancel = false; return; } } IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "没有找到[{0}]{1}代码", cboT184LeafID.Text, lblT184LeafID.Text), caption); cboT184LeafID.Text = ""; lblT184Name.Text = ""; e.Cancel = true; } private void edtT119LeafID_Validating(object sender, CancelEventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); if (cboT119LeafID.Text.Trim() == "") { lblT119Name.Text = ""; item.T119LeafID = 0; e.Cancel = false; return; } if (failureNatures.Count == 0) { cboT119LeafID.Text = ""; lblT119Name.Text = string.Format("未配置{0}!", lblT119LeafID.Text); lblT119Name.ForeColor = Color.Red; item.T119LeafID = 0; e.Cancel = false; return; } string t119Code = GetCode(cboT119LeafID.Text); foreach (ProductRepairMode repairMode in repairModes) { if (repairMode.Code == t119Code) { cboT119LeafID.Text = string.Format( "[{0}]{1}", repairMode.Code, repairMode.LeafName); item.T119LeafID = repairMode.LeafID; lblT119Name.Text = repairMode.LeafName; lblT119Name.ForeColor = Color.Blue; #region if (item.T119LeafID == 10700) { WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; string skuID = ""; #region 获取更换后的 SKUID IRAPMESTSClient.Instance.ufn_GetFIFOSKUIDinTSSite( IRAPUser.Instance.CommunityID, CurrentOptions.Instance.OptionOne.T107LeafID, item.T101LeafID, IRAPUser.Instance.SysLogID, ref skuID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { XtraMessageBox.Show( errText, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } else { if (skuID == "") { XtraMessageBox.Show( "维修库位没有可用库存,请先进行维修领料!", caption, MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } else { item.SKUID2 = skuID; } } #endregion #region 获取原物料的 SKUID IRAPMESTSClient.Instance.ufn_GetMaterialSKUIDBySymbol( IRAPUser.Instance.CommunityID, wipCode, item.T110LeafID, item.T101LeafID, IRAPUser.Instance.SysLogID, ref skuID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { XtraMessageBox.Show( errText, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); e.Cancel = true; return; } else { item.SKUID1 = skuID; } #endregion } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } #endregion e.Cancel = false; return; } } IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "没有找到[{0}]{1}代码", cboT119LeafID.Text, lblT119LeafID.Text), caption); cboT119LeafID.Text = ""; lblT119Name.Text = ""; e.Cancel = true; } private void edtTrackReferenceValue_Validating(object sender, CancelEventArgs e) { item.TrackReferenceValue = edtTrackReferenceValue.Text; e.Cancel = false; } private void btnSave_Click(object sender, EventArgs e) { if (item.T110LeafID == 0 && item.T101LeafID == 0) { IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "[{0}]未输入!", lblSymbolText.Text)); cboSymbol.Focus(); return; } if (item.T118LeafID == 0 && cboT118LeafID.Visible) { IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "[{0}]未输入!", lblT118LeafID.Text)); cboT118LeafID.Focus(); return; } if (item.T216LeafID == 0 && cboT216LeafID.Visible) { IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "[{0}]未输入!", lblT216LeafID.Text)); cboT216LeafID.Focus(); return; } if (item.T183LeafID == 0 && cboT183LeafID.Visible) { IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "[{0}]未输入!", lblT183LeafID.Text)); cboT183LeafID.Focus(); return; } if (item.T184LeafID == 0 && cboT184LeafID.Visible) { IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "[{0}]未输入!", lblT184LeafID.Text)); cboT184LeafID.Focus(); return; } if (item.T119LeafID == 0 && cboT119LeafID.Visible) { IRAPMessageBox.Instance.ShowErrorMessage( string.Format( "[{0}]未输入!", lblT119LeafID.Text)); cboT119LeafID.Focus(); return; } DialogResult = DialogResult.OK; } } }
namespace Assets.Scripts.Models.ResourceObjects { public abstract class ResourceObject : BaseObject { } }
using NUnit.Framework; using OrbCore.Core.Cache; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrbCoreTests.CacheTests { [TestFixture] class DiscordCacheTests { DiscordObjectsCache<int> _cache; ulong _idCount; [OneTimeSetUp] public void SetUp() { _cache = new DiscordObjectsCache<int>(); _idCount = 0; } [Test] public void TestAdd() { var id = GetAndUpdateId(); _cache.SetMember(id, 1); Assert.AreEqual(1, _cache.GetMember(id).Value); } [Test] public void TestUpdate() { var id = GetAndUpdateId(); _cache.SetMember(id, 1); _cache.SetMember(id, 2); Assert.AreEqual(2, _cache.GetMember(id).Value); } [Test] public void TestChangeIfExistWhenExists() { var id = GetAndUpdateId(); _cache.SetMember(id, 1); _cache.ChangeIfExists(id, 2); Assert.AreEqual(2, _cache.GetMember(id).Value); } [Test] public void TestChangeIfExistWhenNotExists() { var id = GetAndUpdateId(); _cache.ChangeIfExists(id, 2); Assert.IsFalse(_cache.GetMember(id).Present); } [Test] public void TestGettingNonExistentMember() { var id = GetAndUpdateId(); Assert.IsFalse(_cache.GetMember(id).Present); } [Test] public void TestGetMemberOrCall() { var id = GetAndUpdateId(); Assert.AreEqual(1, _cache.GetMemberOrCall(id, (s) => { return 1; })); Assert.AreEqual(1, _cache.GetMember(id).Value); } [Test] public void TestRemoveMember() { var id = GetAndUpdateId(); _cache.SetMember(id, 1); Assert.AreEqual(1, _cache.GetMember(id).Value); _cache.RemoveMember(id); Assert.IsFalse(_cache.GetMember(id).Present); } [Test] public void TestHasMemberExists() { var id = GetAndUpdateId(); _cache.SetMember(id, 1); Assert.IsTrue(_cache.HasMember(id)); } [Test] public void TestHasMemberNotExists() { var id = GetAndUpdateId(); Assert.IsFalse(_cache.HasMember(id)); } private ulong GetAndUpdateId() { _idCount++; return _idCount; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BookService.Models { public class Jack { public class JackCollection { public List<Jack> Jacks { get; set; } } public int id { get; set; } public string title { get; set; } public string album { get; set; } public string artist { get; set; } public string genre { get; set; } public string source { get; set; } public string image { get; set; } public int trackNumber { get; set; } public int totalTrackCount { get; set; } public int duration { get; set; } public string site { get; set; } } }
using Photon.Pun; using Photon.Realtime; using Source.Code.Utils; using System; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; namespace Source.Code.MyPhoton { public class ConnectionToMaster : MonoBehaviourPunCallbacks { [SerializeField] private NickNameSetter nickSetter; [SerializeField] private TextMeshProUGUI debugTMP; [SerializeField] private Transform afterConnectedCanvas; [SerializeField] private Button connectButton; public event Action ConnectedToMaster; public event Action Disconnected; private void Start() { debugTMP.text = ""; } public void ConnectButton() { if (nickSetter.IsNicknameEmpty()) return; if (PhotonNetwork.IsConnected) return; PhotonNetwork.ConnectUsingSettings(); PhotonNetwork.GameVersion = GlobalSettings.Version; debugTMP.text = "Connecting..."; connectButton.interactable = false; } public void MainMenuButton() { Disconnected = null; if (PhotonNetwork.IsConnected) PhotonNetwork.Disconnect(); SceneManager.LoadScene(0); } public override void OnConnectedToMaster() { string text = $"Successfully connected to PUN master server. The current region is \"{PhotonNetwork.CloudRegion}\""; Debug.Log(text); debugTMP.text = text; debugTMP.color = Color.green; connectButton.interactable = false; afterConnectedCanvas.gameObject.SetActive(true); ConnectedToMaster?.Invoke(); } public override void OnDisconnected(DisconnectCause cause) { string text = $"OnDisconnected() was called by PUN with reason {cause}"; Debug.LogError(text); debugTMP.text = text; debugTMP.color = Color.red; afterConnectedCanvas.gameObject.SetActive(false); connectButton.interactable = true; Disconnected?.Invoke(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BeeFarm { abstract class Bee { public int Age { get; set; } public Hive HomeHive { get; set; } public Bee() { Age = 0; } public Bee(Hive hv) { HomeHive = hv; Age = 0; } public void FlyTo(Hive hv) { hv.bees.Add(this); HomeHive = hv; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Net; using MediaBrowser.Model.Threading; namespace MediaBrowser.Controller.Net { /// <summary> /// Starts sending data over a web socket periodically when a message is received, and then stops when a corresponding stop message is received /// </summary> /// <typeparam name="TReturnDataType">The type of the T return data type.</typeparam> /// <typeparam name="TStateType">The type of the T state type.</typeparam> public abstract class BasePeriodicWebSocketListener<TReturnDataType, TStateType> : IWebSocketListener, IDisposable where TStateType : WebSocketListenerState, new() where TReturnDataType : class { /// <summary> /// The _active connections /// </summary> protected readonly List<Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType>> ActiveConnections = new List<Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType>>(); /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> protected abstract string Name { get; } /// <summary> /// Gets the data to send. /// </summary> /// <param name="state">The state.</param> /// <returns>Task{`1}.</returns> protected abstract Task<TReturnDataType> GetDataToSend(TStateType state, CancellationToken cancellationToken); /// <summary> /// The logger /// </summary> protected ILogger Logger; protected ITimerFactory TimerFactory { get; private set; } protected BasePeriodicWebSocketListener(ILogger logger, ITimerFactory timerFactory) { if (logger == null) { throw new ArgumentNullException("logger"); } Logger = logger; TimerFactory = timerFactory; } /// <summary> /// The null task result /// </summary> protected Task NullTaskResult = Task.FromResult(true); /// <summary> /// Processes the message. /// </summary> /// <param name="message">The message.</param> /// <returns>Task.</returns> public Task ProcessMessage(WebSocketMessageInfo message) { if (message == null) { throw new ArgumentNullException("message"); } if (string.Equals(message.MessageType, Name + "Start", StringComparison.OrdinalIgnoreCase)) { Start(message); } if (string.Equals(message.MessageType, Name + "Stop", StringComparison.OrdinalIgnoreCase)) { Stop(message); } return NullTaskResult; } protected readonly CultureInfo UsCulture = new CultureInfo("en-US"); protected virtual bool SendOnTimer { get { return false; } } protected virtual void ParseMessageParams(string[] values) { } /// <summary> /// Starts sending messages over a web socket /// </summary> /// <param name="message">The message.</param> private void Start(WebSocketMessageInfo message) { var vals = message.Data.Split(','); var dueTimeMs = long.Parse(vals[0], UsCulture); var periodMs = long.Parse(vals[1], UsCulture); if (vals.Length > 2) { ParseMessageParams(vals.Skip(2).ToArray()); } var cancellationTokenSource = new CancellationTokenSource(); Logger.Debug("{1} Begin transmitting over websocket to {0}", message.Connection.RemoteEndPoint, GetType().Name); var timer = SendOnTimer ? TimerFactory.Create(TimerCallback, message.Connection, Timeout.Infinite, Timeout.Infinite) : null; var state = new TStateType { IntervalMs = periodMs, InitialDelayMs = dueTimeMs }; lock (ActiveConnections) { ActiveConnections.Add(new Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType>(message.Connection, cancellationTokenSource, timer, state)); } if (timer != null) { timer.Change(TimeSpan.FromMilliseconds(dueTimeMs), TimeSpan.FromMilliseconds(periodMs)); } } /// <summary> /// Timers the callback. /// </summary> /// <param name="state">The state.</param> private void TimerCallback(object state) { var connection = (IWebSocketConnection)state; Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType> tuple; lock (ActiveConnections) { tuple = ActiveConnections.FirstOrDefault(c => c.Item1 == connection); } if (tuple == null) { return; } if (connection.State != WebSocketState.Open || tuple.Item2.IsCancellationRequested) { DisposeConnection(tuple); return; } SendData(tuple); } protected void SendData(bool force) { Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType>[] tuples; lock (ActiveConnections) { tuples = ActiveConnections .Where(c => { if (c.Item1.State == WebSocketState.Open && !c.Item2.IsCancellationRequested) { var state = c.Item4; if (force || (DateTime.UtcNow - state.DateLastSendUtc).TotalMilliseconds >= state.IntervalMs) { return true; } } return false; }) .ToArray(); } foreach (var tuple in tuples) { SendData(tuple); } } private async void SendData(Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType> tuple) { var connection = tuple.Item1; try { var state = tuple.Item4; var cancellationToken = tuple.Item2.Token; var data = await GetDataToSend(state, cancellationToken).ConfigureAwait(false); if (data != null) { await connection.SendAsync(new WebSocketMessage<TReturnDataType> { MessageType = Name, Data = data }, cancellationToken).ConfigureAwait(false); state.DateLastSendUtc = DateTime.UtcNow; } } catch (OperationCanceledException) { if (tuple.Item2.IsCancellationRequested) { DisposeConnection(tuple); } } catch (Exception ex) { Logger.ErrorException("Error sending web socket message {0}", ex, Name); DisposeConnection(tuple); } } /// <summary> /// Stops sending messages over a web socket /// </summary> /// <param name="message">The message.</param> private void Stop(WebSocketMessageInfo message) { lock (ActiveConnections) { var connection = ActiveConnections.FirstOrDefault(c => c.Item1 == message.Connection); if (connection != null) { DisposeConnection(connection); } } } /// <summary> /// Disposes the connection. /// </summary> /// <param name="connection">The connection.</param> private void DisposeConnection(Tuple<IWebSocketConnection, CancellationTokenSource, ITimer, TStateType> connection) { Logger.Debug("{1} stop transmitting over websocket to {0}", connection.Item1.RemoteEndPoint, GetType().Name); var timer = connection.Item3; if (timer != null) { try { timer.Dispose(); } catch (ObjectDisposedException) { } } try { connection.Item2.Cancel(); connection.Item2.Dispose(); } catch (ObjectDisposedException) { } ActiveConnections.Remove(connection); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool dispose) { if (dispose) { lock (ActiveConnections) { foreach (var connection in ActiveConnections.ToArray()) { DisposeConnection(connection); } } } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } } public class WebSocketListenerState { public DateTime DateLastSendUtc { get; set; } public long InitialDelayMs { get; set; } public long IntervalMs { get; set; } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using WebDriverOnCore.WebDriver; namespace WebDriverOnCore.TestUntillities { public static class SeleniumExtension { public static IWebElement WaitUntilElementExists(By locator, int maxSeconds) { return new WebDriverWait(Driver.CurrentBrowser, TimeSpan.FromSeconds(maxSeconds)).Until(dr => dr.FindElement(locator)); } public static IReadOnlyCollection<IWebElement> WaitUntilElementsExists(By locator, int maxSeconds) { return new WebDriverWait(Driver.CurrentBrowser, TimeSpan.FromSeconds(maxSeconds)).Until(dr => dr.FindElements(locator)); } } }
namespace Uintra.Infrastructure.Providers { public interface IDateTimeFormatProvider { string TimeFormat { get; set; } string EventDetailsDateFormat { get; set; } string EventDetailsDateTimeFormat { get; set; } string EventDetailsTimeFormat { get; set; } string EventDetailsTimeWithoutMinutesFormat { get; set; } string DateFormat { get; set; } string DateTimeFormat { get; set; } string DateTimeValuePickerFormat { get; set; } string DatePickerFormat { get; set; } string DateTimePickerFormat { get; set; } } }
namespace Vendr.Checkout.Pipeline { /// <summary> /// Base type for individual pipeline task. /// Descendants of this type map an input value to an output value. /// The input and output types can differ. /// </summary> internal interface IPipelineTask<INPUT, OUTPUT> { OUTPUT Process(INPUT input); } }
/* * Author: Generated Code * Date Created: 26.04.2011 * Description: Represents a row in the tblCustInkAktAktion table */ using System.Data.SqlClient; using System.Data; using System; namespace HTB.Database { public class tblCustInkAktAktion : Record { #region Property Declaration [MappingAttribute(FieldType = MappingAttribute.FIELD_TYPE_ID, FieldAutoNumber = true)] public int CustInkAktAktionID { get; set; } public DateTime CustInkAktAktionDate { get; set; } public string CustInkAktAktionCaption { get; set; } public int CustInkAktAktionTyp { get; set; } public DateTime CustInkAktAktionEditDate { get; set; } public int CustInkAktAktionAktID { get; set; } public string CustInkAktAktionMemo { get; set; } public int CustInkAktAktionUserId { get; set; } #endregion } }
using System; using System.Linq; using TY.SPIMS.Controllers.Interfaces; using TY.SPIMS.Entities; using TY.SPIMS.POCOs; using TY.SPIMS.Utilities; namespace TY.SPIMS.Controllers { public class SalesCounterController : ISalesCounterController { private readonly IUnitOfWork unitOfWork; private readonly ISaleController saleController; private TYEnterprisesEntities db { get { return unitOfWork.Context; } } public SalesCounterController(IUnitOfWork unitOfWork, ISaleController saleController) { this.unitOfWork = unitOfWork; this.saleController = saleController; } public void Insert(CounterSale counter) { try { using (this.unitOfWork) { if (counter != null) { counter.IsDeleted = false; this.unitOfWork.Context.CounterSales.AddObject(counter); this.unitOfWork.SaveChanges(); } } } catch (Exception ex) { throw ex; } } public void Update(CounterSale newCounter) { try { using (this.unitOfWork) { var original = db.CounterSales.Single(a => a.Id == newCounter.Id); original.CounterSalesItems.ToList().ForEach(a => db.DeleteObject(a)); newCounter.CounterSalesItems.ToList().ForEach(a => original.CounterSalesItems.Add(a)); this.unitOfWork.Context.CounterSales.Attach(original); this.unitOfWork.Context.CounterSales.ApplyCurrentValues(newCounter); this.unitOfWork.SaveChanges(); } } catch (Exception ex) { throw ex; } } public void Delete(int id) { try { using (this.unitOfWork) { var counter = db.CounterSales.Single(a => a.Id == id); counter.IsDeleted = true; counter.CounterSalesItems.ToList().ForEach(a => db.DeleteObject(a)); this.unitOfWork.SaveChanges(); } } catch (Exception ex) { throw ex; } } private IQueryable<CounterSale> CreateQuery(CounterFilterModel filter) { var items = from i in db.CounterSales where i.IsDeleted == null || i.IsDeleted != true select i; if (filter != null) { if (filter.CustomerId != 0) items = items.Where(a => a.CustomerId == filter.CustomerId); if (!string.IsNullOrWhiteSpace(filter.CounterNumber)) items = items.Where(a => a.CounterNumber.Contains(filter.CounterNumber)); if (filter.DateType != DateSearchType.All) { DateTime dateFrom = filter.DateFrom.Date; DateTime dateTo = filter.DateTo.AddDays(1).Date; items = items.Where(a => a.Date >= dateFrom && a.Date < dateTo); } } else { //Default sorting items = items.OrderByDescending(a => a.Date); } return items; } public SortableBindingList<SalesCounterDisplayModel> FetchSalesCounterWithSearch(CounterFilterModel filter) { try { var query = CreateQuery(filter); var result = from a in query select new SalesCounterDisplayModel { Id = a.Id, CounterNumber = a.CounterNumber, Customer = a.Customer.CompanyName, Date = a.Date, TotalAmount = a.Total.HasValue ? a.Total.Value : 0 }; SortableBindingList<SalesCounterDisplayModel> b = new SortableBindingList<SalesCounterDisplayModel>(result); return b; } catch (Exception ex) { throw ex; } } public SortableBindingList<SalesCounterItemModel> FetchSalesItems(int id) { try { var result = db.CounterSalesItems.Where(a => a.CounterSalesId == id) .Select(a => new SalesCounterItemModel() { InvoiceNumber = a.Sale.InvoiceNumber, MemoNumber = a.SalesReturnDetail.SalesReturn.MemoNumber, Amount = a.Amount, Date = a.SaleId != null ? a.Sale.Date : a.SalesReturnDetail.SalesReturn.ReturnDate, SaleId = a.SaleId, ReturnId = a.SalesReturnDetailId }); foreach (var r in result) { if(r.SaleId != null) r.PONumber = this.saleController.GetPONumber(r.SaleId.Value); } SortableBindingList<SalesCounterItemModel> b = new SortableBindingList<SalesCounterItemModel>(result); return b; } catch (Exception ex) { throw ex; } } public CounterSale FetchCounterById(int id) { try { var counter = db.CounterSales.Single(a => a.Id == id); return counter; } catch (Exception ex) { throw ex; } } } }
using System.Windows; namespace Crystal.Plot2D { public static class PointExtensions { public static Vector ToVector(this Point pt) => new(pt.X, pt.Y); public static bool IsFinite(this Point pt) => pt.X.IsFinite() && pt.Y.IsFinite(); } }
 using ComInLan.Model.Base; namespace ComInLan.Model { public interface IBroadcastData : IJson { int ListeningPort { get; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using LeonClientApp.Models; using System.ComponentModel.DataAnnotations; using System; namespace LeonClientApp.Database { public class PrimaryDatabaseContext : DbContext { private readonly IConfiguration _config; public DbSet<Client> Client { get; set; } public PrimaryDatabaseContext(DbContextOptions<PrimaryDatabaseContext> options, IConfiguration config) : base(options) { _config = config; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=LeonClientTracker.db"); //optionsBuilder.UseSqlite("Data Source=/home/znick46/LeonClientApp/LeonClientApp/LeonClientTracker.db"); // Find a way to get the root of this app directory path instead of hard code } // Sample code for relationships and table init protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Client>() .ToTable("Client") .HasKey(k => k.Id); } // Perhaps put this in it's own file later //public class Client //{ // [Required] // public int Id { get; set; } // public string firstName { get; set; } // public string lastName { get; set; } // public DateTime birthday { get; set; } // Todo Consider update type in future // public int totalSpending { get; set; } //} } }
namespace BettingSystem.Infrastructure.Teams.Repositories { using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Application.Teams; using Application.Teams.Queries.All; using Application.Teams.Queries.Coaches; using Application.Teams.Queries.Players; using AutoMapper; using Common.Repositories; using Domain.Teams.Models; using Domain.Teams.Repositories; using Microsoft.EntityFrameworkCore; using Persistence; internal class TeamRepository : DataRepository<TeamsDbContext, Team>, ITeamDomainRepository, ITeamQueryRepository { private readonly IMapper mapper; public TeamRepository(TeamsDbContext db, IMapper mapper) : base(db) => this.mapper = mapper; public async Task<bool> Delete( int id, CancellationToken cancellationToken = default) { var team = await this.Data.Teams.FindAsync(id); if (team == null) { return false; } this.Data.Teams.Remove(team); await this.Data.SaveChangesAsync(cancellationToken); return true; } public async Task<Team?> Find( int id, CancellationToken cancellationToken = default) => await this .All() .Where(t => t.Id == id) .FirstOrDefaultAsync(cancellationToken); public async Task<Coach?> GetCoach( string name, CancellationToken cancellationToken = default) => await this .AllCoaches() .Where(c => c.Name == name) .FirstOrDefaultAsync(cancellationToken); public async Task<IEnumerable<GetAllTeamsResponseModel>> GetTeamsListing( CancellationToken cancellationToken = default) => await this.mapper .ProjectTo<GetAllTeamsResponseModel>(this .AllAsNoTracking()) .ToListAsync(cancellationToken); public async Task<IEnumerable<GetCoachesResponseModel>> GetCoachesListing( CancellationToken cancellationToken = default) => await this.mapper .ProjectTo<GetCoachesResponseModel>(this .AllCoaches()) .ToListAsync(cancellationToken); public async Task<IEnumerable<GetTeamPlayersResponseModel>> GetTeamPlayersListing( int teamId, CancellationToken cancellationToken = default) => await this.mapper .ProjectTo<GetTeamPlayersResponseModel>(this .AllAsNoTracking() .Where(t => t.Id == teamId) .SelectMany(t => t.Players)) .ToListAsync(cancellationToken); private IQueryable<Coach> AllCoaches() => this .Data .Coaches .AsNoTracking(); } }
namespace gView.Framework.Carto { public class FeatureCounter { public int Counter; } }
using alg.graph; using System; using System.Collections.Generic; using System.Linq; /* * tags: K subsets with equal sum, TSP * It is similar with TSP(Travelling Salesman Problem). It's easy to solve using backtracking with much more complex. * Here, it can be solved in O(n^2*2^n) using Dynamic Programming with Bit Mask. */ namespace alg.dp { public class KSubsets { /* * Time(n*2^n), Space(2^n) * dp[S] is the sum of nodes in subset S * dp[S] is initialized to invalid number[-1], and is set only if dp[S-{i}] is valid and num[i] can fit into the group * (dp[S-{i}] % target) + nums[i] <= target, where target is sum of a partition = sum(nums)/k * Lc698. Partition to K Equal Sum Subsets */ bool CanPartitionKSubsets(int[] nums, int k) { if (k == 1) return true; int n = nums.Length, sum = nums.Sum(); if (sum % k != 0) return false; Array.Sort(nums); if (nums.Last() > sum / k) return false; int target = sum / k; var dp = new int[1 << n]; Array.Fill(dp, -1); dp[0] = 0; for (int fromMask = 0; fromMask < dp.Length; fromMask++) { if (dp[fromMask] == -1) continue; for (int i = 0; i < n; i++) { int toMask = fromMask | (1 << i); if (toMask == fromMask) continue; if ((dp[fromMask] % target) + nums[i] > target) // a little short cut, break; // as the current one [and all after as nums are sorted] is too big to fit into current group dp[toMask] = dp[fromMask] + nums[i]; // set the valid sum } } return dp.Last() == sum; } public void Test() { var nums = new int[] { 4, 3, 2, 3, 5, 2, 1 }; Console.WriteLine(CanPartitionKSubsets(nums, 4) == true); nums = new int[] { 1, 2, 3, 4 }; Console.WriteLine(CanPartitionKSubsets(nums, 3) == false); nums = new int[] { 18, 20, 39, 73, 96, 99, 101, 111, 114, 190, 207, 295, 471, 649, 700, 1037 }; Console.WriteLine(CanPartitionKSubsets(nums, 4) == true); } } }
using Bank.DataAccess; using Bank.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Bank.Controllers { public class BankController : Controller { private IBankRepository repo; public BankController(IBankRepository repo) { this.repo = repo; } public BankController() { repo = new BankRepository(); } public ActionResult Index() { return View(); } public ViewResult Deposit(int id) { var tr = new Transaction { AccountToId = id }; return View(tr); } [HttpPost] public ActionResult Deposit(int AccountToId, decimal Amount) { repo.Deposit(AccountToId, Amount); return View(); } } }
using Project.Interface; using Project.Presenter; using System; using System.Data; using System.Windows.Forms; namespace Project.View { public partial class ScheduleTime : Form { SubjectEventScheduler presenter; DataRow dr; ISubjectEventScheduler iSubjectEventScheduler; DataTable eventList = new DataTable(); int selectedID = 0; public ScheduleTime(ISubjectEventScheduler iSubjectEventScheduler, DataRow dr) { presenter = new SubjectEventScheduler(iSubjectEventScheduler); InitializeComponent(); loadItems(dr); } private void loadItems(DataRow dr) { this.dr = dr; lblEventName.Text = dr["Description"].ToString(); dateTimePicker1.Format = DateTimePickerFormat.Time; dateTimePicker1.ShowUpDown = true; selectedID = Convert.ToInt32(dr["study_details_id"].ToString()); presenter.loadScheduledTime(selectedID, dataGridView1); } private void button1_Click(object sender, System.EventArgs e) { int selectedID = Convert.ToInt32(dr["study_details_id"].ToString()); presenter.submitScheduledTime(selectedID,dateTimePicker1.Value); presenter.loadScheduledTime(selectedID, dataGridView1); numSched.Text = "Schedules:" + dataGridView1.RowCount.ToString(); } private void button2_Click(object sender, EventArgs e) { presenter.showStudyHelper(dataGridView1.SelectedRows[0].Index); loadItems(dr); } private void ScheduleTime_Load(object sender, EventArgs e) { numSched.Text = "Schedules:" + dataGridView1.RowCount.ToString(); } private void close_btn_Click(object sender, EventArgs e) { this.Close(); } private void minimize_btn_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Collections.Generic; using System.ComponentModel.Design; using System.Linq; using AkkaOverview.Oanda.Library.Contracts; using AkkaOverview.Oanda.Library.Factories; using AkkaOverview.Oanda.Library.Models; using AkkaOverview.Providers; using AkkaOverview.Providers.Contracts; namespace AkkaOverviewTest { [TestClass] public class TickDataProviderShould { private readonly IStreamProvider _tickProvider; private readonly Mock<IStreamingDataService> _serviceMock; private readonly Candle _candle; public TickDataProviderShould() { _serviceMock = new Mock<IStreamingDataService>(); _tickProvider = new StreamProvider(StreamingSource.OandaAPI); _candle = new Candle() { Time = "1"}; } [TestMethod] public void Return_Data_When_Connected() { _serviceMock.Setup(s => s.Connect()).Returns(true); _serviceMock.Setup(s => s.GetData<Candle>(It.IsAny<string>(),It.IsAny<Action<IEnumerable<Candle>>>())).Returns(new List<Candle>() { _candle }); //sut _tickProvider.GetData<Candle>("MSFT"); _serviceMock.VerifyAll(); CollectionAssert.Contains(data.ToList(), _candle); } [TestMethod] public void Return_Empty_List_When_Not_Connected() { _serviceMock.Setup(s => s.Connect()).Returns(false); //sut ITickProvider provider = new TickProvider(_serviceMock.Object); var data = provider.GetData<Candle>("MSFT"); _serviceMock.VerifyAll(); _serviceMock.Verify(s => s.GetData<Candle>(It.IsAny<string>()), Times.Never); CollectionAssert.AreEquivalent(data.ToList(), Enumerable.Empty<Candle>().ToList()); } [TestMethod] [ExpectedException(typeof(CheckoutException))] public void Get_Exception_When_Service_Throw_Unhandled_Exception() { _serviceMock.Setup(s => s.Connect()).Returns(true); _serviceMock.Setup(s => s.GetData<Candle>(It.IsAny<string>())).Throws(new CheckoutException()); //sut ITickProvider provider = new TickProvider(_serviceMock.Object); var data = provider.GetData<Candle>("MSFT"); _serviceMock.VerifyAll(); _serviceMock.Verify(s => s.GetData<Candle>(It.IsAny<string>()), Times.Never); } } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.Experimental.UIElements; using UnityEngine.UI; public class Player : MonoBehaviour { public int lives; public float speed; public Animator anim; void Start () { } void Update () { //pega os inputs 1, 0 ou -1; float x = Input.GetAxisRaw("Horizontal"); float y = Input.GetAxisRaw("Vertical"); Vector2 direction = new Vector2(x,y).normalized; Movement(direction); } void Movement(Vector2 direction) {//os quatro limites da tela, esquerda, direia, cima e baixo; Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0)); Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1)); // max da tela somados ou subtraidos a metada do tamanho da nave , para não ultrapassar metade dela para fora; max.x = max.x - 0.7f; min.x = min.x + 0.7f; max.y = max.y - 0.3f; min.y = min.y + 1.1f; //movimentação da nave Vector2 pos = transform.position; pos += direction * speed * Time.deltaTime; //calculo para nao permitir a nave ir para fora da tela; pos.x = Mathf.Clamp(pos.x, min.x, max.x); pos.y = Mathf.Clamp(pos.y, min.y, max.y); //posição nova definida; if (direction.y > 0) { anim.SetBool("IsMovingDown",false); anim.SetBool("IsMovingUp",true); }else if (direction.y < 0) { anim.SetBool("IsMovingUp",false); anim.SetBool("IsMovingDown",true); } else { anim.SetBool("IsMovingUp",false); anim.SetBool("IsMovingDown",false); } transform.position = pos; } private void OnCollisionEnter2D(Collision2D other) { print(other.gameObject); } }
namespace DChild.Gameplay.Systems.Serialization { public interface ISerializer { void Save(); void Load(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class TareaIndividual : System.Web.UI.Page { webservicio.Webservice2Client conec = new webservicio.Webservice2Client(); protected void Page_Load(object sender, EventArgs e) { } protected void Button4_Click(object sender, EventArgs e) { string aa = coditarea.Text; string bb = nombret.Text; string cc = descrip.Text; string dd = fechaitarea.Text; string ss = requisitos.Text; int ww = Convert.ToInt32(pagot.Text); string mm = nicktarea.Text; conec.CrearTareaIndividual(aa, bb, cc, dd, ss, ww, mm); coditarea.Text = ""; nombret.Text = ""; descrip.Text = ""; fechaitarea.Text = ""; requisitos.Text = ""; pagot.Text = ""; nicktarea.Text = ""; } protected void Button5_Click1(object sender, EventArgs e) { string a2 = nt.Text; string b2 = nc.Text; conec.DetalleTareaIndividual(a2, b2); nt.Text = ""; nc.Text = ""; } protected void Button6_Click(object sender, EventArgs e) { string[] Lista; Lista = conec.Verpartarea("", t12.Text); TableCell c1 = new TableCell(); c1.Text = "Nombre"; TableRow fila = new TableRow(); fila.Controls.Add(c1); Table1.Controls.Add(fila); for (int i = 0; i < Lista.Length; i = i + 1) { TableCell casilla1 = new TableCell(); casilla1.Text = Lista[i]; TableRow fila1 = new TableRow(); fila1.Controls.Add(casilla1); Table1.Controls.Add(fila1); } } }
using ServiceStack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TomKlonowski.Api.Model.Request { [Route("/note", "POST")] public class CreateNoteRequest { public string Title { get; set; } public string Description { get; set; } } [Route("/note/{NoteId}", "GET")] public class GetNoteRequest { [ApiMember(Name = "NoteId", ParameterType = "query", Description = "Id of the Note to get", DataType = "int", IsRequired = true)] public int NoteId { get; set; } } }
namespace RosPurcell.Web.Constants.Images { public class BreakPointDefinition { public int Width { get; set; } public int Height { get; set; } public int? MaxWidth { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CEMAPI.Models { public class TransitionApprovalPendingDetail { public int? ProjectId { get; set; } public string ProjectColor { get; set; } public string ProjectCode { get; set; } public string ProjectName { get; set; } public int TowerId { get; set; } public string TowerName { get; set; } public int ProductId { get; set; } public string ProductCode { get; set; } public string UnitNumber { get; set; } public string CustomerName { get; set; } public int OfferID { get; set; } public string Notes { get; set; } public decimal? Area { get; set; } public double? Value { get; set; } public decimal? Received { get; set; } public decimal? Balance { get; set; } public decimal? DueNow { get; set; } public decimal? CumulativeDue { get; set; } public string CustomerId { get; set; } public string SaleOrderId { get; set; } public string CustomerEmailID { get; set; } public string CEMManager { get; set; } public string Stage { get; set; } public string CustomerMobile { get; set; } public decimal? InvoicedAmount { get; set; } public DateTime ? OfferCancelledDate { get; set; } public DateTime? PromisedHandOverDate { get; set; } public string CancelRequestStatus { get; set; } public decimal? ProposedRefundAmount { get; set; } } }
using Euler_Logic.Helpers; using System.Collections.Generic; namespace Euler_Logic.Problems { public class Problem133 : ProblemBase { private PrimeSieveWithPrimeListULong _primes = new PrimeSieveWithPrimeListULong(); private Dictionary<ulong, bool> _isGood = new Dictionary<ulong, bool>(); /* We can easily determine when a single prime is divisible by R(n) by starting with x = 1, then continue to do x = (x * 10 + 1) % prime until x equals 0. For example, if p = 7, then: x = 1 x = (1 * 10 + 1) = 11 % 7 = 4 x = (4 * 10 + 1) = 41 % 7 = 6 x = (6 * 10 + 1) = 61 % 7 = 5 x = (5 * 10 + 1) = 51 % 7 = 2 x = (2 * 10 + 1) = 21 % 7 = 0 I can be observed that when p = 7, then there are 6 iterations. Now instead of looking at the prime, let's look at the iteration length (l). If p = 7, then l = 6. The question is, after 10 iterations, will x = 0? No, because 10 % 6 = 4. What about after 100 iterations? Well then we simply multiply 4 by 10 (40) and return 40 % 6. That gives us 4 again. So because we got 4 twice, we know that p = 7 will never give us a number divisible by R(10^n). Do this for all prime numbers below 100000. Many primes share the same length (l), so use a hash to store all the answers for each discovered (l). */ public override string ProblemName { get { return "133: Repunit nonfactors"; } } public override string GetAnswer() { ulong max = 100000; _primes.SievePrimes(max); return Solve().ToString(); } private ulong Solve() { _isGood.Add(1, true); ulong sum = 0; foreach (var prime in _primes.Enumerate) { if (IsGood(prime)) { sum += prime; } } return sum; } private bool IsGood(ulong prime) { ulong length = GetPatternLength(prime); if (!_isGood.ContainsKey(length)) { var ten = 10 % length; HashSet<ulong> found = new HashSet<ulong>(); while (ten != 0) { ten = (ten * 10) % length; if (found.Contains(ten)) { _isGood.Add(length, true); return true; } else { found.Add(ten); } } _isGood.Add(length, false); return false; } return _isGood[length]; } private ulong GetPatternLength(ulong prime) { ulong num = 11 % prime; ulong start = num; ulong count = 0; do { num = (num * 10 + 1) % prime; count++; } while (num != start); return count; } } }
using UnityEngine; using System.Collections; public class InputDelegates : MonoBehaviour { public delegate void InputDelegate(); public delegate void MovementDelegate(Vector2 moveVector); public static event MovementDelegate MovementInput; public static event InputDelegate AttackInput; public static event InputDelegate JumpInput; void Update () { CheckForInput(); } void CheckForInput() { if (MovementInput != null && Input.GetButton(InputAxis.MOVEHORIZONTAL)) { MovementInput(new Vector2 (Input.GetAxis(InputAxis.MOVEHORIZONTAL),0)); } if(AttackInput != null && Input.GetButtonDown(InputAxis.ATTACK)) { AttackInput(); } if (JumpInput != null && Input.GetButtonDown(InputAxis.JUMP)) { JumpInput(); } } }
using System; using FluentAssertions; using NUnit.Framework; namespace NumberToWordsService.WCF.UnitTests { [TestFixture] public class CreatingMoney { [Test] public void WhenInvalidTextIsPassedThenArgumentExceptionIsThrown() { Action action = () => { var x = new Money("abc"); }; action.ShouldThrow<ArgumentException>(); } [Test] public void WhenTooBigNumberIsPassedThenArgumentOutOfRangeExceptionIsThrown() { var multiplier = WordTables.NumberTypes.Length * 3; Action action = () => { var x = new Money((Math.Pow(10, multiplier)+1).ToString()); }; action.ShouldThrow<ArgumentOutOfRangeException>(); } [Test] public void WhenNumberHasMoreThan2DecimalsThenArgumentOutOfRangeExceptionIsThrown() { Action action = () => { var x = new Money("0,123"); }; action.ShouldThrow<ArgumentOutOfRangeException>(); } [Test] public void WhenIntegerTextValueIsPassedThenMoneyIsCreated() { var money = new Money("123"); money.Dollars.Should().Be(123); money.Cents.Should().Be(0); } [Test] public void WhenDeciamlTextValueIsPassedThenMoneyIsCreated() { var money = new Money("123,45"); money.Dollars.Should().Be(123); money.Cents.Should().Be(45); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Forecast.io.Entities; using Forecast.io.Extensions; namespace SimplyWeather.Models { public class ForcastIoDataProvider : IWeatherDataProvider { public async Task<WeatherData> GetWeather() { var settings = Properties.Settings.Default; var units = settings.Celsius ? Unit.ca : Unit.us; var forecast = new ForecastIORequest(settings.ApiKey, settings.Latitude, settings.Longitude, units); var weather = await forecast.Get(); if (weather == null || weather.currently == null || weather.daily == null) return null; var weatherData = new WeatherData { Location = settings.LocationName, Celsius = settings.Celsius, Icon = IconToMateocon(weather.currently.icon), CurrentTemperature = Temperature(weather.currently.temperature), FeelsLikeTemperature = Temperature(weather.currently.apparentTemperature), Summary = weather.currently.summary ?? "N/A", LongSummary = weather.daily.summary ?? "N/A", Wind = WindSummary(weather.currently.windSpeed, weather.currently.windBearing, settings.Celsius), Humidity = Probability(weather.currently.humidity), Time = weather.currently.time.ToDateTime().ToLocalTime().ToShortTimeString(), PoweredBy = "Powered by Forecast", Link = "http://forecast.io", Alert = (weather.alerts != null && weather.alerts.Count > 0) ? weather.alerts[0].title : string.Empty, AlertLink = (weather.alerts != null && weather.alerts.Count > 0) ? weather.alerts[0].uri : string.Empty, Forecasts = new ObservableCollection<WeatherForecast>(GetForecasts(weather.daily.data)) }; weatherData.Forecasts[0].Day = "Today"; return weatherData; } private static string WindSummary(float speed, float bearing, bool celsius) { if (speed < 1) return "Calm"; return string.Format(CultureInfo.InvariantCulture, "{0} {1} {2}", Round(speed), celsius ? "kph" : "mph", WindRose(bearing)); } private static string WindRose(float bearing) { if (bearing < 30) return "N"; if (bearing < 60) return "NE"; if (bearing < 110) return "E"; if (bearing < 150) return "SE"; if (bearing < 210) return "S"; if (bearing < 240) return "SW"; if (bearing < 300) return "W"; if (bearing < 330) return "NW"; return "N"; } private static IEnumerable<WeatherForecast> GetForecasts(IEnumerable<DailyForecast> forecasts) { return forecasts.Select(f => new WeatherForecast { Day = f.time.ToDateTime().ToString("dddd"), Low = Temperature(f.temperatureMin), High = Temperature(f.temperatureMax), Icon = IconToMateocon(f.icon), Summary = f.summary, PrecipType = f.precipType, PrecipProbability = Probability(f.precipProbability) }); } private static readonly Dictionary<string, string> MateoconsDictionary = new Dictionary<string, string> { {"clear-day", "B"}, {"clear-night", "C"}, {"rain", "R"}, {"snow", "U"}, {"sleet", "X"}, {"wind", "F"}, {"fog", "M"}, {"cloudy", "N"}, {"partly-cloudy-day", "H"}, {"partly-cloudy-night", "I"}, {"hail", "X"}, {"thunderstorm", "O"}, {"tornado", "F"} }; private static string IconToMateocon(string icon) { string mateocon; return MateoconsDictionary.TryGetValue(icon ?? "", out mateocon) ? mateocon : ")"; } private static string Temperature(float temperature) { return Round(temperature).ToString(CultureInfo.InvariantCulture); } private static float Round(float value) { return (float) Math.Round(value); } private static string Probability(float probability) { return string.Format(CultureInfo.InvariantCulture, "{0}%", Round(probability*100)); } } }
using Microsoft.AspNetCore.Identity; using System.ComponentModel.DataAnnotations; namespace Tndm_ArtShop.Data { public class ApplicationUser : IdentityUser { [Required(ErrorMessage = "Unesite ime.")] [StringLength(30)] public string Ime { get; set; } [Required(ErrorMessage = "Unesite prezime.")] [StringLength(30)] public string Prezime { get; set; } [Required(ErrorMessage = "Unesite drzavu.")] [StringLength(70)] public string Drzava { get; set; } [Required(ErrorMessage = "Unesite grad.")] [StringLength(70)] public string Grad { get; set; } [Required(ErrorMessage = "Unesite adresu.")] [StringLength(100)] public string Adresa { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _13.Modify_Bit { class ModifyBit { static void Main(string[] args) { ulong number = ulong.Parse(Console.ReadLine()); byte position = byte.Parse(Console.ReadLine()); byte bitValue = byte.Parse(Console.ReadLine()); ulong LastBitValue; ulong mask = 1; LastBitValue = (number >> position) & 1; //Checks the value of the numbersBit and the input value of the bit if (LastBitValue == 0 && bitValue == 0) { Console.WriteLine(number); } else if (LastBitValue == 0 && bitValue == 1) { mask = mask << position; Console.WriteLine(number | mask); } else if (LastBitValue == 1 && bitValue == 0) { mask = ~(mask << position); Console.WriteLine(number & mask); } else if (LastBitValue == 1 && bitValue == 1) { Console.WriteLine(number); } } } }
using System.ComponentModel; using CoreGraphics; using Foundation; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using CustomXamarinControls; using CustomXamarinControls.iOS; [assembly: ExportRenderer(typeof(LabelStriked), typeof(LabelStrikedRenderer))] namespace CustomXamarinControls.iOS { public class LabelStrikedRenderer : LabelRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Label> e) { base.OnElementChanged(e); if (Control != null) { //Control.BorderStyle = UITextBorderStyle.None; //Control.BackgroundColor = UIColor.Clear; //Control.TintColor = UIColor.White; //Control.LeftView = new UIView(new CGRect(0, 0, 15, 10)); //Control.LeftViewMode = UITextFieldViewMode.Always; UpdateStrikeThrough(e.NewElement as LabelStriked); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == nameof(LabelStriked.IsStrikeThrough)) { UpdateStrikeThrough(sender as LabelStriked); } } private void UpdateStrikeThrough(LabelStriked label) { var text = new NSMutableAttributedString(Control.AttributedText); text.SetAttributes(new UIStringAttributes { StrikethroughStyle = label?.IsStrikeThrough == true ? NSUnderlineStyle.Single : NSUnderlineStyle.None }, new NSRange(0, text.Length)); Control.AttributedText = text; } } }
using UnityEngine; using UnityAtoms.MonoHooks; namespace UnityAtoms.MonoHooks { /// <summary> /// Event Instancer of type `ColliderGameObject`. Inherits from `AtomEventInstancer&lt;ColliderGameObject, ColliderGameObjectEvent&gt;`. /// </summary> [EditorIcon("atom-icon-sign-blue")] [AddComponentMenu("Unity Atoms/Event Instancers/ColliderGameObject Event Instancer")] public class ColliderGameObjectEventInstancer : AtomEventInstancer<ColliderGameObject, ColliderGameObjectEvent> { } }
using System; using System.Collections.Generic; using System.Text; namespace DBDiff.Schema.Events { public class Progress { public delegate void ProgressHandler(object sender, ProgressEventArgs e); } }
using Terminal.Gui; namespace UICatalog.Scenarios { [ScenarioMetadata (Name: "Borders Comparisons", Description: "Compares Window, Toplevel and FrameView borders.")] [ScenarioCategory ("Layout")] [ScenarioCategory ("Borders")] public class BordersComparisons : Scenario { public override void Init (ColorScheme colorScheme) { Application.Init (); var borderStyle = BorderStyle.Double; var drawMarginFrame = false; var borderThickness = new Thickness (1, 2, 3, 4); var borderBrush = Color.BrightMagenta; ; var padding = new Thickness (1, 2, 3, 4); var background = Color.Cyan; var effect3D = true; var win = new Window (new Rect (5, 5, 40, 20), "Test", 8, new Border () { BorderStyle = borderStyle, DrawMarginFrame = drawMarginFrame, BorderThickness = borderThickness, BorderBrush = borderBrush, Padding = padding, Background = background, Effect3D = effect3D }); var tf1 = new TextField ("1234567890") { Width = 10 }; var button = new Button ("Press me!") { X = Pos.Center (), Y = Pos.Center (), }; button.Clicked += () => MessageBox.Query (20, 7, "Hi", "I'm a Window?", "Yes", "No"); var label = new Label ("I'm a Window") { X = Pos.Center (), Y = Pos.Center () - 3, }; var tv = new TextView () { Y = Pos.AnchorEnd (2), Width = 10, Height = Dim.Fill (), Text = "1234567890" }; var tf2 = new TextField ("1234567890") { X = Pos.AnchorEnd (10), Y = Pos.AnchorEnd (1), Width = 10 }; win.Add (tf1, button, label, tv, tf2); Application.Top.Add (win); var top2 = new Border.ToplevelContainer (new Rect (50, 5, 40, 20), new Border () { BorderStyle = borderStyle, DrawMarginFrame = drawMarginFrame, BorderThickness = borderThickness, BorderBrush = borderBrush, Padding = padding, Background = background, Effect3D = effect3D, Title = "Test2" }) { ColorScheme = Colors.Base, }; var tf3 = new TextField ("1234567890") { Width = 10 }; var button2 = new Button ("Press me!") { X = Pos.Center (), Y = Pos.Center (), }; button2.Clicked += () => MessageBox.Query (20, 7, "Hi", "I'm a Toplevel?", "Yes", "No"); var label2 = new Label ("I'm a Toplevel") { X = Pos.Center (), Y = Pos.Center () - 3, }; var tv2 = new TextView () { Y = Pos.AnchorEnd (2), Width = 10, Height = Dim.Fill (), Text = "1234567890" }; var tf4 = new TextField ("1234567890") { X = Pos.AnchorEnd (10), Y = Pos.AnchorEnd (1), Width = 10 }; top2.Add (tf3, button2, label2, tv2, tf4); Application.Top.Add (top2); var frm = new FrameView (new Rect (95, 5, 40, 20), "Test3", null, new Border () { BorderStyle = borderStyle, DrawMarginFrame = drawMarginFrame, BorderThickness = borderThickness, BorderBrush = borderBrush, Padding = padding, Background = background, Effect3D = effect3D }) { ColorScheme = Colors.Base }; var tf5 = new TextField ("1234567890") { Width = 10 }; var button3 = new Button ("Press me!") { X = Pos.Center (), Y = Pos.Center (), }; button3.Clicked += () => MessageBox.Query (20, 7, "Hi", "I'm a FrameView?", "Yes", "No"); var label3 = new Label ("I'm a FrameView") { X = Pos.Center (), Y = Pos.Center () - 3, }; var tv3 = new TextView () { Y = Pos.AnchorEnd (2), Width = 10, Height = Dim.Fill (), Text = "1234567890" }; var tf6 = new TextField ("1234567890") { X = Pos.AnchorEnd (10), Y = Pos.AnchorEnd (1), Width = 10 }; frm.Add (tf5, button3, label3, tv3, tf6); Application.Top.Add (frm); Application.Run (); } public override void Run () { // Do nothing } } }
using Com.Colin.Lib; using System; using System.Collections; namespace Com.Colin.IbatisDataAccess { public class BaseBL : HTAbstractBLBaseTransactionLogic { public static IDataAccess doAccess; public BaseBL() { doAccess = dataAccess; } public BaseBL(string sqlConfigName) : base(sqlConfigName) { doAccess = dataAccess; } public T DBOperation<T>(Func<Hashtable, T> operation, Hashtable inParameter) { try { T result = operation(inParameter); return result; } catch (Exception ex) { LogHelper.WriteLog(this.GetType(), ex); throw ex; } finally { this.dataAccess.Close(); } } public T DBOperationWithTrans<T>(Func<Hashtable, T> operation, Hashtable inParameter) { try { this.dataAccess.BeginTransaction(); T result = operation(inParameter); this.dataAccess.Commit(); return result; } catch (Exception ex) { this.dataAccess.Rollback(); LogHelper.WriteLog(this.GetType(), ex); throw ex; } finally { this.dataAccess.Close(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; using UnityEngine.UI; using TMPro; public class PlayerListingsMenu : MonoBehaviourPunCallbacks, IPunCallbacks { [SerializeField] private Button startButton = null; [SerializeField] private GameObject Panel_HostGame = null; [SerializeField] private GameObject Panel_MainMenu = null; [SerializeField] private GameObject Panel_CurrentRoom = null; [SerializeField] private TMP_Text lobbyName = null, lobbyCapacity = null; [SerializeField] private List<PlayerListing> playerListings = new List<PlayerListing>(); private int numberOfPlayers = 0, maxPlayers = 8; public override void OnJoinedRoom() { Panel_HostGame.SetActive(false); Panel_CurrentRoom.SetActive(true); lobbyName.text = PhotonNetwork.CurrentRoom.Name; maxPlayers = PhotonNetwork.CurrentRoom.MaxPlayers; lobbyCapacity.text = "" + numberOfPlayers + " / " + maxPlayers; GetCurrentRoomPlayers(); } void Update() { if(PhotonNetwork.InRoom) { if(PhotonNetwork.CurrentRoom.PlayerCount > 1) { startButton.interactable = PhotonNetwork.IsMasterClient; } } } void GetCurrentRoomPlayers() { if (!PhotonNetwork.IsConnected) return; if (PhotonNetwork.CurrentRoom == null || PhotonNetwork.CurrentRoom.Players == null) return; foreach (KeyValuePair<int, Player> playerInfo in PhotonNetwork.CurrentRoom.Players) { AddPlayerListing(playerInfo.Value); } } void AddPlayerListing(Player player) { int index = playerListings.FindIndex(x => x._player == player); if (index == -1) { playerListings[numberOfPlayers].SetPlayerInfo(player); numberOfPlayers++; } lobbyCapacity.text = "" + numberOfPlayers + " / " + maxPlayers; } public override void OnPlayerEnteredRoom(Player newPlayer) { AddPlayerListing(newPlayer); } public override void OnPlayerLeftRoom(Player otherPlayer) { int index = playerListings.FindIndex(x => x._player == otherPlayer); if (index != -1) { playerListings[index].ClearListing(); } numberOfPlayers--; lobbyCapacity.text = "" + numberOfPlayers + " / " + maxPlayers; } public void OnClick_LeaveRoom() { PhotonNetwork.LeaveRoom(); } public override void OnLeftRoom() { foreach (PlayerListing playerList in playerListings) { playerList.ClearListing(); } numberOfPlayers = 0; Panel_MainMenu.SetActive(true); Panel_CurrentRoom.SetActive(false); //StartCoroutine("LeaveLobbyIE"); } IEnumerator LeaveLobbyIE() { yield return new WaitForSeconds(.5f); PhotonNetwork.JoinLobby(); } public void OnClick_StartGame() { if (PhotonNetwork.IsMasterClient) { PhotonNetwork.CurrentRoom.IsOpen = false; PhotonNetwork.CurrentRoom.IsVisible = false; PhotonNetwork.LoadLevel("Game"); } } public override void OnMasterClientSwitched(Player newMasterClient) { int index = playerListings.FindIndex(x => x._player == newMasterClient); if(index != -1) { playerListings[index].SetPlayerInfo(newMasterClient); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebQz.Models; namespace WebQz.Service { public interface IQuestionsService { public IEnumerable<Questions> Shuffle(); public void StartStopGame(Game game, string originalTitle, string start); public void ShowInfo(string someString, Game game); public bool GameProcess(Game game, string originalTitle, int maxSteps); public List<Questions> GetQuestions(); public List<string> GetRandomTitle(); public void SetQuestionValue(List<string> collection); public void SetRandomTitle(List<string> collection); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class BezierPath : MonoBehaviour { #region variables [SerializeField] private Vector3[] ControlPoints = new Vector3[4]; [SerializeField] private int segments = 10; [SerializeField] private Vector3[] bezierpoint; #endregion // Start is called before the first frame update void Start() { SetupCurve(); } #region BezierCalculations void SetupCurve() { bezierpoint = new Vector3[segments + 1]; float step = 1f / segments; float u = 0; for (int i = 0; i <= segments; i++) { bezierpoint[i] = Bezier(u,ControlPoints.Length - 1); u += step; } } Vector3 Bezier(float u, int n) { float acumX = 0; float acumY = 0; float acumZ = 0; for (int i = 0; i < ControlPoints.Length; i++) { float blend = Blending(u,n,i); acumX += ControlPoints[i].x * blend; acumY += ControlPoints[i].y * blend; acumZ += ControlPoints[i].z * blend; } return new Vector3(acumX,acumY,acumZ); } float Blending(float u, int n, int k) { return Coefficient(n,k) * Mathf.Pow(u,k) * Mathf.Pow(1 - u,n - k); } int Coefficient (int n, int k) { return Factorial(n) / (Factorial(k) * Factorial(n - k)); } int Factorial (int value){ int accum = 1; for(int i = 1; i <= value; i++) { accum *= i; } return accum; } #endregion //Called each time the editor is modified void OnValidate() { SetupCurve(); } public Vector3[] GetBezierPoints() { return bezierpoint; } public int GetBezierPointsLength() { return segments + 1; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CheckPoint : MonoBehaviour { public GameObject poingLight; public GameObject globalLight; void OnTriggerEnter2D(Collider2D other) //플레이어 리셋 { if (other.gameObject.tag.Equals("Player")) { Destroy(poingLight); Instantiate(globalLight); } } }
using System; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HNDunit20 { public partial class frmBehavioural : Form { SpindleStack myst = new SpindleStack(); public frmBehavioural() { InitializeComponent(); } private void btnCollection_Click(object sender, EventArgs e) { ArrayList al = new ArrayList(); al.Add(1); al.Add(2); al.Add(3); al.Add(4); al.Add(5); string[] names = { "Fred", "Ted", "Zed", "Shed" }; lblOutput.Text = ""; IEnumerator ie = names.GetEnumerator(); while(ie.MoveNext()) { lblOutput.Text += ie.Current.ToString(); } } private void btnPush_Click(object sender, EventArgs e) { CDNode cd = new CDNode(); cd.Artist = txtData.Text; cd.Duration = Convert.ToInt32(nudMinutes.Value); myst.push(cd); } private void btnIterate_Click(object sender, EventArgs e) { lblOutput.Text = ""; //lblOutput.Text = myst.list(); Iterator it = myst.createIterator(); while(it.hasMore()) { lblOutput.Text += it.getNext() + "\n"; } } } }
using System; namespace SocketLite { public class RequestInfo { public string ClientId { get; set; } public string Handler { get; set; } public string Action { get; set; } public string ParamJson { get; set; } public DateTime RequestTime { get; set; } } }
using System; namespace TY.SPIMS.POCOs { public class CheckColumnModel { public int Id { get; set; } public string CheckNumber { get; set; } public string Bank { get; set; } public string Branch { get; set; } public decimal Amount { get; set; } public DateTime CheckDate { get; set; } public DateTime ClearingDate { get; set; } public bool IsDeleted { get; set; } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Text; using System.Collections; namespace VolumetricFogAndMist { public class VolumetricFogShaderOptions { public bool pendingChanges; public ShaderAdvancedOption[] options; public void ReadOptions() { pendingChanges = false; // Populate known options options = new ShaderAdvancedOption[] { new ShaderAdvancedOption { id = "FOG_ORTHO", name = "Orthographic Mode", description = "Enables support for orthographic camera projection." }, new ShaderAdvancedOption { id = "FOG_DEBUG", name = "Debug Mode", description = "Enables fog debug view." }, new ShaderAdvancedOption { id = "FOG_MASK", name = "Geometry Mask", description = "Enables mask defined by geometry volumes (meshes). Fog will only be visible inside the volumes." }, new ShaderAdvancedOption { id = "FOG_INVERTED_MASK", name = "Geometry Mask (Inverted)", description = "Enables mask defined by geometry volumes (meshes). Fog will NOT be visible through the volumes. Note: this option cannot be combined with the previous one." }, new ShaderAdvancedOption { id = "FOG_VOID_HEAVY_LOOP", name = "Raymarched Void Area", description = "Computes void within ray loop improving quality." }, new ShaderAdvancedOption { id = "FOG_OF_WAR_HEAVY_LOOP", name = "Raymarched Fog Of War", description = "Computes fog of war within ray loop improving quality." }, new ShaderAdvancedOption { id = "FOG_SMOOTH_SCATTERING", name = "Smooth Scattering Rays", description = "Adds blur passes to smooth light scattering rays." }, new ShaderAdvancedOption { id = "FOG_DIFFUSION", name = "Sun Light Diffusion", description = "Computes diffusion of Sun light across the fog." }, new ShaderAdvancedOption { id = "FOG_UNITY_DIR_SHADOWS", name = "Native Directional Shadows", description = "Use Unity directional shadow map to render shadows (Sun shadows option must be enabled)." }, new ShaderAdvancedOption { id = "FOG_DIR_SHADOWS_COOKIE", name = "Directional Light Cookie", description = "Enables directional light cookie sampling over fog shadow." }, new ShaderAdvancedOption { id = "FOG_MAX_POINT_LIGHTS", name = "", description = "", hasValue = true } }; Shader shader = Shader.Find("VolumetricFogAndMist/VolumetricFog"); if (shader != null) { string path = AssetDatabase.GetAssetPath(shader); string file = Path.GetDirectoryName(path) + "/VolumetricFogOptions.cginc"; string[] lines = File.ReadAllLines(file, Encoding.UTF8); for (int k = 0; k < lines.Length; k++) { for (int o = 0; o < options.Length; o++) { if (lines[k].Contains(options[o].id)) { options[o].enabled = !lines[k].StartsWith("//"); if (options[o].hasValue) { string[] tokens = lines[k].Split(null); if (tokens.Length > 2) { int.TryParse(tokens[2], out options[o].value); } } break; } } } } } public bool GetAdvancedOptionState(string optionId) { if (options == null) return false; for (int k = 0; k < options.Length; k++) { if (options[k].id.Equals(optionId)) { return options[k].enabled; } } return false; } public void UpdateAdvancedOptionsFile() { // Reloads the file and updates it accordingly Shader shader = Shader.Find("VolumetricFogAndMist/VolumetricFog"); if (shader != null) { string path = AssetDatabase.GetAssetPath(shader); string file = Path.GetDirectoryName(path) + "/VolumetricFogOptions.cginc"; string[] lines = File.ReadAllLines(file, Encoding.UTF8); for (int k = 0; k < lines.Length; k++) { for (int o = 0; o < options.Length; o++) { if (lines[k].Contains(options[o].id)) { if (options[o].hasValue) { lines[k] = "#define " + options[o].id + " " + options[o].value; } else { if (options[o].enabled) { lines[k] = "#define " + options[o].id; } else { lines[k] = "//#define " + options[o].id; } } break; } } } File.WriteAllLines(file, lines, Encoding.UTF8); // Save VolumetricFog.cs change int maxPointLights = GetOptionValue("FOG_MAX_POINT_LIGHTS"); bool enableSmoothScattering = GetAdvancedOptionState("FOG_SMOOTH_SCATTERING"); bool useUnityShadowMap = GetAdvancedOptionState("FOG_UNITY_DIR_SHADOWS"); bool useUnityDirectionalCookie = GetAdvancedOptionState("FOG_DIR_SHADOWS_COOKIE"); bool enableDiffusion = GetAdvancedOptionState("FOG_DIFFUSION"); file = Path.GetDirectoryName(path) + "/../../Scripts/VolumetricFogStaticParams.cs"; if (!File.Exists(file)) { Debug.LogError("VolumetricFogStaticParams.cs file not found!"); } else { lines = File.ReadAllLines(file, Encoding.UTF8); for (int k = 0; k < lines.Length; k++) { if (lines[k].Contains("MAX_POINT_LIGHTS")) { lines[k] = "public const int MAX_POINT_LIGHTS = " + maxPointLights + ";"; } else if (lines[k].Contains("LIGHT_SCATTERING_BLUR_ENABLED")) { string value = enableSmoothScattering ? "true" : "false"; lines[k] = "public const bool LIGHT_SCATTERING_BLUR_ENABLED = " + value + ";"; } else if (lines[k].Contains("USE_UNITY_SHADOW_MAP")) { string value = useUnityShadowMap ? "true" : "false"; lines[k] = "public const bool USE_UNITY_SHADOW_MAP = " + value + ";"; } else if (lines[k].Contains("LIGHT_DIFFUSION_ENABLED")) { string value = enableDiffusion ? "true" : "false"; lines[k] = "public const bool LIGHT_DIFFUSION_ENABLED = " + value + ";"; } else if (lines[k].Contains("USE_DIRECTIONAL_LIGHT_COOKIE")) { string value = useUnityDirectionalCookie ? "true" : "false"; lines[k] = "public const bool USE_DIRECTIONAL_LIGHT_COOKIE = " + value + ";"; } } File.WriteAllLines(file, lines, Encoding.UTF8); } } pendingChanges = false; AssetDatabase.Refresh(); } public int GetOptionValue(string id) { for (int k = 0; k < options.Length;k++) { if (options[k].hasValue && options[k].id.Equals(id)) { return options[k].value; } } return 0; } public void SetOptionValue(string id, int value) { for (int k = 0; k < options.Length; k++) { if (options[k].hasValue && options[k].id.Equals(id)) { options[k].value = value; } } } } public struct ShaderAdvancedOption { public string id; public string name; public string description; public bool enabled; public bool hasValue; public int value; } }
using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace MailSender { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class WpfMailSender : Window { public WpfMailSender() { InitializeComponent(); } } }
using System; using UnityEngine; using UnityEngine.Assertions; namespace UnityAtoms { /// <summary> /// A Variable Instancer is a MonoBehaviour that takes a variable as a base and creates an in memory copy of it OnEnable. /// This is handy when you want to use atoms for prefabs that are instantiated at runtime. Use together with AtomCollection to /// react accordingly when a prefab with an assoicated atom is added or deleted to the scene. /// </summary> /// <typeparam name="V">Variable of type T.</typeparam> /// <typeparam name="P">IPair of type `T`.</typeparam> /// <typeparam name="T">The value type.</typeparam> /// <typeparam name="E1">Event of type T.</typeparam> /// <typeparam name="E2">Event x 2 of type T.</typeparam> /// <typeparam name="F">Function of type T => T</typeparam> [EditorIcon("atom-icon-hotpink")] [DefaultExecutionOrder(Runtime.ExecutionOrder.VARIABLE_INSTANCER)] public abstract class AtomBaseVariableInstancer<T, V> : MonoBehaviour, IVariable<V> where V : AtomBaseVariable<T> { /// <summary> /// Getter for retrieving the in memory runtime variable. /// </summary> public V Variable { get => _inMemoryCopy; } /// <summary> /// Getter for retrieving the value of the in memory runtime variable. /// </summary> public T Value { get => _inMemoryCopy.Value; set => _inMemoryCopy.Value = value; } public virtual V Base { get => _base; } [SerializeField] [ReadOnly] protected V _inMemoryCopy = default(V); /// <summary> /// The variable that the in memory copy will be based on when created at runtime. /// </summary> [SerializeField] protected V _base = null; /// <summary> /// Override to add implementation specific setup on `OnEnable`. /// </summary> protected virtual void ImplSpecificSetup() { } private void OnEnable() { if (Base == null) { _inMemoryCopy = ScriptableObject.CreateInstance<V>(); } else { _inMemoryCopy = Instantiate(Base); } ImplSpecificSetup(); } } }
using System; using System.Collections; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; using HTB.Database; using HTB.Database.HTB.Views; using HTB.Database.LookupRecords; using HTB.v2.intranetx.util; using HTBUtilities; namespace HTB.v2.intranetx.search { public partial class Search : Page { private const string SessionSearchName = "Search_Record"; private int GegnerId; private int ClientId; private int AgId; private double TotalInkassoForderung = 0; private double TotalInkassoCharges = 0; private double TotalInkassoPaid = 0; private double TotalInterventionForderung = 0; private double TotalInterventionCharges = 0; private double TotalInterventionPaid = 0; private tblGegner currentGegner = null; private tblKlient currentClient = null; private tblAuftraggeber currentAg = null; protected void Page_Load(object sender, EventArgs e) { ClearScreen(); if (!IsPostBack) { GegnerId = GlobalUtilArea.GetZeroIfConvertToIntError(Request[GlobalHtmlParams.GEGNER_ID]); ClientId = GlobalUtilArea.GetZeroIfConvertToIntError(Request[GlobalHtmlParams.CLIENT_ID]); AgId = GlobalUtilArea.GetZeroIfConvertToIntError(Request[GlobalHtmlParams.AUFTRAGGEBER_ID]); var searchRec = (SearchRecord) Session[SessionSearchName]; PopulateFieldsFromSearchRecord(searchRec); if (GegnerId == 0 && ClientId == 0 && AgId == 0) { if (searchRec != null) { LookupName(searchRec); } } else if(GegnerId > 0) { ctlMessage.ShowInfo(GegnerId.ToString()); LookupGegner(); } else if (AgId > 0) { ctlMessage.ShowInfo(AgId.ToString()); LookupAg(); } } } #region Event Handlers protected void btnSubmit_Click(object sender, EventArgs e) { LookupName(new SearchRecord { SearchName = txtName.Text, SearchNumber = txtAkt.Text }); } protected void btnCancel_Click(object sender, EventArgs e) { } protected void gvGegner_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#2dc6ee'"); // when mouse leaves the row, change the bg color to its original value e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;"); e.Row.Attributes.Add("onClick", "location.href='Search.aspx?" + GlobalHtmlParams.GEGNER_ID + "=" + DataBinder.Eval(e.Row.DataItem, "ID") + "'"); // e.Row.Attributes.Add("onClick", "location.href='http://www.yahoo.com'"); // e.Row.Attributes.Add("onClick", "javascript:alert('here');"); } } protected void gvKlient_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#2dc6ee'"); // when mouse leaves the row, change the bg color to its original value e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;"); e.Row.Attributes.Add("onClick", "location.href='Search.aspx?"+GlobalHtmlParams.CLIENT_ID+"=" + DataBinder.Eval(e.Row.DataItem, "ID") + "'"); } } protected void gvAG_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#2dc6ee'"); // when mouse leaves the row, change the bg color to its original value e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;"); e.Row.Attributes.Add("onClick", "location.href='Search.aspx?" + GlobalHtmlParams.AUFTRAGGEBER_ID + "=" + DataBinder.Eval(e.Row.DataItem, "ID") + "'"); } } protected void gvInkasso_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#2dc6ee'"); // when mouse leaves the row, change the bg color to its original value e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;"); e.Row.Attributes.Add("onClick", "location.href='/v2/intranetx/aktenink/EditAktInk.aspx?" + GlobalHtmlParams.ID + "=" + DataBinder.Eval(e.Row.DataItem, "ID") + "&" + GlobalHtmlParams.RETURN_TO_URL_ON_CANCEL +"=" +GlobalHtmlParams.BACK+"'"); } } protected void gvIntervention_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#2dc6ee'"); // when mouse leaves the row, change the bg color to its original value e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;"); e.Row.Attributes.Add("onClick", "location.href='/v2/intranetx/aktenint/workaktint.aspx?" + GlobalHtmlParams.ID + "=" + DataBinder.Eval(e.Row.DataItem, "ID") + "'"); } } protected void gvGegnerAddress_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // when mouse is over the row, save original color to new attribute, and change it to highlight yellow color // e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#2dc6ee'"); // when mouse leaves the row, change the bg color to its original value // e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;"); // e.Row.Attributes.Add("onClick", "location.href='/v2/intranetx/aktenint/workaktint.aspx?" + GlobalHtmlParams.ID + "=" + DataBinder.Eval(e.Row.DataItem, "ID") + "'"); } } protected void gvGegnerPhone_RowCreated(object sender, GridViewRowEventArgs e) { } #endregion private void LookupName(SearchRecord searchRec) { var parameters = new ArrayList { new StoredProcedureParameter("countGegner", SqlDbType.Int, 1), new StoredProcedureParameter("countClients", SqlDbType.Int, 1), new StoredProcedureParameter("countAuftraggeber", SqlDbType.Int, 1), new StoredProcedureParameter("totalGegner", SqlDbType.Int, 0, ParameterDirection.Output), new StoredProcedureParameter("totalClients", SqlDbType.Int, 0, ParameterDirection.Output), new StoredProcedureParameter("totalAuftraggeber", SqlDbType.Int, 0, ParameterDirection.Output), new StoredProcedureParameter("name", SqlDbType.NVarChar, searchRec.SearchName) }; ArrayList[] lists = HTBUtils.GetMultipleListsFromStoredProcedure("spSearchDetail", parameters, new Type[] { typeof(GegnerDetailLookup), typeof(KlientDetailLookup), typeof(AuftraggeberDetailLookup) }); foreach (Object obj in parameters) { if(obj is ArrayList) { var outParams = (ArrayList) obj; foreach (StoredProcedureParameter outParam in outParams) { if(outParam.Name == "totalGegner") ShowFoundCounter(lblGegnerCount, outParam.Value.ToString()); else if (outParam.Name == "totalClients") ShowFoundCounter(lblClientCount, outParam.Value.ToString()); else if (outParam.Name == "totalAuftraggeber") ShowFoundCounter(lblAgCount, outParam.Value.ToString()); } } } PopulateGegnerGrid(lists[0]); PopulateKlientGrid(lists[1]); PopulateAgGrid(lists[2]); Session[SessionSearchName] = searchRec; } private void LookupGegner() { var parameters = new ArrayList { new StoredProcedureParameter("@gegnerID", SqlDbType.Int, GegnerId) }; ArrayList[] lists = HTBUtils.GetMultipleListsFromStoredProcedure("spGetAllAktsByGegnerID", parameters, new Type[] { typeof(tblGegner), typeof(tblGegnerAdressen), typeof(tblGegnerPhone), typeof(SearchAktLookup), typeof(SearchAktLookup) }); try { currentGegner = (tblGegner)lists[0][0]; if (currentGegner != null) { ctlMessage.ShowInfo(currentGegner.GegnerName2 + " " + currentGegner.GegnerName1 + "<br/><br/>" + currentGegner.GegnerLastStrasse + "<br/>" + currentGegner.GegnerLastZipPrefix + " - " + currentGegner.GegnerLastZip + " " + currentGegner.GegnerOrt); if(!string.IsNullOrEmpty(currentGegner.GegnerMemo)) lblGegnerMemo.Text = "<b>Schuldner Memo:</b><BR/>" + currentGegner.GegnerMemo+"<BR/>"; } } catch { } PopulateGegnerAddressGrid(lists[1]); PopulateGegnerPhoneGrid(lists[2]); PopulateInkassoGrid(lists[3], true); PopulateInterventionGrid(lists[4], true); tabContainer1.Visible = true; tabContainer1.Tabs[1].Visible = true; } private void LookupClient() { var parameters = new ArrayList { new StoredProcedureParameter("@clientID", SqlDbType.Int, ClientId) }; ArrayList[] lists = HTBUtils.GetMultipleListsFromStoredProcedure("spGetAllAktsByClientID", parameters, new Type[] { typeof(tblKlient), typeof(SearchAktLookup), typeof(SearchAktLookup) }); try { currentClient = (tblKlient)lists[0][0]; if (currentClient != null) { ctlMessage.ShowInfo(currentClient.KlientName1 + " " + currentClient.KlientName2 + "<br/><br/>" + currentClient.KlientStrasse + "<br/>" + currentClient.KlientStaat + " - " + currentClient.KlientPLZ + " " + currentClient.KlientOrt); if (!string.IsNullOrEmpty(currentClient.KlientMemo)) lblGegnerMemo.Text = "<b>Klient Memo:</b><BR/>" + currentClient.KlientMemo + "<BR/>"; } } catch { } PopulateInkassoGrid(lists[1], false, true); PopulateInterventionGrid(lists[2], false, true); tabContainer1.Visible = true; tabContainer1.Tabs[1].Visible = false; } private void LookupAg() { var parameters = new ArrayList { new StoredProcedureParameter("@auftraggeberID", SqlDbType.Int, AgId) }; ArrayList[] lists = HTBUtils.GetMultipleListsFromStoredProcedure("spGetAllAktsByAuftraggeberID", parameters, new Type[] { typeof(tblAuftraggeber), typeof(SearchAktLookup) }); try { currentAg = (tblAuftraggeber)lists[0][0]; if (currentAg != null) { ctlMessage.ShowInfo(currentAg.AuftraggeberName1 + " " + currentAg.AuftraggeberName2 + "<br/><br/>" + currentAg.AuftraggeberStrasse + "<br/>" + currentAg.AuftraggeberStaat + " - " + currentAg.AuftraggeberPLZ + " " + currentAg.AuftraggeberOrt); if (!string.IsNullOrEmpty(currentAg.AuftraggeberMemo)) lblGegnerMemo.Text = "<b>Klient Memo:</b><BR/>" + currentAg.AuftraggeberMemo + "<BR/>"; } } catch { } PopulateInterventionGrid(lists[1], false, true); tabContainer1.Visible = true; tabContainer1.Tabs[1].Visible = false; } private DataTable GetDataTableStructure() { var dt = new DataTable(); dt.Columns.Add(new DataColumn("ID", typeof(string))); dt.Columns.Add(new DataColumn("OldID", typeof(string))); dt.Columns.Add(new DataColumn("Name", typeof(string))); dt.Columns.Add(new DataColumn("LKZ", typeof(string))); dt.Columns.Add(new DataColumn("Ort", typeof(string))); dt.Columns.Add(new DataColumn("Strasse", typeof(string))); dt.Columns.Add(new DataColumn("DOB", typeof(string))); dt.Columns.Add(new DataColumn("InterventionAkte", typeof(string))); dt.Columns.Add(new DataColumn("InkassoAkte", typeof(string))); dt.Columns.Add(new DataColumn("InkassoBalance", typeof(string))); dt.Columns.Add(new DataColumn("Date", typeof(string))); return dt; } private DataTable GetAktDataTableStructure() { var dt = new DataTable(); dt.Columns.Add(new DataColumn("ID", typeof(string))); dt.Columns.Add(new DataColumn("AZ", typeof(string))); dt.Columns.Add(new DataColumn("AktEnteredDate", typeof(string))); dt.Columns.Add(new DataColumn("KlientName", typeof(string))); dt.Columns.Add(new DataColumn("GegnerInfo", typeof(string))); dt.Columns.Add(new DataColumn("AktStatus", typeof(string))); dt.Columns.Add(new DataColumn("AktCurStatus", typeof(string))); dt.Columns.Add(new DataColumn("Forderung", typeof(string))); dt.Columns.Add(new DataColumn("TotalCharges", typeof(string))); dt.Columns.Add(new DataColumn("TotalPaid", typeof(string))); dt.Columns.Add(new DataColumn("Balance", typeof(string))); return dt; } private DataTable GetPhoneDataTableStructure() { var dt = new DataTable(); dt.Columns.Add(new DataColumn("PhoneType", typeof(string))); dt.Columns.Add(new DataColumn("PhoneCountry", typeof(string))); dt.Columns.Add(new DataColumn("PhoneCity", typeof(string))); dt.Columns.Add(new DataColumn("Phone", typeof(string))); dt.Columns.Add(new DataColumn("PhoneDate", typeof(string))); dt.Columns.Add(new DataColumn("PhoneDescription", typeof(string))); return dt; } private void PopulateFieldsFromSearchRecord(SearchRecord searchRec) { if (searchRec != null) { txtName.Text = searchRec.SearchName; txtAkt.Text = searchRec.SearchNumber; } } protected string GetTotalInkassoForderung() { return HTBUtils.FormatCurrency(TotalInkassoForderung, true); } protected string GetTotalInkassoCharges() { return HTBUtils.FormatCurrency(TotalInkassoCharges, true); } protected string GetTotalInkassoPaid() { return HTBUtils.FormatCurrency(TotalInkassoPaid, true); } protected string GetTotalInkassoBalance() { return HTBUtils.FormatCurrency(TotalInkassoCharges - TotalInkassoPaid, true); } protected string GetTotalInterventionForderung() { return HTBUtils.FormatCurrency(TotalInterventionForderung, true); } protected string GetTotalInterventionCharges() { return HTBUtils.FormatCurrency(TotalInterventionCharges, true); } protected string GetTotalInterventionPaid() { return HTBUtils.FormatCurrency(TotalInterventionPaid, true); } protected string GetTotalInterventionBalance() { return HTBUtils.FormatCurrency(TotalInterventionCharges - TotalInterventionPaid, true); } private void ClearScreen() { ClearGegnerGrid(); ClearGegnerAddressGrid(); ClearKlientGrid(); ClearInkassoGrid(); ClearInterventionGrid(); trHeaderGegner.Visible = false; trHeaderKlient.Visible = false; trHeaderAg.Visible = false; trHeaderInkasso.Visible = false; trHeaderIntervention.Visible = false; trHeaderGegnerAddress.Visible = false; trHeaderGegnerPhone.Visible = false; tabContainer1.Visible = false; } #region Gegner Grid private void ClearGegnerGrid() { PopulateGegnerGrid(new ArrayList()); } private void PopulateGegnerGrid(ArrayList list) { DataTable dt = GetDataTableStructure(); string currentName = ""; foreach (GegnerDetailLookup rec in list) { DataRow dr = dt.NewRow(); dr["ID"] = rec.GegnerID.ToString(); dr["OldID"] = rec.GegnerOldID; if(rec.GegnerName.ToLower() == currentName) { dr["Name"] = ""; } else { dr["Name"] = rec.GegnerName; currentName = rec.GegnerName.ToLower(); } dr["LKZ"] = rec.GegnerLastZipPrefix; dr["Ort"] = rec.GegnerLastOrt; dr["Strasse"] = rec.GegnerLastStrasse; dr["DOB"] = (rec.GegnerDOB == HTBUtils.DefaultDate || rec.GegnerDOB.ToShortDateString() == "01.01.0001") ? "" : rec.GegnerDOB.ToShortDateString(); dr["InterventionAkte"] = rec.InterventionAkte.ToString(); dr["InkassoAkte"] = rec.InkassoAkte.ToString(); dr["InkassoBalance"] = HTBUtils.FormatCurrency(rec.InkassoBalance); dt.Rows.Add(dr); } gvGegner.DataSource = dt; gvGegner.DataBind(); trHeaderGegner.Visible = gvGegner.Rows.Count > 0; } #endregion #region Gegner Address Grid private void ClearGegnerAddressGrid() { PopulateGegnerAddressGrid(new ArrayList()); } private void PopulateGegnerAddressGrid(ArrayList list) { DataTable dt = GetDataTableStructure(); string currentName = ""; string name = ""; foreach (tblGegnerAdressen rec in list) { DataRow dr = dt.NewRow(); name = rec.GAName2.Trim() + " " + rec.GAName1.Trim(); dr["ID"] = rec.GAID.ToString(); if (name == currentName) { dr["Name"] = ""; } else { dr["Name"] = name; currentName = name; } dr["LKZ"] = rec.GAZipPrefix; dr["Ort"] = rec.GAOrt; dr["Strasse"] = rec.GAStrasse; dr["Date"] = rec.GATimeStamp.ToShortDateString(); dt.Rows.Add(dr); } gvGegnerAddress.DataSource = dt; gvGegnerAddress.DataBind(); trHeaderGegnerAddress.Visible = gvGegnerAddress.Rows.Count > 0; } #endregion #region Gegner Phone Grid private void ClearGegnerPhoneGrid() { PopulateGegnerPhoneGrid(new ArrayList()); } private void PopulateGegnerPhoneGrid(ArrayList list) { DataTable dt = GetPhoneDataTableStructure(); if (currentGegner != null && !string.IsNullOrEmpty(currentGegner.GegnerPhone)) { DataRow dr = dt.NewRow(); dr["PhoneType"] = ""; dr["PhoneCity"] = currentGegner.GegnerPhoneCountry + " " + currentGegner.GegnerPhoneCity; dr["Phone"] = currentGegner.GegnerPhone; dr["PhoneDate"] = "Aktuell"; dr["PhoneDescription"] = ""; dt.Rows.Add(dr); } foreach (qryGegnerPhone rec in list) { DataRow dr = dt.NewRow(); dr["PhoneType"] = rec.PhoneTypeCaption; dr["PhoneCity"] = rec.GPhoneCountry + " " + rec.GPhoneCity; dr["Phone"] = rec.GPhone; dr["PhoneDate"] = rec.GPhoneDate.ToShortDateString(); dr["PhoneDescription"] = rec.GPhoneDescription; dt.Rows.Add(dr); } gvGegnerPhone.DataSource = dt; gvGegnerPhone.DataBind(); trHeaderGegnerPhone.Visible = gvGegnerPhone.Rows.Count > 0; } #endregion #region Klient Grid private void ClearKlientGrid() { PopulateKlientGrid(new ArrayList()); } private void PopulateKlientGrid(ArrayList list) { DataTable dt = GetDataTableStructure(); string currentName = ""; foreach (KlientDetailLookup rec in list) { DataRow dr = dt.NewRow(); dr["ID"] = rec.KlientID.ToString(); dr["OldID"] = rec.KlientOldID; if (rec.KlientName.ToLower() == currentName) { dr["Name"] = ""; } else { dr["Name"] = rec.KlientName; currentName = rec.KlientName.ToLower(); } dr["LKZ"] = rec.KlientLKZ; dr["Ort"] = rec.KlientOrt; dr["Strasse"] = rec.KlientStrasse; dr["InterventionAkte"] = rec.InterventionAkte.ToString(); dr["InkassoAkte"] = rec.InkassoAkte.ToString(); dr["InkassoBalance"] = HTBUtils.FormatCurrency(rec.InkassoBalance, true); dt.Rows.Add(dr); } gvKlient.DataSource = dt; gvKlient.DataBind(); trHeaderKlient.Visible = gvKlient.Rows.Count > 0; } #endregion #region Auftraggeber Grid private void ClearAgGrid() { PopulateAgGrid(new ArrayList()); } private void PopulateAgGrid(ArrayList list) { DataTable dt = GetDataTableStructure(); string currentName = ""; foreach (AuftraggeberDetailLookup rec in list) { DataRow dr = dt.NewRow(); dr["ID"] = rec.AgId.ToString(); if (rec.AgName.ToLower() == currentName) { dr["Name"] = ""; } else { dr["Name"] = rec.AgName; currentName = rec.AgName.ToLower(); } dr["LKZ"] = rec.AgLKZ; dr["Ort"] = rec.AgOrt; dr["Strasse"] = rec.AgStrasse; dr["InterventionAkte"] = rec.InterventionAkte.ToString(); dr["InkassoAkte"] = rec.InkassoAkte.ToString(); dr["InkassoBalance"] = HTBUtils.FormatCurrency(rec.InkassoBalance, true); dt.Rows.Add(dr); } gvAg.DataSource = dt; gvAg.DataBind(); trHeaderAg.Visible = gvAg.Rows.Count > 0; } #endregion #region CollectionInvoice Grid private void ClearInkassoGrid() { PopulateInkassoGrid(new ArrayList()); } private void PopulateInkassoGrid(ArrayList list, bool isGegner = false, bool isClient = false) { TotalInkassoForderung = 0; TotalInkassoCharges = 0; TotalInkassoPaid = 0; DataTable dt = GetAktDataTableStructure(); foreach (SearchAktLookup rec in list) { DataRow dr = dt.NewRow(); dr["ID"] = rec.AktId.ToString(); dr["AZ"] = rec.AktAZ; dr["AktEnteredDate"] = (rec.AktEnteredDate == HTBUtils.DefaultDate || rec.AktEnteredDate.ToShortDateString() == "01.01.0001") ? "" : rec.AktEnteredDate.ToShortDateString(); dr["KlientName"] = rec.KlientName; dr["GegnerInfo"] = rec.GegnerName + "<br/><br/>" + rec.GegnerAddress + "<br/>" + rec.GegnerCountry + " - " + rec.GegnerZip + " " + rec.GegnerCity; dr["AktStatus"] = rec.AktStatusCaption + "<BR/>" + rec.AktCurStatusCaption; dr["Forderung"] = HTBUtils.FormatCurrency(rec.Forderung, true); dr["TotalCharges"] = HTBUtils.FormatCurrency(rec.TotalCharges, true); dr["TotalPaid"] = HTBUtils.FormatCurrency(rec.TotalPaid, true); dr["Balance"] = HTBUtils.FormatCurrency(rec.TotalCharges - rec.TotalPaid, true); TotalInkassoForderung += rec.Forderung; TotalInkassoCharges += rec.TotalCharges; TotalInkassoPaid += rec.TotalPaid; dt.Rows.Add(dr); } if (isGegner) gvInkasso.Columns[4].Visible = false; if(isClient) gvInkasso.Columns[3].Visible = false; gvInkasso.DataSource = dt; gvInkasso.DataBind(); trHeaderInkasso.Visible = gvInkasso.Rows.Count > 0; } #endregion #region Intervention Grid private void ClearInterventionGrid() { PopulateInterventionGrid(new ArrayList()); } private void PopulateInterventionGrid(ArrayList list, bool isGegner = false, bool isClient = false, bool isAg = false) { TotalInterventionForderung = 0; TotalInterventionCharges = 0; TotalInterventionPaid = 0; DataTable dt = GetAktDataTableStructure(); foreach (SearchAktLookup rec in list) { DataRow dr = dt.NewRow(); dr["ID"] = rec.AktId.ToString(); dr["AZ"] = rec.AktAZ; dr["AktEnteredDate"] = (rec.AktEnteredDate == HTBUtils.DefaultDate || rec.AktEnteredDate.ToShortDateString() == "01.01.0001") ? "" : rec.AktEnteredDate.ToShortDateString(); dr["KlientName"] = rec.KlientName; if(!isGegner) dr["GegnerInfo"] = rec.GegnerName + "<br/><br/>" + rec.GegnerAddress + "<br/>" + rec.GegnerCountry + " - " + rec.GegnerZip + " " + rec.GegnerCity; dr["AktStatus"] = rec.AktStatusCaption; dr["AktCurStatus"] = rec.AktCurStatusCaption; dr["Forderung"] = HTBUtils.FormatCurrency(rec.Forderung, true); dr["TotalCharges"] = HTBUtils.FormatCurrency(rec.TotalCharges, true); dr["TotalPaid"] = HTBUtils.FormatCurrency(rec.TotalPaid, true); dr["Balance"] = HTBUtils.FormatCurrency(rec.TotalCharges - rec.TotalPaid, true); TotalInterventionForderung += rec.Forderung; TotalInterventionCharges += rec.TotalCharges; TotalInterventionPaid += rec.TotalPaid; dt.Rows.Add(dr); } if (isGegner) gvIntervention.Columns[4].Visible = false; if(isClient) gvIntervention.Columns[3].Visible = false; gvIntervention.DataSource = dt; gvIntervention.DataBind(); trHeaderIntervention.Visible = gvIntervention.Rows.Count > 0; } #endregion private void ShowFoundCounter(Label label, string counter) { int count = 0; try { count = Convert.ToInt32(counter); } catch { } if (count > 15) label.Text = "[15 von " + count + ".] Bitte definieren Sie ihre Suche genauer."; else label.Text = "[" + count + " von " + count + "]"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class pages_sizeManage : System.Web.UI.Page { //private DataLayer sqlOperation = new DataLayer("sqljiuye");//数据库操作类 protected void Page_Load(object sender, EventArgs e) { //string id = Request.QueryString["ID"]; // string sqlCommand = "SELECT enterprise,totalassets,area,productoutput,employeesnumber,year from size"; //sqlOperation.AddParameterWithValue("@id", id); //MySql.Data.MySqlClient.MySqlDataReader reader = sqlOperation.ExecuteReader(sqlCommand); //if (reader.Read()) //{ // this.year.Value = reader["year"].ToString(); // this.enterpriseName.Value = reader["enterprise"].ToString(); // this.totalAssets.Value = reader["totalassets"].ToString(); // this.area.Value = reader["area"].ToString(); // this.productNumber.Value = reader["productoutput"].ToString(); // this.employeesNumber.Value = reader["employeesnumber"].ToString(); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; namespace LoadLibrary { public class JSONDataLoader : ILoader { private string _fileName; public JSONDataLoader(string fileName) { _fileName = fileName; } public Queue<Candle> GetCandles() { Queue<Candle> candles = new Queue<Candle>(); var text = File.ReadAllText(_fileName); dynamic jsonDe = JsonConvert.DeserializeObject(text); List<decimal> open = jsonDe.o.ToObject<List<decimal>>(); List<decimal> high = jsonDe.h.ToObject<List<decimal>>(); List<decimal> low = jsonDe.l.ToObject<List<decimal>>(); List<decimal> close = jsonDe.c.ToObject<List<decimal>>(); List<long> timestamp = jsonDe.t.ToObject<List<long>>(); for (int i = 0; i < open.Count; i++) { Candle candle = new Candle() { High = high[i], Low = low[i], Open = open[i], Close = close[i], Time = DateTimeOffset.FromUnixTimeSeconds(timestamp[i]).UtcDateTime, TimeStamp = timestamp[i], }; candles.Enqueue(candle); } return candles; } } }
using System; using System.Collections.Generic; using System.Web.Http; using System.IO; using Giusti.Chat.Web.Library; using System.Net.Http; using System.Net; using Giusti.Chat.Model; using Giusti.Chat.Model.Dominio; using System.Web; using Giusti.Chat.Business; namespace Giusti.Chat.Web.Controllers.Api { /// <summary> /// Area /// </summary> public class AreaController : ApiBase { AreaBusiness biz = new AreaBusiness(); /// <summary> /// Retorna todas as áreas /// </summary> /// <returns></returns> public List<Area> Get() { List<Area> ResultadoBusca = new List<Area>(); try { VerificaAutenticacao(Constantes.FuncionalidadeAreaConsulta, Constantes.FuncionalidadeNomeAreaConsulta, biz); //API ResultadoBusca = new List<Area>(biz.RetornaAreas(RetornaEmpresaIdAutenticado())); if (!biz.IsValid()) throw new InvalidDataException(); } catch (InvalidDataException) { GeraErro(HttpStatusCode.InternalServerError, biz.serviceResult); } catch (UnauthorizedAccessException) { GeraErro(HttpStatusCode.Unauthorized, biz.serviceResult); } catch (Exception ex) { GeraErro(HttpStatusCode.BadRequest, ex); } return ResultadoBusca; } /// <summary> /// Retorna a área com id solicidado /// </summary> /// <param name="id"></param> /// <returns></returns> public Area Get(int id) { Area ResultadoBusca = new Area(); try { VerificaAutenticacao(Constantes.FuncionalidadeAreaConsulta, Constantes.FuncionalidadeNomeAreaConsulta, biz); //API ResultadoBusca = biz.RetornaArea_Id(id, RetornaEmpresaIdAutenticado()); if (!biz.IsValid()) throw new InvalidDataException(); } catch (InvalidDataException) { GeraErro(HttpStatusCode.InternalServerError, biz.serviceResult); } catch (UnauthorizedAccessException) { GeraErro(HttpStatusCode.Unauthorized, biz.serviceResult); } catch (Exception ex) { GeraErro(HttpStatusCode.BadRequest, ex); } return ResultadoBusca; } /// <summary> /// Inclui uma área /// </summary> /// <param name="itemSalvar"></param> /// <returns></returns> public int? Post([FromBody]Area itemSalvar) { try { VerificaAutenticacao(Constantes.FuncionalidadeAreaInclusao, Constantes.FuncionalidadeNomeAreaInclusao, biz); //API biz.SalvaArea(itemSalvar, RetornaEmpresaIdAutenticado()); if (!biz.IsValid()) throw new InvalidDataException(); GravaLog(Constantes.FuncionalidadeNomeAreaInclusao, RetornaEmailAutenticado(), itemSalvar.Id); } catch (InvalidDataException) { GeraErro(HttpStatusCode.InternalServerError, biz.serviceResult); } catch (UnauthorizedAccessException) { GeraErro(HttpStatusCode.Unauthorized, biz.serviceResult); } catch (Exception ex) { GeraErro(HttpStatusCode.BadRequest, ex); } return itemSalvar.Id; } /// <summary> /// Altera uma determinada área /// </summary> /// <param name="id"></param> /// <param name="itemSalvar"></param> /// <returns></returns> public Area Put(int id, [FromBody]Area itemSalvar) { try { VerificaAutenticacao(Constantes.FuncionalidadeAreaEdicao, Constantes.FuncionalidadeNomeAreaEdicao, biz); //API itemSalvar.Id = id; biz.SalvaArea(itemSalvar, RetornaEmpresaIdAutenticado()); if (!biz.IsValid()) throw new InvalidDataException(); GravaLog(Constantes.FuncionalidadeNomeAreaEdicao, RetornaEmailAutenticado(), itemSalvar.Id); } catch (InvalidDataException) { GeraErro(HttpStatusCode.InternalServerError, biz.serviceResult); } catch (UnauthorizedAccessException) { GeraErro(HttpStatusCode.Unauthorized, biz.serviceResult); } catch (Exception ex) { GeraErro(HttpStatusCode.BadRequest, ex); } return itemSalvar; } /// <summary> /// Exclui uma determinada área /// </summary> /// <param name="id"></param> /// <returns></returns> public HttpResponseMessage Delete(int id) { HttpResponseMessage retorno = null; try { VerificaAutenticacao(Constantes.FuncionalidadeAreaExclusao, Constantes.FuncionalidadeNomeAreaExclusao, biz); //API Area itemExcluir = biz.RetornaArea_Id(id, RetornaEmpresaIdAutenticado()); biz.ExcluiArea(itemExcluir, RetornaEmpresaIdAutenticado()); if (!biz.IsValid()) throw new InvalidDataException(); retorno = RetornaMensagemOk(biz.serviceResult); GravaLog(Constantes.FuncionalidadeNomeAreaExclusao, RetornaEmailAutenticado(), itemExcluir.Id); } catch (InvalidDataException) { retorno = RetornaMensagemErro(HttpStatusCode.InternalServerError, biz.serviceResult); } catch (UnauthorizedAccessException) { retorno = RetornaMensagemErro(HttpStatusCode.Unauthorized, biz.serviceResult); } catch (Exception ex) { retorno = RetornaMensagemErro(HttpStatusCode.BadRequest, ex); } return retorno; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //This is a mess...just let me get it working 100% will clean up. Sorry!! public class SlidingTilePuzzle : MonoBehaviour { public GameObject horizontalButton; public GameObject verticalButton; public GameObject[] tiles; public GameObject[] moveablePieces; public GameObject tester; //change a lot of this to enums later. (still new to those) //any of the [] relevant to the moveable pieces are ordered [leftPiece,midPiece,rightPiece].... so bad.. sorry public int[] myTileNumber;// which tile the piece should move to or is currently on public int[] myStartTile; private int hDirection;//0 left 1 right private int vDirection;//0 up 1 down private int delayLock; public bool[] pieceLocked;//if all true "turn" is over public bool[] tileOccupied; public bool moveH, moveV; public bool puzzleComplete; public bool[] isTileDown; public Vector3[] desiredPos; public float speed; float step; int animState = 0; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if(puzzleComplete) { WinAnim(); } else {RunPuzzle();} } void RunPuzzle() { step = speed * Time.deltaTime; if (!moveH && !moveV) { horizontalButton.GetComponent<PushButton>().isActive = false; verticalButton.GetComponent<PushButton>().isActive = false; checkButtons(); } if (moveV) { if (vDirection == 0) { MoveUp(); } if (vDirection == 1) { MoveDown(); } } if (moveH) { if (hDirection == 0) { MoveLeft(); } if (hDirection == 1) { MoveRight(); } } } void checkWin() { if(myTileNumber[0] < myTileNumber[1] && myTileNumber[1] < myTileNumber[2]) { puzzleComplete = true; } } void WinAnim() { for (int i = 0; i < 3; i++) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[i + 3].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[i + 3].transform.position, step / 3); } else { } } } void checkButtons() { if (verticalButton.GetComponent<PushButton>().isPressed) { if (vDirection == 1) { vDirection = 0; } else { vDirection = 1; } moveV = true; moveH = false; } if (horizontalButton.GetComponent<PushButton>().isPressed) { if (hDirection == 1) { hDirection = 0; } else { hDirection = 1; } moveH = true; moveV = false; } } void MoveRight() { delayLock++; for(int i = 0; i < 3; i++) { if(pieceLocked[0] && pieceLocked[1] && pieceLocked[2] && delayLock > 100) { delayLock = 0; horizontalButton.GetComponent<PushButton>().isPressed = false; horizontalButton.GetComponent<PushButton>().isActive = false; moveH = false; } if(myTileNumber[i] < 9) { if (!tileOccupied[myTileNumber[i] + 1] && myTileNumber[i] < 8) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[myTileNumber[i] + 1].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[myTileNumber[i] + 1].transform.position, step); } else { pieceLocked[i] = true; tileOccupied[myTileNumber[i]] = false; tileOccupied[myTileNumber[i] + 1] = true; myTileNumber[i]++; } } else { if (delayLock > 98) { // Debug.Log("TilesFinished"); if(myTileNumber[0] < 9 && myTileNumber[1] < 9 && myTileNumber[2] < 9) { checkWin(); } } } } } } void MoveLeft() { delayLock++; for (int i = 0; i < 3; i++) { if (pieceLocked[0] && pieceLocked[1] && pieceLocked[2] && delayLock > 100) { delayLock = 0; horizontalButton.GetComponent<PushButton>().isPressed = false; horizontalButton.GetComponent<PushButton>().isActive = false; moveH = false; } if (myTileNumber[i] < 9) { if (myTileNumber[i] > 0 && !tileOccupied[myTileNumber[i] - 1] && myTileNumber[i] > 0) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[myTileNumber[i] - 1].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[myTileNumber[i] - 1].transform.position, step); } else { pieceLocked[i] = true; tileOccupied[myTileNumber[i]] = false; tileOccupied[myTileNumber[i] - 1] = true; myTileNumber[i]--; } } else { if (delayLock > 98) { //Debug.Log("TilesFinished"); if (myTileNumber[0] < 9 && myTileNumber[1] < 9 && myTileNumber[2] < 9) { checkWin(); } } } } } } void MoveUp() { for(int i = 0; i < 3; i++) { if(myTileNumber[i] == 9) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[2].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[2].transform.position, step); } else { pieceLocked[i] = true; tileOccupied[9] = false; tileOccupied[2] = true; myTileNumber[i] = 2; delayLock = 0; verticalButton.GetComponent<PushButton>().isPressed = false; verticalButton.GetComponent<PushButton>().isActive = false; moveV = false; } } if (myTileNumber[i] == 10) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[6].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[6].transform.position, step); } else { pieceLocked[i] = true; tileOccupied[10] = false; tileOccupied[6] = true; myTileNumber[i] = 6; delayLock = 0; verticalButton.GetComponent<PushButton>().isPressed = false; verticalButton.GetComponent<PushButton>().isActive = false; moveV = false; } } } } void MoveDown() { for (int i = 0; i < 3; i++) { if (myTileNumber[i] == 2) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[9].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[9].transform.position, step); } else { pieceLocked[i] = true; tileOccupied[2] = false; tileOccupied[9] = true; myTileNumber[i] = 9; delayLock = 0; verticalButton.GetComponent<PushButton>().isPressed = false; verticalButton.GetComponent<PushButton>().isActive = false; moveV = false; } } if (myTileNumber[i] == 6) { if (Vector3.Distance(moveablePieces[i].transform.position, tiles[10].transform.position) > 0.001f) { moveablePieces[i].transform.position = Vector3.MoveTowards(moveablePieces[i].transform.position, tiles[10].transform.position, step); } else { pieceLocked[i] = true; tileOccupied[6] = false; tileOccupied[10] = true; myTileNumber[i] = 10; delayLock = 0; verticalButton.GetComponent<PushButton>().isPressed = false; verticalButton.GetComponent<PushButton>().isActive = false; moveV = false; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace lab_014 { class Program { static void Main(string[] args) { string @string; for (; ; ) { @string = Microsoft.VisualBasic.Interaction.InputBox("Введите первое число:", "Складываю два числа"); if (Microsoft.VisualBasic.Information.IsNumeric(@string) == true) break; } float X = float.Parse(@string); for (; ; ) { @string = Microsoft.VisualBasic.Interaction.InputBox("Введите второе число:", "Складываю два числа"); if (Microsoft.VisualBasic.Information.IsNumeric(@string) == true) break; } float Y = float.Parse(@string); float Z = X + Y; @string = string.Format("Сумма: {0} + {1} = {2}", X, Y, Z); Microsoft.VisualBasic.Interaction.MsgBox(@string); } } }
using System; using System.ComponentModel.DataAnnotations; using com.Sconit.Entity.ACC; namespace com.Sconit.Entity.ISS { [Serializable] public partial class IssueMaster : EntityBase, IAuditable { #region O/R Mapping Properties [Display(Name = "Code", ResourceType = typeof(Resources.ISS.IssueMaster))] public string Code { get; set; } // [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "IssueAddress", ResourceType = typeof(Resources.ISS.IssueMaster))] public string IssueAddress { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "IssueType", ResourceType = typeof(Resources.ISS.IssueMaster))] public IssueType IssueType { get; set; } //[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "IssueNo", ResourceType = typeof(Resources.ISS.IssueMaster))] public IssueNo IssueNo { get; set; } [Display(Name = "IssueSubject", ResourceType = typeof(Resources.ISS.IssueMaster))] public string IssueSubject { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "BackYards", ResourceType = typeof(Resources.ISS.IssueMaster))] public string BackYards { get; set; } //[DataType(DataType.MultilineText)] [StringLength(100)] [Display(Name = "Content", ResourceType = typeof(Resources.ISS.IssueMaster))] public string Content { get; set; } [StringLength(100)] [Display(Name = "Solution", ResourceType = typeof(Resources.ISS.IssueMaster))] public string Solution { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "Status", ResourceType = typeof(Resources.ISS.IssueMaster))] public com.Sconit.CodeMaster.IssueStatus Status { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "Priority", ResourceType = typeof(Resources.ISS.IssueMaster))] public com.Sconit.CodeMaster.IssuePriority Priority { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "Type", ResourceType = typeof(Resources.ISS.IssueMaster))] public com.Sconit.CodeMaster.IssueType Type { get; set; } [Display(Name = "UserName", ResourceType = typeof(Resources.ISS.IssueMaster))] public string UserName { get; set; } [DataType(DataType.EmailAddress)] [Display(Name = "Email", ResourceType = typeof(Resources.ISS.IssueMaster))] public string Email { get; set; } [DataType(DataType.PhoneNumber)] [Display(Name = "MobilePhone", ResourceType = typeof(Resources.ISS.IssueMaster))] public string MobilePhone { get; set; } [Display(Name = "FinishedDate", ResourceType = typeof(Resources.ISS.IssueMaster))] public DateTime? FinishedDate { get; set; } [Display(Name = "FinishedUser", ResourceType = typeof(Resources.ISS.IssueMaster))] public User FinishedUser { get; set; } public Int32 CreateUserId { get; set; } [Display(Name = "Common_CreateUserName", ResourceType = typeof(Resources.SYS.Global))] public string CreateUserName { get; set; } [Display(Name = "Common_CreateDate", ResourceType = typeof(Resources.SYS.Global))] public DateTime CreateDate { get; set; } public Int32 LastModifyUserId { get; set; } [Display(Name = "Common_LastModifyUserName", ResourceType = typeof(Resources.SYS.Global))] public string LastModifyUserName { get; set; } [Display(Name = "Common_LastModifyDate", ResourceType = typeof(Resources.SYS.Global))] public DateTime LastModifyDate { get; set; } [Display(Name = "ReleaseDate", ResourceType = typeof(Resources.ISS.IssueMaster))] public DateTime? ReleaseDate { get; set; } //[Display(Name = "ReleaseUser", ResourceType = typeof(Resources.ISS.IssueMaster))] public Int32? ReleaseUser { get; set; } [Display(Name = "ReleaseUserName", ResourceType = typeof(Resources.ISS.IssueMaster))] public string ReleaseUserName { get; set; } [Display(Name = "StartDate", ResourceType = typeof(Resources.ISS.IssueMaster))] public DateTime? StartDate { get; set; } //[Display(Name = "StartUser", ResourceType = typeof(Resources.ISS.IssueMaster))] public Int32? StartUser { get; set; } [Display(Name = "StartUserName", ResourceType = typeof(Resources.ISS.IssueMaster))] public string StartUserName { get; set; } [Display(Name = "CloseDate", ResourceType = typeof(Resources.ISS.IssueMaster))] public DateTime? CloseDate { get; set; } //[Display(Name = "CloseUser", ResourceType = typeof(Resources.ISS.IssueMaster))] public Int32? CloseUser { get; set; } [Display(Name = "CloseUserName", ResourceType = typeof(Resources.ISS.IssueMaster))] public string CloseUserName { get; set; } [Display(Name = "CancelDate", ResourceType = typeof(Resources.ISS.IssueMaster))] public DateTime? CancelDate { get; set; } //[Display(Name = "CancelUser", ResourceType = typeof(Resources.ISS.IssueMaster))] public Int32? CancelUser { get; set; } [Display(Name = "CancelUserName", ResourceType = typeof(Resources.ISS.IssueMaster))] public string CancelUserName { get; set; } [Display(Name = "CompleteDate", ResourceType = typeof(Resources.ISS.IssueMaster))] public DateTime? CompleteDate { get; set; } //[Display(Name = "CompleteUser", ResourceType = typeof(Resources.ISS.IssueMaster))] public Int32? CompleteUser { get; set; } [Display(Name = "CompleteUserName", ResourceType = typeof(Resources.ISS.IssueMaster))] public string CompleteUserName { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "FailCode", ResourceType = typeof(Resources.ISS.IssueMaster))] public string FailCode { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "DefectCode", ResourceType = typeof(Resources.ISS.IssueMaster))] public string DefectCode { get; set; } #endregion public override int GetHashCode() { if (Code != null) { return Code.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { IssueMaster another = obj as IssueMaster; if (another == null) { return false; } else { return (this.Code == another.Code); } } } }
using System.ComponentModel.DataAnnotations.Schema; namespace GradConnect.Models { public class Sponsored : Post { [InverseProperty("Employer")] public int EmployerId { get; set; } public virtual Employer Employer { get; set; } } }
// <copyright file="MemberController.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> namespace SmartLibrary.Admin.Controllers { using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Mvc; using DataTables.Mvc; using EmailServices; using Infrastructure; using Infrastructure.Code; using Infrastructure.Filters; using Models; using OfficeOpenXml; using Resources; using Services; using SmartLibrary.Admin.Pages; using SmartLibrary.Models; using static Infrastructure.SystemEnumList; /// <summary> /// Used to Member Controller. /// </summary> /// <CreatedBy>Bhoomi Shah.</CreatedBy> /// <CreatedDate>10-sep-2018.</CreatedDate> /// <ModifiedBy></ModifiedBy> /// <ModifiedDate></ModifiedDate> /// <ReviewBy></ReviewBy> /// <ReviewDate></ReviewDate> public class MemberController : BaseController { private MemberDataBL memberDataBL; private CommonBL commonDataBL; private MasterDataBL masterDataBL; #region Constructor /// <summary> /// Initializes a new instance of the <see cref="MemberController"/> class. /// MemberController /// </summary> public MemberController() { if (this.memberDataBL == null) { this.memberDataBL = new MemberDataBL(); } if (this.commonDataBL == null) { this.commonDataBL = new CommonBL(); } if (this.masterDataBL == null) { this.masterDataBL = new MasterDataBL(); } } #endregion Constructor #region Customers /// <summary> /// CustomerList this instance. /// </summary> /// <returns>List of CustomerList</returns> [ActionName(Actions.CustomerList)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public ActionResult CustomerList() { this.ViewData["CurrentPageAccessRight"] = this.PageAccessRight; return this.View(Views.CustomerList); } /// <summary> /// list of customer with search criteria /// </summary> /// <param name="requestModel">the requestModel</param> /// <param name="searchdata">search</param> /// <returns>List of Customer</returns> [HttpPost] [ActionName(Actions.CustomerList)] [NoAntiForgeryCheck] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public JsonResult CustomerList([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel, string searchdata = "") { List<Customer> customerList = new List<Customer>(); Customer model = new Customer() { FirstName = searchdata, LastName = searchdata, Email = searchdata, StartRowIndex = requestModel.Start + 1, EndRowIndex = requestModel.Start + requestModel.Length, SortDirection = requestModel.OrderDir, SortExpression = requestModel.Columns.ElementAt(requestModel.OrderColumn).Data }; customerList = this.memberDataBL.GetCustomerList(model); int totalRecord = 0; int filteredRecord = 0; if (customerList != null && customerList.Count > 0) { totalRecord = customerList.FirstOrDefault().TotalRecords; filteredRecord = customerList.FirstOrDefault().TotalRecords; foreach (var customer in customerList) { customer.IdEncrypted = EncryptionDecryption.EncryptByTripleDES(customer.Id.ToString()); } } return this.Json(new DataTablesResponse(requestModel.Draw, customerList, filteredRecord, totalRecord), JsonRequestBehavior.AllowGet); } #endregion #region CustomerGrid /// <summary> /// View Customer /// </summary> /// <returns>Return View</returns> [HttpGet] [ActionName(Actions.CustomerGrid)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public ActionResult CustomerGrid() { this.ViewData["CurrentPageAccessRight"] = this.PageAccessRight; List<Customer> customerList = new List<Customer>(); Customer model = new Customer() { StartRowIndex = 1, EndRowIndex = ProjectConfiguration.PageSizeGrid, }; customerList = this.memberDataBL.GetCustomerList(model); foreach (var customer in customerList) { customer.IdEncrypted = EncryptionDecryption.EncryptByTripleDES(customer.Id.ToString()); } int totalRecord = customerList.FirstOrDefault()?.TotalRecords ?? 0; this.ViewBag.TotalPage = Math.Ceiling((float)totalRecord / 20); return this.View(Views.CustomerGrid, customerList); } /// <summary> /// list of Customer with search criteria /// </summary> /// <param name="baseModel">model</param> /// <returns>List of customers</returns> [HttpPost] [ActionName(Actions.CustomerGrid)] [NoAntiForgeryCheck] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public ActionResult CustomerGrid(BaseViewModel baseModel) { List<Customer> customerList; Customer model = new Customer() { FirstName = baseModel.Searchtext, LastName = baseModel.Searchtext, Email = baseModel.Searchtext, StartRowIndex = ((baseModel.CurrentPage - 1) * ProjectConfiguration.PageSizeGrid) + 1, EndRowIndex = baseModel.CurrentPage * ProjectConfiguration.PageSizeGrid, }; customerList = this.memberDataBL.GetCustomerList(model); int totalRecord = 0; if (customerList != null && customerList.Count > 0) { totalRecord = customerList.FirstOrDefault().TotalRecords; foreach (var customer in customerList) { customer.IdEncrypted = EncryptionDecryption.EncryptByTripleDES(customer.Id.ToString()); } } this.ViewBag.TotalPage = Math.Ceiling((float)totalRecord / ProjectConfiguration.PageSizeGrid); return this.PartialView(PartialViews.CustomerGrid, customerList); } #endregion #region Invite Customer /// <summary> /// Invite Customer /// </summary> /// <returns>Partial view</returns> [HttpGet] [ActionName(Actions.InviteCustomer)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public ActionResult InviteCustomer() { return this.PartialView(PartialViews.InviteCustomer); } /// <summary> /// Invite Customer /// </summary> /// <param name="email">email</param> /// <returns>Json result</returns> [HttpPost] [ActionName(Actions.InviteCustomer)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public JsonResult InviteCustomer(string email) { Customer objCustomer = this.memberDataBL.GetCustomerList(new Customer()).Where(x => x.Email == email).FirstOrDefault(); var encryptLoginType = EncryptionDecryption.EncryptByTripleDES(LoginType.Guest.GetHashCode().ToString()); if (objCustomer == null) { string signUpParameter = string.Format("{0}", email); string encryptsignUpParameter = EncryptionDecryption.EncryptByTripleDES(signUpParameter); string signUpURL = string.Format("{0}?q={1}&loginType={2}", ProjectConfiguration.FrontEndSiteUrl + Controllers.ActiveDirectory + "/" + Actions.SignUp, encryptsignUpParameter, encryptLoginType); EmailViewModel emailModel = new EmailViewModel() { Email = email, ResetUrl = signUpURL, LanguageId = ConvertTo.ToInteger(ProjectSession.AdminPortalLanguageId) }; if (UserMail.SendInviteMail(emailModel)) { return this.Json(new { status = Infrastructure.SystemEnumList.MessageBoxType.Success.GetDescription(), message = Messages.EmailSent, title = Infrastructure.SystemEnumList.Title.Member.GetDescription(), JsonRequestBehavior.AllowGet }); } else { return this.Json(new { status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = Messages.ErrorMessage, title = Infrastructure.SystemEnumList.Title.Member.GetDescription(), JsonRequestBehavior.AllowGet }); } } else { return this.Json(new { status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = Messages.MemberAlreadyRegistered, title = Infrastructure.SystemEnumList.Title.Member.GetDescription(), JsonRequestBehavior.AllowGet }); } } #endregion #region Download /// <summary> /// Export to excel /// </summary> /// <param name="searchdata">search</param> /// <returns>List of Customer export to excel</returns> [HttpGet] [ActionName(Actions.CustomersExportToExcel)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public ActionResult CustomersExportToExcel(string searchdata = "") { DataTable customers = new DataTable(); Customer model = new Customer() { FirstName = searchdata, LastName = searchdata, Email = searchdata }; var customerList = this.memberDataBL.GetCustomerList(model).Select(x => new { x.FirstName, x.LastName, x.Email, x.Gender, x.Phone }).ToList(); customers = ConvertTo.ToDataTable(customerList.ToList()); customers.Columns.Add("strGender", typeof(string)); foreach (DataRow row in customers?.Rows) { bool active = row["Gender"].ToBoolean(); if (active) { row["strGender"] = "Female"; } else { row["strGender"] = "Male"; } } customers.Columns.Remove("Gender"); byte[] bytes; string filename; try { ////this.Response.Clear(); using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("Member"); workSheet.Cells["A1"].LoadFromDataTable(customers, true); workSheet.Cells["A1"].Value = "FirstName"; workSheet.Cells["B1"].Value = "LastName"; workSheet.Cells["C1"].Value = "Email"; workSheet.Cells["D1"].Value = "Phone"; workSheet.Cells["E1"].Value = "Gender"; filename = "Member_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".xlsx"; bytes = package.GetAsByteArray(); return this.File(bytes, "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename); } } catch (Exception ex) { return this.Json(new object[] { false, ex.Message.ToString() }, JsonRequestBehavior.AllowGet); } return this.File(bytes, "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", filename); } #endregion #region History /// <summary> /// CustomerList this instance. /// </summary> /// <param name="data">the encrypted Id</param> /// <returns>List of CustomerList</returns> [ActionName(Actions.HistoryOfMember)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] [HttpGet] public ActionResult HistoryOfMember(string data = "") { this.ViewData["CurrentPageAccessRight"] = this.PageAccessRight; string decryptedVal = EncryptionDecryption.DecryptByTripleDES(data); if (decryptedVal != string.Empty) { this.ViewData["ID"] = data; Customer model = new Customer() { Id = decryptedVal.ToInteger() }; var customer = this.memberDataBL.GetCustomerList(model).FirstOrDefault(); this.ViewBag.MemberName = customer.FirstName + " " + customer.LastName; return this.View(Views.HistoryOfMember); } else { return this.RedirectToAction(Actions.CustomerList, Controllers.Member); } } /// <summary> /// list of Book Genres with search criteria /// </summary> /// <param name="requestModel">the requestModel</param> /// <param name="searchdata">search</param> /// <param name="data">the encrypted id</param> /// <param name="historyType">type of history</param> /// <returns>List of BookGenres</returns> [HttpPost] [ActionName(Actions.HistoryOfMember)] [NoAntiForgeryCheck] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] public JsonResult HistoryOfMember([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel, string searchdata = "", string data = "", int historyType = 1) { int id = ConvertTo.ToInteger(EncryptionDecryption.DecryptByTripleDES(data)); int totalRecord = 0; int filteredRecord = 0; if (historyType == 1) { List<BorrowedBook> borrowedBookList ; borrowedBookList = this.commonDataBL.GetBookDetailsOfCustomer(id, searchdata, requestModel.Start + 1, requestModel.Start + requestModel.Length, requestModel.Columns.ElementAt(requestModel.OrderColumn).Data, requestModel.OrderDir); if (borrowedBookList != null && borrowedBookList.Count > 0) { totalRecord = borrowedBookList.FirstOrDefault().TotalRecords; filteredRecord = borrowedBookList.FirstOrDefault().TotalRecords; } return this.Json(new DataTablesResponse(requestModel.Draw, borrowedBookList, filteredRecord, totalRecord), JsonRequestBehavior.AllowGet); } else { List<SpaceBooking> spaceList; spaceList = this.commonDataBL.GetSpaceDetailsOfCustomer(id, searchdata, requestModel.Start + 1, requestModel.Start + requestModel.Length, requestModel.Columns.ElementAt(requestModel.OrderColumn).Data, requestModel.OrderDir); if (spaceList != null && spaceList.Count > 0) { totalRecord = spaceList.FirstOrDefault().TotalRecords; filteredRecord = spaceList.FirstOrDefault().TotalRecords; } return this.Json(new DataTablesResponse(requestModel.Draw, spaceList, filteredRecord, totalRecord), JsonRequestBehavior.AllowGet); } } /// <summary> /// Status change of space booking /// </summary> /// <param name="statusId">statusId.</param> /// <param name="spaceBookingId">spaceBookingId.</param> /// <param name="comment">comment</param> /// <returns>Approve/Reject BorrowedBook</returns> [HttpPost] [ActionName(Actions.ApproveCancelSpaceBooking)] [NoAntiForgeryCheck] [PageAccessAttribute(PermissionName = Constants.ACTION_ADDUPDATE, ActionName = Actions.Customer)] public JsonResult ApproveCancelSpaceBooking(int statusId, int spaceBookingId = 0, string comment = null) { string msg = string.Empty; try { if (statusId == SystemEnumList.SpaceBookingStatus.Approved.GetHashCode()) { msg = SystemEnumList.SpaceBookingStatus.Approved.GetDescription(); } else if (statusId == SystemEnumList.SpaceBookingStatus.Cancel.GetHashCode()) { msg = SystemEnumList.SpaceBookingStatus.Cancel.GetDescription(); } else if (statusId == SystemEnumList.SpaceBookingStatus.Pending.GetHashCode()) { msg = SystemEnumList.SpaceBookingStatus.Pending.GetDescription(); } SpaceBooking spacebooking = this.masterDataBL.SelectObject<SpaceBooking>(spaceBookingId); spacebooking.StatusId = statusId; string spaceName = spacebooking.SpaceName; spacebooking.SpaceName = null; if (statusId == SystemEnumList.SpaceBookingStatus.Cancel.GetHashCode()) { spacebooking.Comment = comment; } int id = this.masterDataBL.Save<SpaceBooking>(spacebooking, checkForDuplicate: false); if (id > 0) { if (statusId == SystemEnumList.SpaceBookingStatus.Approved.GetHashCode()) { EmailViewModel emailModel = new EmailViewModel() { Email = spacebooking.CustomerEmail, Name = spacebooking.CustomerName, People = spacebooking.NoOfPeople.ToString(), RoomName = spaceName, Date = spacebooking.FromDate.ToDate().ToString(ProjectConfiguration.DateFormat, System.Globalization.CultureInfo.InvariantCulture), Fromtime = spacebooking.FromDate.ToDate().ToString("hh:mm tt", System.Globalization.CultureInfo.InvariantCulture), Totime = spacebooking.ToDate.ToDate().ToString("hh:mm tt", System.Globalization.CultureInfo.InvariantCulture), LanguageId = ConvertTo.ToInteger(ProjectSession.AdminPortalLanguageId) }; UserMail.RoomBookingApprove(emailModel); NotificationFactory.AddNotification(NotificationType.SpaceBookingApprove, spacebooking); } else if (statusId == SystemEnumList.SpaceBookingStatus.Cancel.GetHashCode()) { EmailViewModel emailModel = new EmailViewModel() { Email = spacebooking.CustomerEmail, Name = spacebooking.CustomerName, People = spacebooking.NoOfPeople.ToString(), RoomName = spaceName, Date = spacebooking.FromDate.ToDate().ToString(ProjectConfiguration.DateFormat, System.Globalization.CultureInfo.InvariantCulture), Fromtime = spacebooking.FromDate.ToDate().ToString("hh:mm tt", System.Globalization.CultureInfo.InvariantCulture), Totime = spacebooking.ToDate.ToDate().ToString("hh:mm tt", System.Globalization.CultureInfo.InvariantCulture), LanguageId = ConvertTo.ToInteger(ProjectSession.AdminPortalLanguageId) }; UserMail.RoomBookingCancel(emailModel); NotificationFactory.AddNotification(NotificationType.SpaceBookingReject, spacebooking); } else if (statusId == SystemEnumList.SpaceBookingStatus.Pending.GetHashCode()) { NotificationFactory.AddNotification(NotificationType.SpaceBookingPending, spacebooking); } return this.Json(new { success = true, status = Infrastructure.SystemEnumList.MessageBoxType.Success.GetDescription(), message = Messages.ApproveSpaceBookingStatus.SetArguments(msg), title = Infrastructure.SystemEnumList.Title.Space.GetDescription(), JsonRequestBehavior.AllowGet }); } else { msg = Messages.ErrorMessage.SetArguments(General.BookSpace); if (id == -3) { var spaceCapacity = new MasterDataBL().GetSpaceList(new Space() { ID = spaceBookingId })?.FirstOrDefault()?.Capacity ?? 0; msg = Messages.NoOfAttendeeExceedCapacity.SetArguments(spaceCapacity, General.NoOfPeople); } else if (id == -4) { msg = Messages.BookingAreaUnavailable; } return this.Json(new { success = false, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = msg, title = Infrastructure.SystemEnumList.Title.Space.GetDescription(), JsonRequestBehavior.AllowGet }); } } catch (Exception ex) { return this.Json(new { success = false, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = Messages.ErrorMessage.SetArguments(msg), title = Infrastructure.SystemEnumList.Title.Space.GetDescription(), JsonRequestBehavior.AllowGet }); } } /// <summary> /// Book the Space. /// </summary> /// <param name="id">The identifier.</param> /// <returns>Book a Space modal</returns> [ActionName(Actions.RescheduleBookSpace)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Space)] public ActionResult RescheduleBookSpace(int id = 0) { SpaceBooking model = new SpaceBooking(); model.ID = id; if (id > 0) { model = this.masterDataBL.Search(model).FirstOrDefault(); } return this.PartialView(PartialViews.BookSpace, model); } /// <summary> /// Book the Space. /// </summary> /// <param name="id">The identifier.</param> /// <returns>Space Status modal</returns> [ActionName(Actions.ViewSpaceStatus)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Space)] public ActionResult ViewSpaceStatus(int id = 0) { SpaceBooking model = new SpaceBooking(); model.ID = id; if (id > 0) { model = this.masterDataBL.Search(model).FirstOrDefault(); } return this.PartialView(PartialViews.ViewSpaceStatus, model); } /// <summary> /// Manages the BookSpace booking. /// </summary> /// <param name="spaceBooking">The SpaceBooking.</param> /// <returns>Save BookSpace booking</returns> [ActionName(Actions.RescheduleBookSpace)] [HttpPost] [PageAccessAttribute(PermissionName = Constants.ACTION_ADDUPDATE, ActionName = Actions.Space)] public JsonResult RescheduleBookSpace(SpaceBooking spaceBooking) { int rescheduldid = spaceBooking.ID; spaceBooking.ID = 0; try { if (this.ModelState.IsValid) { string comment = spaceBooking.Comment; spaceBooking.Comment = string.Empty; spaceBooking.FromDate = DateTime.ParseExact(spaceBooking.BookingDate + " " + spaceBooking.FromTime, ProjectConfiguration.DateTimeFormat, System.Globalization.CultureInfo.InvariantCulture); spaceBooking.ToDate = DateTime.ParseExact(spaceBooking.BookingDate + " " + spaceBooking.ToTime, ProjectConfiguration.DateTimeFormat, System.Globalization.CultureInfo.InvariantCulture); if (spaceBooking.FromDate <= DateTime.Now) { return this.Json(new { resultData = 0, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = Messages.SpaceBookingTimeMessage }, JsonRequestBehavior.DenyGet); } if (spaceBooking.ToDate <= spaceBooking.FromDate) { return this.Json(new { resultData = 0, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = Messages.TimeCompareMessage.SetArguments(General.ToTime, General.FromTime) }, JsonRequestBehavior.DenyGet); } int status = this.masterDataBL.AddSpaceBooking(spaceBooking, SystemEnumList.SpaceBookingStatus.Approved.GetHashCode().ToInteger()); string message = string.Empty; if (status > 0) { message = Messages.SpaceBookingReschedule; SpaceBooking oldspacebooking = this.masterDataBL.SelectObject<SpaceBooking>(rescheduldid); string oldSpaceName = oldspacebooking.SpaceName; oldspacebooking.StatusId = ConvertTo.ToInteger(SystemEnumList.SpaceBookingStatus.Rescheduled.GetHashCode()); oldspacebooking.RescheduleId = status; oldspacebooking.Reschedule = true; oldspacebooking.SpaceName = null; oldspacebooking.Comment = comment; int id = this.masterDataBL.Save<SpaceBooking>(oldspacebooking, checkForDuplicate: false); if (id > 0) { spaceBooking.ID = status; NotificationFactory.AddNotification(NotificationType.SpaceBookingReschedule, spaceBooking); SpaceBooking newSpaceBooking = this.masterDataBL.SelectObject<SpaceBooking>(status); EmailViewModel emailModel = new EmailViewModel() { Email = newSpaceBooking.CustomerEmail, Name = newSpaceBooking.CustomerName, OldroomName = oldSpaceName, OldDate = oldspacebooking.FromDate.ToDate().ToString(ProjectConfiguration.DateFormat, System.Globalization.CultureInfo.InvariantCulture), OldFromtime = oldspacebooking.FromDate.ToDate().ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), OldTotime = oldspacebooking.ToDate.ToDate().ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), OldPeople = oldspacebooking.NoOfPeople.ToString(), RoomName = newSpaceBooking.SpaceName, People = spaceBooking.NoOfPeople.ToString(), Date = spaceBooking.BookingDate.ToDate().ToString(ProjectConfiguration.DateFormat, System.Globalization.CultureInfo.InvariantCulture), Fromtime = spaceBooking.FromDate.ToDate().ToString("hh:mm tt", System.Globalization.CultureInfo.InvariantCulture), Totime = spaceBooking.ToDate.ToDate().ToString("hh:mm tt", System.Globalization.CultureInfo.InvariantCulture), LanguageId = ConvertTo.ToInteger(ProjectSession.AdminPortalLanguageId) }; UserMail.RoomBookingReschedule(emailModel); return this.Json(new { resultData = status, status = Infrastructure.SystemEnumList.MessageBoxType.Success.GetDescription(), message = message, title = General.BookSpace }, JsonRequestBehavior.DenyGet); } else { return this.Json(new { success = false, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = Messages.ErrorMessage.SetArguments(General.BookSpace), title = Infrastructure.SystemEnumList.Title.Space.GetDescription(), JsonRequestBehavior.AllowGet }); } } else if (status == -3) { var spaceCapacity = new MasterDataBL().GetSpaceList(new Space() { ID = spaceBooking.SpaceId.Value })?.FirstOrDefault()?.Capacity ?? 0; message = Messages.NoOfAttendeeExceedCapacity.SetArguments(spaceCapacity, General.NoOfPeople); } else if (status == -4) { message = Messages.BookingAreaUnavailable; } else { message = Messages.DuplicateMessage.SetArguments(General.BookSpace); } return this.Json(new { resultData = status, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = message }, JsonRequestBehavior.DenyGet); } else { string errorMsg = string.Empty; foreach (ModelState modelState in this.ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { if (!string.IsNullOrEmpty(errorMsg)) { errorMsg = errorMsg + " , "; } errorMsg = errorMsg + error.ErrorMessage; } } return this.Json(new { resultData = string.Empty, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = errorMsg }, JsonRequestBehavior.DenyGet); } } catch (Exception ex) { return this.Json(new { resultData = string.Empty, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = ex.Message == null ? ex.InnerException.Message : ex.Message }, JsonRequestBehavior.DenyGet); } } #endregion #region ::Edit Customer:: /// <summary> /// Customer Edit . /// </summary> /// <param name="id">the Id</param> /// <returns>Partial view of edit customer.</returns> [ActionName(Actions.EditCustomer)] [PageAccessAttribute(PermissionName = Constants.ACTION_VIEW, ActionName = Actions.Customer)] [HttpGet] public ActionResult EditCustomer(int id = 0) { Customer model; if (id < 0) { return this.View(Views.CustomerGrid); } model = this.memberDataBL.SelectCustomer(id); return this.PartialView(PartialViews.EditCustomer, model); } /// <summary> /// Manages the User. /// </summary> /// <param name="user">The User.</param> /// <returns>Edit Customer</returns> [ActionName(Actions.EditCustomer)] [HttpPost] [PageAccessAttribute(PermissionName = Constants.ACTION_ADDUPDATE, ActionName = Actions.Customer)] public JsonResult EditCustomer(Customer user) { if (user.LoginType == SystemEnumList.LoginType.Guest.GetHashCode() && !string.IsNullOrEmpty(user.AGUserId)) { ActiveDirectoryRegister activeDirectoryUpdate = new ActiveDirectoryRegister() { Email = user.Email, Password = user.Password, FirstName = user.FirstName, LastName = user.LastName, FullName = user.FirstName + string.Empty + user.LastName, UserId = user.AGUserId, LanguageId = user.Language ?? SystemEnumList.Language.Arabic.GetHashCode() }; var updateResponse = this.commonDataBL.ActiveDirectoryUpdateResponse(activeDirectoryUpdate); if (updateResponse == null || updateResponse.Status != SystemEnumList.ApiStatus.Success.GetDescription()) { return this.Json(new { resultData = 0, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = updateResponse?.Message ?? Messages.ErrorMessage.SetArguments(General.Member), title = Infrastructure.SystemEnumList.Title.Member.GetDescription(), JsonRequestBehavior.DenyGet }); } } var userData = this.memberDataBL.SelectCustomer(user.Id); userData.FirstName = user.FirstName; userData.LastName = user.LastName; userData.Phone = user.Phone; userData.Gender = user.Gender; userData.Language = user.Language; int status = this.memberDataBL.SaveCustomer(userData, userData.Id); string message = string.Empty; if (status > 0) { message = Messages.UpdateMessage.SetArguments(General.Member); } else { if (status == -2) { message = Messages.DuplicateMessage.SetArguments(General.Member); } else { message = Messages.ErrorMessage.SetArguments(General.Member); } return this.Json(new { resultData = status, status = Infrastructure.SystemEnumList.MessageBoxType.Error.GetDescription(), message = message, title = Infrastructure.SystemEnumList.Title.Member.GetDescription(), JsonRequestBehavior.DenyGet }); } return this.Json(new { resultData = status, status = Infrastructure.SystemEnumList.MessageBoxType.Success.GetDescription(), message = message, title = Infrastructure.SystemEnumList.Title.Member.GetDescription(), JsonRequestBehavior.DenyGet }); } #endregion } }
using Microsoft.EntityFrameworkCore.Migrations; namespace CouponMerchant.Migrations { public partial class AddedMerchantIdFKtoUserTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "MerchantId", table: "AspNetUsers", nullable: true); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_MerchantId", table: "AspNetUsers", column: "MerchantId"); migrationBuilder.AddForeignKey( name: "FK_AspNetUsers_Merchant_MerchantId", table: "AspNetUsers", column: "MerchantId", principalTable: "Merchant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_AspNetUsers_Merchant_MerchantId", table: "AspNetUsers"); migrationBuilder.DropIndex( name: "IX_AspNetUsers_MerchantId", table: "AspNetUsers"); migrationBuilder.DropColumn( name: "MerchantId", table: "AspNetUsers"); } } }
using Alabo.Cloud.School.SmallTargets.Domain.Entities; using Alabo.Domains.Services; using MongoDB.Bson; namespace Alabo.Cloud.School.SmallTargets.Domain.Services { public interface ISmallTargetRankingService : IService<SmallTargetRanking, ObjectId> { } }
namespace Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class SiteDivisionSettings : DbMigration { public override void Up() { DropIndex("Web.JobReceiveSettings", new[] { "DocTypeId" }); DropIndex("Web.JobReceiveSettings", new[] { "SiteId" }); DropIndex("Web.JobReceiveSettings", new[] { "DivisionId" }); CreateTable( "Web.CompanySettings", c => new { CompanySettingsId = c.Int(nullable: false, identity: true), CompanyId = c.Int(nullable: false), isVisibleMessage = c.Boolean(), isVisibleTask = c.Boolean(), isVisibleNotification = c.Boolean(), SiteCaption = c.String(), DivisionCaption = c.String(), GodownCaption = c.String(), CreatedBy = c.String(), ModifiedBy = c.String(), CreatedDate = c.DateTime(nullable: false), ModifiedDate = c.DateTime(nullable: false), OMSId = c.String(maxLength: 50), }) .PrimaryKey(t => t.CompanySettingsId); CreateTable( "Web.SiteDivisionSettings", c => new { SiteDivisionSettingsId = c.Int(nullable: false, identity: true), SiteId = c.Int(nullable: false), DivisionId = c.Int(nullable: false), StartDate = c.DateTime(nullable: false), EndDate = c.DateTime(), IsApplicableVAT = c.Boolean(nullable: false), IsApplicableGST = c.Boolean(nullable: false), ReportHeaderTextLeft = c.String(), ReportHeaderTextRight = c.String(), CreatedBy = c.String(), ModifiedBy = c.String(), CreatedDate = c.DateTime(nullable: false), ModifiedDate = c.DateTime(nullable: false), }) .PrimaryKey(t => t.SiteDivisionSettingsId) .ForeignKey("Web.Divisions", t => t.DivisionId) .ForeignKey("Web.Sites", t => t.SiteId) .Index(t => t.SiteId) .Index(t => t.DivisionId); AddColumn("Web.ProductCategories", "DefaultSalesTaxProductCodeId", c => c.Int()); AddColumn("Web.ProductGroups", "DefaultSalesTaxGroupProductId", c => c.Int()); AddColumn("Web.PackingLines", "BaleCount", c => c.Int()); AddColumn("Web.LedgerHeaders", "ForLedgerHeaderId", c => c.Int()); AddColumn("Web.CarpetSkuSettings", "isVisibleSalesTaxProductCode", c => c.Boolean()); AddColumn("Web.CarpetSkuSettings", "SalesTaxProductCodeCaption", c => c.String(maxLength: 50)); AddColumn("Web.ChargeGroupSettings", "ProcessId", c => c.Int(nullable: false)); AddColumn("Web.LedgerSettings", "CancelDocTypeId", c => c.Int()); AddColumn("Web.StockHeaderSettings", "isPostedInStock", c => c.Boolean(nullable: false)); AddColumn("Web.PackingSettings", "isVisibleProductUID", c => c.Boolean()); AddColumn("Web.PackingSettings", "isVisibleBaleCount", c => c.Boolean()); AddColumn("Web.PackingSettings", "filterProductDivision", c => c.String()); AddColumn("Web.PackingSettings", "filterLedgerAccountGroups", c => c.String()); AddColumn("Web.PackingSettings", "filterLedgerAccounts", c => c.String()); AddColumn("Web.PackingSettings", "ProcessId", c => c.Int()); AddColumn("Web.PersonSettings", "isVisibleGstNo", c => c.Boolean()); AddColumn("Web.PersonSettings", "isMandatoryGstNo", c => c.Boolean()); AddColumn("Web.SaleInvoiceSettings", "DoNotUpdateProductUidStatus", c => c.Boolean()); AddColumn("Web.StockInHandSettings", "ShowOpening", c => c.Boolean(nullable: false)); AddColumn("Web.StockInHandSettings", "ProductTypeId", c => c.Int()); AddColumn("Web.StockInHandSettings", "TableName", c => c.String()); CreateIndex("Web.ProductCategories", "DefaultSalesTaxProductCodeId"); CreateIndex("Web.ProductGroups", "DefaultSalesTaxGroupProductId"); CreateIndex("Web.LedgerHeaders", "ForLedgerHeaderId"); CreateIndex("Web.ChargeGroupSettings", "ProcessId"); CreateIndex("Web.JobReceiveSettings", new[] { "DocTypeId", "SiteId", "DivisionId" }, unique: true, name: "IX_JobReceiveSettings_DocID"); CreateIndex("Web.LedgerSettings", "CancelDocTypeId"); CreateIndex("Web.PackingSettings", "ProcessId"); AddForeignKey("Web.ProductCategories", "DefaultSalesTaxProductCodeId", "Web.SalesTaxProductCodes", "SalesTaxProductCodeId"); AddForeignKey("Web.ProductGroups", "DefaultSalesTaxGroupProductId", "Web.ChargeGroupProducts", "ChargeGroupProductId"); AddForeignKey("Web.LedgerHeaders", "ForLedgerHeaderId", "Web.LedgerHeaders", "LedgerHeaderId"); AddForeignKey("Web.ChargeGroupSettings", "ProcessId", "Web.Processes", "ProcessId"); AddForeignKey("Web.LedgerSettings", "CancelDocTypeId", "Web.DocumentTypes", "DocumentTypeId"); AddForeignKey("Web.PackingSettings", "ProcessId", "Web.Processes", "ProcessId"); DropColumn("Web.Sites", "ReportHeaderTextLeft"); DropColumn("Web.Sites", "ReportHeaderTextRight"); } public override void Down() { AddColumn("Web.Sites", "ReportHeaderTextRight", c => c.String()); AddColumn("Web.Sites", "ReportHeaderTextLeft", c => c.String()); DropForeignKey("Web.SiteDivisionSettings", "SiteId", "Web.Sites"); DropForeignKey("Web.SiteDivisionSettings", "DivisionId", "Web.Divisions"); DropForeignKey("Web.PackingSettings", "ProcessId", "Web.Processes"); DropForeignKey("Web.LedgerSettings", "CancelDocTypeId", "Web.DocumentTypes"); DropForeignKey("Web.ChargeGroupSettings", "ProcessId", "Web.Processes"); DropForeignKey("Web.LedgerHeaders", "ForLedgerHeaderId", "Web.LedgerHeaders"); DropForeignKey("Web.ProductGroups", "DefaultSalesTaxGroupProductId", "Web.ChargeGroupProducts"); DropForeignKey("Web.ProductCategories", "DefaultSalesTaxProductCodeId", "Web.SalesTaxProductCodes"); DropIndex("Web.SiteDivisionSettings", new[] { "DivisionId" }); DropIndex("Web.SiteDivisionSettings", new[] { "SiteId" }); DropIndex("Web.PackingSettings", new[] { "ProcessId" }); DropIndex("Web.LedgerSettings", new[] { "CancelDocTypeId" }); DropIndex("Web.JobReceiveSettings", "IX_JobReceiveSettings_DocID"); DropIndex("Web.ChargeGroupSettings", new[] { "ProcessId" }); DropIndex("Web.LedgerHeaders", new[] { "ForLedgerHeaderId" }); DropIndex("Web.ProductGroups", new[] { "DefaultSalesTaxGroupProductId" }); DropIndex("Web.ProductCategories", new[] { "DefaultSalesTaxProductCodeId" }); DropColumn("Web.StockInHandSettings", "TableName"); DropColumn("Web.StockInHandSettings", "ProductTypeId"); DropColumn("Web.StockInHandSettings", "ShowOpening"); DropColumn("Web.SaleInvoiceSettings", "DoNotUpdateProductUidStatus"); DropColumn("Web.PersonSettings", "isMandatoryGstNo"); DropColumn("Web.PersonSettings", "isVisibleGstNo"); DropColumn("Web.PackingSettings", "ProcessId"); DropColumn("Web.PackingSettings", "filterLedgerAccounts"); DropColumn("Web.PackingSettings", "filterLedgerAccountGroups"); DropColumn("Web.PackingSettings", "filterProductDivision"); DropColumn("Web.PackingSettings", "isVisibleBaleCount"); DropColumn("Web.PackingSettings", "isVisibleProductUID"); DropColumn("Web.StockHeaderSettings", "isPostedInStock"); DropColumn("Web.LedgerSettings", "CancelDocTypeId"); DropColumn("Web.ChargeGroupSettings", "ProcessId"); DropColumn("Web.CarpetSkuSettings", "SalesTaxProductCodeCaption"); DropColumn("Web.CarpetSkuSettings", "isVisibleSalesTaxProductCode"); DropColumn("Web.LedgerHeaders", "ForLedgerHeaderId"); DropColumn("Web.PackingLines", "BaleCount"); DropColumn("Web.ProductGroups", "DefaultSalesTaxGroupProductId"); DropColumn("Web.ProductCategories", "DefaultSalesTaxProductCodeId"); DropTable("Web.SiteDivisionSettings"); DropTable("Web.CompanySettings"); CreateIndex("Web.JobReceiveSettings", "DivisionId"); CreateIndex("Web.JobReceiveSettings", "SiteId"); CreateIndex("Web.JobReceiveSettings", "DocTypeId"); } } }
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.Shapes; using Wpf.Dao; namespace Wpf { /// <summary> /// LoginWindow.xaml 的交互逻辑 /// 登陆窗口 /// </summary> public partial class LoginWindow : Window { public bool isLogin = false; public LoginWindow() { InitializeComponent(); this.MouseLeftButtonDown += (sender, e) => { if (e.ButtonState == MouseButtonState.Pressed) { this.DragMove(); } }; } private void Login(object sender, RoutedEventArgs e) { UserDao userDao = new UserDao(); if (Verify() != true) { MessageBox.Show("验证信息不能为空!"); return; } App.user.UserName = this.usrName.Text; App.user.Type = "管理员"; if (userDao.VertifyLogin(this.usrName.Text, this.usrPassWord.Password) == true) { isLogin = true; } else { isLogin = false; } this.Close(); } /// <summary> /// 验证数据 /// </summary> /// <param name="pt"></param> /// <returns></returns> private bool Verify() { if (this.usrName.Text != "" && this.usrPassWord.Password != "") { return true; } return false; } } }
namespace KioskClient.View { public interface IRefreshablePage { void Refresh(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using iSukces.Code.Interfaces; using JetBrains.Annotations; namespace iSukces.Code.AutoCode { public static class GeneratorsHelper { public static void AddInitCode(CsClass cl, string codeLine) { var method = cl.Methods.FirstOrDefault(a => a.Name == AutoCodeInitMethodName); if (method is null) method = cl.AddMethod(AutoCodeInitMethodName, "void") .WithVisibility(Visibilities.Private); method.Body += "\r\n" + codeLine; } public static CsExpression CallMethod(string instance, string method, params string[] arguments) => (CsExpression)string.Format("{0}.{1}({2})", instance, method, string.Join(", ", arguments)); public static CsExpression CallMethod(string method, params CsExpression[] arguments) { return (CsExpression)string.Format("{0}({1})", method, string.Join(", ", arguments.Select(a => a.Code))); } public static CsExpression CallMethod(string method, IArgumentsHolder holder) => (CsExpression)string.Format("{0}({1})", method, string.Join(", ", holder.GetArguments())); public static CsExpression CallMethod(string instance, string method, IArgumentsHolder holder) => (CsExpression)string.Format("{0}.{1}({2})", instance, method, string.Join(", ", holder.GetArguments())); public static MyStruct DefaultComparerMethodName(Type type, ITypeNameResolver resolver) { var comparer = typeof(Comparer<>).MakeGenericType(type); var comparerName = resolver.TypeName(comparer); return new MyStruct("{0}.Compare", $"{comparerName}.Default"); } public static string FieldName(string x) => "_" + x.Substring(0, 1).ToLower() + x.Substring(1); public static Type GetMemberResultType([NotNull] MemberInfo mi) { if (mi == null) throw new ArgumentNullException(nameof(mi)); if (mi is PropertyInfo pi) return pi.PropertyType; if (mi is FieldInfo fi) return fi.FieldType; if (mi is MethodInfo mb) return mb.ReturnType; throw new NotSupportedException(mi.GetType().ToString()); } public static string GetTypeName(this INamespaceContainer container, Type type) { //todo: Generic types if (type == null) return null; if (type.IsArray) { var arrayRank = type.GetArrayRank(); var st = GetTypeName(container, type.GetElementType()); if (arrayRank < 2) return st + "[]"; return string.Format("{0}[{1}]", st, new string(',', arrayRank - 1)); } var simple = type.SimpleTypeName(); if (!string.IsNullOrEmpty(simple)) return simple; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (type.DeclaringType != null) return GetTypeName(container, type.DeclaringType) + "." + type.Name; string fullName; { var w = new ReflectionTypeWrapper(type); if (w.IsGenericType) { if (w.IsGenericTypeDefinition) { var args = w.GetGenericArguments(); var args2 = string.Join(",", args.Select(a => a.Name)); fullName = type.FullName.Split('`')[0] + "<" + args2 + ">"; } else { { var nullable = w.UnwrapNullable(true); if (nullable != null) return GetTypeName(container, nullable) + "?"; } var gt = type.GetGenericTypeDefinition(); var args = w.GetGenericArguments(); var args2 = string.Join(",", args.Select(a => GetTypeName(container, a))); fullName = gt.FullName.Split('`')[0] + "<" + args2 + ">"; } } else { fullName = type.FullName; } } var typeNamespace = type.Namespace; var canCut = container?.IsKnownNamespace(typeNamespace) ?? false; return canCut ? fullName.Substring(typeNamespace.Length + 1) : fullName; } public static string GetWriteMemeberName(PropertyInfo pi) { var props = pi.GetCustomAttribute<Auto.WriteMemberAttribute>(); return !string.IsNullOrEmpty(props?.Name) ? props.Name : pi.Name; } public static HashSet<T> MakeCopy<T>(IEnumerable<T> source, IEnumerable<T> append = null, IEnumerable<T> remove = null) { var s = new HashSet<T>(); if (source != null) foreach (var i in source) s.Add(i); if (append != null) foreach (var i in append) s.Add(i); if (remove != null) foreach (var i in remove) s.Remove(i); return s; } public struct MyStruct { public MyStruct(string expressionTemplate, string instance = null) { Instance = instance; ExpressionTemplate = expressionTemplate; } public string GetCode() { if (string.IsNullOrEmpty(Instance)) return ExpressionTemplate; return string.Format(ExpressionTemplate, Instance); } public string Instance { get; } public string ExpressionTemplate { get; } } public const BindingFlags AllVisibility = BindingFlags.NonPublic | BindingFlags.Public; public const BindingFlags AllInstance = BindingFlags.Instance | AllVisibility; public const BindingFlags AllStatic = BindingFlags.Static | AllVisibility; public const BindingFlags All = AllInstance | BindingFlags.Static; public const BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance; public const string StringEmpty = "string.Empty"; public const string AutoCodeInitMethodName = "AutocodeInit"; /*public static string TypeName<T>(this INamespaceContainer container) { return TypeName(container, typeof(T)); }*/ } }
using FluentNHibernate.Automapping; using FluentNHibernate.Automapping.Alterations; using NHibernate.Type; using Profiling2.Domain.Prf.Suggestions; namespace Profiling2.Infrastructure.NHibernateMaps.Overrides { public class AdminSuggestionPersonResponsibilityOverride : IAutoMappingOverride<AdminSuggestionPersonResponsibility> { public void Override(AutoMapping<AdminSuggestionPersonResponsibility> mapping) { mapping.Map(x => x.SuggestionFeatures).CustomType<XmlDocType>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace xKnight.Attacking { public enum EncodedXssAttackStatus { InitAttackStarted, InitAttackFinished, AttackStarted, AttackFinished, AttackHalted } }
using System; using System.Collections.Generic; using System.Linq; using Fingo.Auth.AuthServer.Services.Interfaces; using Fingo.Auth.DbAccess.Models; using Fingo.Auth.DbAccess.Models.Policies.Enums; using Fingo.Auth.DbAccess.Models.Statuses; using Fingo.Auth.DbAccess.Repository.Interfaces; using Fingo.Auth.Domain.Models.UserModels; using Fingo.Auth.Domain.Policies.CheckingFunctions; using Fingo.Auth.Domain.Policies.ConfigurationClasses; using Fingo.Auth.Domain.Policies.Enums; using Fingo.Auth.Domain.Policies.ExtensionMethods; using Fingo.Auth.Domain.Policies.Factories.Interfaces; using Fingo.Auth.Domain.Projects.Factories.Interfaces; using Fingo.Auth.Domain.Users.Factories.Interfaces; using Fingo.Auth.Infrastructure.Logging; using Fingo.Auth.JsonWrapper; namespace Fingo.Auth.AuthServer.Services.Implementation { public class AccountService : IAccountService { private readonly IAddUserFactory _addUserFactory; private readonly IChangePasswordToUserFactory _changePasswordToUserFactory; private readonly IGetAllProjectFactory _getAllProjectFactory; private readonly IGetPoliciesFromProjectFactory _getPoliciesFromProjectFactory; private readonly IHashingService _hashingService; private readonly IUserRepository _userRepository; public AccountService(IAddUserFactory addUserFactory , ILogger<AccountService> logger , IChangePasswordToUserFactory changePasswordToUserFactory , IGetPoliciesFromProjectFactory getPoliciesFromProjectFactory , IGetAllProjectFactory getAllProjectFactory , IUserRepository userRepository , IHashingService hashingService) { _getAllProjectFactory = getAllProjectFactory; _getPoliciesFromProjectFactory = getPoliciesFromProjectFactory; _addUserFactory = addUserFactory; _changePasswordToUserFactory = changePasswordToUserFactory; _userRepository = userRepository; _hashingService = hashingService; } public string CreateNewUserInProject(UserModel user , Guid projectGuid) { int projectId; try { projectId = _getAllProjectFactory.Create().Invoke().FirstOrDefault(p => p.ProjectGuid == projectGuid).Id; } catch (Exception) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find id of project with guid: {projectGuid}" }.ToJson(); } List<Tuple<Policy , PolicyConfiguration>> list; try { list = _getPoliciesFromProjectFactory.Create() .Invoke(projectId) .WithTypes(PolicyType.AccountCreation) .ToList(); } catch (Exception) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find policies of project with id: {projectId}" }.ToJson(); } try { foreach (var policyTuple in list) switch (policyTuple.Item1) { case Policy.MinimumPasswordLength: if ( !Check.MinimumPasswordLength((MinimumPasswordLengthConfiguration) policyTuple.Item2 , user.Password)) return new JsonObject {Result = JsonValues.PasswordLengthIncorrect}.ToJson(); break; case Policy.RequiredPasswordCharacters: if ( !Check.RequiredPasswordCharacters( (RequiredPasswordCharactersConfiguration) policyTuple.Item2 , user.Password)) return new JsonObject {Result = JsonValues.RequiredCharactersViolation}.ToJson(); break; case Policy.ExcludeCommonPasswords: if ( !Check.ExcludeCommonPasswords((ExcludeCommonPasswordsConfiguration) policyTuple.Item2 , user.Password)) return new JsonObject {Result = JsonValues.PasswordTooCommon}.ToJson(); break; default: throw new Exception("Invalid policy."); } } catch (Exception e) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Unable to check policies ({e.Message})." }.ToJson(); } try { user.PasswordSalt = _hashingService.GenerateNewSalt(); user.Password = _hashingService.HashWithGivenSalt(user.Password , user.PasswordSalt); _addUserFactory.Create().Invoke(user , projectGuid); } catch (Exception e) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"User was not created in project because of some internal error ({e.Message})." }.ToJson(); } return new JsonObject {Result = JsonValues.UserCreatedInProject}.ToJson(); } public string PasswordChangeForUser(ChangingPasswordUser user) { if (user.NewPassword != user.ConfirmNewPassword) return new JsonObject { Result = JsonValues.Error , ErrorDetails = "Confirmed password must match new password." }.ToJson(); IEnumerable<Project> projects; try { var id = _userRepository.GetAll().FirstOrDefault(x => x.Login == user.Email).Id; projects = _userRepository.GetAllProjectsFromUser(id); } catch { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find user's (login: {user.Email}) id and all projects that they are in." }.ToJson(); } try { foreach (var project in projects) { var policies = _getPoliciesFromProjectFactory.Create().Invoke(project.Id).ToList(); foreach (var policy in policies) switch (policy.Item1) { case Policy.MinimumPasswordLength: if ( !Check.MinimumPasswordLength((MinimumPasswordLengthConfiguration) policy.Item2 , user.NewPassword)) return new JsonObject {Result = JsonValues.PasswordLengthIncorrect}.ToJson(); break; case Policy.RequiredPasswordCharacters: if ( !Check.RequiredPasswordCharacters( (RequiredPasswordCharactersConfiguration) policy.Item2 , user.NewPassword)) return new JsonObject {Result = JsonValues.RequiredCharactersViolation}.ToJson(); break; case Policy.ExcludeCommonPasswords: if ( !Check.ExcludeCommonPasswords((ExcludeCommonPasswordsConfiguration) policy.Item2 , user.NewPassword)) return new JsonObject {Result = JsonValues.PasswordTooCommon}.ToJson(); break; } } } catch { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find and check all policies for user (login: {user.Email})." }.ToJson(); } try { user.Password = _hashingService.HashWithDatabaseSalt(user.Password , user.Email); user.NewPassword = _hashingService.HashWithDatabaseSalt(user.NewPassword , user.Email); _changePasswordToUserFactory.Create().Invoke(user); } catch (Exception e) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = e.Message }.ToJson(); } return new JsonObject { Result = JsonValues.UsersPasswordChanged }.ToJson(); } public string SetPasswordForUser(string token , string password) { var user = _userRepository.GetAll().FirstOrDefault(u => u.ActivationToken == token); if (user == null) return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find user with token: {token}." }.ToJson(); var projects = _userRepository.GetAllProjectsFromUser(user.Id); if (projects == null) return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find projects of user with id: {user.Id}." }.ToJson(); try { foreach (var project in projects) { var policies = _getPoliciesFromProjectFactory.Create().Invoke(project.Id).ToList(); foreach (var policy in policies) switch (policy.Item1) { case Policy.MinimumPasswordLength: if ( !Check.MinimumPasswordLength((MinimumPasswordLengthConfiguration) policy.Item2 , password)) return new JsonObject {Result = JsonValues.PasswordLengthIncorrect}.ToJson(); break; case Policy.RequiredPasswordCharacters: if ( !Check.RequiredPasswordCharacters( (RequiredPasswordCharactersConfiguration) policy.Item2 , password)) return new JsonObject {Result = JsonValues.RequiredCharactersViolation}.ToJson(); break; case Policy.ExcludeCommonPasswords: if ( !Check.ExcludeCommonPasswords((ExcludeCommonPasswordsConfiguration) policy.Item2 , password)) return new JsonObject {Result = JsonValues.PasswordTooCommon}.ToJson(); break; } } } catch (Exception e) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not find and check all policies for user (id: {user.Id}) ({e.Message})." }.ToJson(); } try { user.PasswordSalt = _hashingService.GenerateNewSalt(); user.Password = _hashingService.HashWithGivenSalt(password , user.PasswordSalt); user.Status = UserStatus.Active; user.LastPasswordChange = DateTime.UtcNow; _userRepository.Edit(user); } catch (Exception e) { return new JsonObject { Result = JsonValues.Error , ErrorDetails = $"Could not generate salt & password hash and edit user in the database ({e.Message})." }.ToJson(); } return new JsonObject { Result = JsonValues.PasswordSet }.ToJson(); } } }
 using Ardalis.Specification; using WritingPlatformCore.Entities; namespace WritingPlatformCore.Specifications { public class CatalogFilterPaginatedSpecification : Specification<CatalogItem> { [System.Obsolete] public CatalogFilterPaginatedSpecification(int skip, int take, int? ganreId, int? languageId) { Query .Where(q => (!ganreId.HasValue || q.CatalogGanreId == ganreId) && (!languageId.HasValue || q.CatalogLanguageId == languageId)) .Paginate(skip, take); } } }
using System.Web.Mvc; using TwitterLikeApp.Entity; using TwitterLikeApp.UI.Models; using TwitterLikeApp.UI.Services; namespace TwitterLikeApp.UI.Controllers { public class BaseController : Controller { protected IContext DataContext; public User CurrentUser { get; private set; } public IRibbitService Ribbits { get; private set; } public IUserService Users { get; private set; } public ISecurityService Security { get; private set; } public IUserProfileService Profiles { get; private set; } public BaseController() { DataContext = new Context(); Users = new UserService(DataContext); Ribbits = new RibbitService(DataContext); Security = new SecurityService(Users); CurrentUser = Security.GetCurrentUser(); Profiles = new UserProfileService(DataContext); } protected override void Dispose(bool disposing) { if (DataContext != null) { DataContext.Dispose(); } base.Dispose(disposing); } public ActionResult GoToReferrer() { if (Request.UrlReferrer != null) { return Redirect(Request.UrlReferrer.AbsoluteUri); } return RedirectToAction("Index", "Home"); } } }
using System; namespace Faker.ValueGenerator.PrimitiveTypes.IntegerTypes { public class SByteGenerator : IPrimitiveTypeGenerator { private static readonly Random Random = new Random(); public Type GenerateType { get; set; } public object Generate() { GenerateType = typeof(sbyte); return (sbyte) Random.Next(); } } }
using Docller.Core.Models; using Docller.Core.Repository; namespace Docller.Core.Services { public class UserSubscriptionService :ServiceBase<IUserSubscriptionRepository>, IUserSubscriptionService { public UserSubscriptionService(IUserSubscriptionRepository repository) : base(repository) { } #region Implementation of IUserSubscriptionService public void UpdateUser(User user) { this.Repository.UpdateUser(user); } #endregion } }
namespace BDTest.Tests; public class MyTestContext { public string Id = Guid.NewGuid().ToString(); }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Xml; using System.Xml.Schema; namespace _3._1_Validating_JSON_XML { class Program { static void Main(string[] args) { var serializer = new JavaScriptSerializer(); //Validador de Json var resultJson = serializer.Deserialize<Dictionary<string, object>>(Aux.Json()); //Validador de Xml Aux.ValidateXML(); //List<string> list = new List<string>(resultJson.Keys); //List<string> list2 = new List<string>(resultXml.Keys); Console.WriteLine(resultJson.Keys.Count); Console.ReadKey(); } } public class Aux { //Classe que retorna um json public static string Json() { return @"{""menu"": { ""id"": ""file"", ""value"": ""File"", ""popup"": { ""menuitem"": [ {""value"": ""New"", ""onclick"": ""CreateNewDoc()""}, {""value"": ""Open"", ""onclick"": ""OpenDoc()""}, {""value"": ""Close"", ""onclick"": ""CloseDoc()""} ] } }}"; } //Classe que retorna um Xml //public static string Xml() //{ // string path = @"..\..\XML.xml"; // return File.ReadAllText(path); //} public static void ValidateXML() { XmlReader reader = XmlReader.Create(@"..\..\XML.xml"); XmlDocument document = new XmlDocument(); document.Schemas.Add("", @"..\..\XML.xsd"); document.Load(reader); ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler); document.Validate(eventHandler); Console.WriteLine(document.Name); Console.WriteLine(document.BaseURI); } static void ValidationEventHandler(object sender, ValidationEventArgs e) { switch (e.Severity) { case XmlSeverityType.Error: Console.WriteLine("Error: {0}", e.Message); break; case XmlSeverityType.Warning: Console.WriteLine("Warning {0}", e.Message); break; default: throw new ArgumentOutOfRangeException(); } } } }
using System; using System.IO; namespace Cradiator.MigrateConfig { class Program { static int Main(string[] args) { var xmlFile = args.Length == 1 ? args[0] : "Cradiator.exe.config"; if (!File.Exists(xmlFile)) { Console.WriteLine("xml config file doesn't exist: '{0}'", xmlFile); return 1; } var migrate = new MultiviewMigrator(xmlFile); var returnVal = migrate.Migrate(); return string.IsNullOrEmpty(returnVal) ? 0 : 1; } } }
namespace Api.Versioned { public static class VersionConstants { // // Configuration Settings // public const string ConfVersionHeader = "configuration:api-version-header-description"; public const string ConfVersionDefault = "configuration:api-version-default"; // // Versioned Constants // public const string VersionHeader = "api-version"; public const int VersionDefault = 1; } }