text
stringlengths
13
6.01M
using EntMob_Xamarin.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using EntMob_Xamarin.Services; using EntMob.DAL; namespace EntMob_Xamarin { public class ViewModelLocator { private static IUserService userService = new UserService(new UserRepository()); private static ISessionService sessionService = new SessionService(new SessionRepository()); private static ITemperatureService temperatureService = new TemperatureService(new TemperatureRepository()); private static IHumidityService humidityService = new HumidityService(new HumidityRepository()); private static RunnerViewModel runnerViewModel; private static RegisterViewModel registerViewModel; private static TimerViewModel timerViewModel; private static ValuesViewModel valuesViewModel; public static RunnerViewModel Main() { return runnerViewModel ?? (runnerViewModel = new RunnerViewModel(userService)); } public static RegisterViewModel Register() { return registerViewModel ?? (registerViewModel = new RegisterViewModel(userService)); } public static TimerViewModel Timer() { return timerViewModel ?? (timerViewModel = new TimerViewModel(sessionService, temperatureService, humidityService)); } public static ValuesViewModel Values() { return valuesViewModel ?? (valuesViewModel = new ValuesViewModel(humidityService)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; namespace SbdProjekto.Models { public class Rejon { public int RejonId { get; set; } [DisplayName("Nazwa rejonu")] public string Nazwa { get; set; } [DisplayName("Województwo")] public string Wojewodztwo { get; set; } public ICollection<Kurier> Kurierzy { get; set; } public Rejon() { this.Kurierzy = new Collection<Kurier>(); } } }
using LuckyMasale.BAL.Managers; using LuckyMasale.Shared.DTO; using PayPal.Api; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace LuckyMasale.WebApi.Controllers { public class PayPalController : ApiController { #region Properties private Lazy<IPayPalManager> payPalManager; #endregion #region Constructors public PayPalController(Lazy<IPayPalManager> payPalManager) { this.payPalManager = payPalManager; } #endregion #region Methods [HttpPost] public async Task<Payment> MakePayment(PaymentInformation paymentInformation) { return await payPalManager.Value.RunSample(paymentInformation); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using static Nac.Field.Citect.CtApi; namespace Nac.Field.Citect { public class NacFieldCitectTagList : IDisposable { private const uint cCitectErr25 = 268443673; //0x10002019 => 0x19 = Citect generic error 25 data not yet valid (to be ignored as per citect doc) private const uint cWinErr997 = 997; //0x3E5 => overlaped operation pending private uint PollTime; private bool Raw; private Dictionary<string, uint> tagHandlesRead = new Dictionary<string, uint>(); private Dictionary<string, uint> tagHandlesWrite = new Dictionary<string, uint>(); private Dictionary<string, string> tagCache = new Dictionary<string, string>(); private uint CtApi; private uint HandleRead, HandleWrite; public NacFieldCitectTagList(uint hCtApi, uint pollTime = 500, bool raw = true) { HandleRead = ctListNew(hCtApi, 0/*, CT_LIST_EVENT_NEW | CT_LIST_EVENT_STATUS*/); //HandleWrite = ctListNew(hCtApi, 0/*, CT_LIST_EVENT_NEW | CT_LIST_EVENT_STATUS*/); CtApi = hCtApi; PollTime = pollTime; Raw = raw; } private void UpdateRead(string[] tagNames) { foreach (var tagName in tagNames) if (!tagHandlesRead.ContainsKey(tagName)) { tagHandlesRead.Add(tagName, ctListAddEx(HandleRead, tagName, Raw, PollTime, 0d)); tagCache[tagName] = "?"; } } private void UpdateWrite(string[] tagNames) { foreach (var tagName in tagNames) if (!tagHandlesWrite.ContainsKey(tagName)) tagHandlesWrite.Add(tagName, ctListAddEx(HandleWrite, tagName, Raw, PollTime, 0d)); } public void Dispose() { ctListFree(HandleRead); HandleRead = 0; ctListFree(HandleWrite); HandleWrite = 0; } internal bool Read(string[] names, out string[] sValues) { UpdateRead(names); int n = names.Length; sValues = new string[n]; if (ctListRead(HandleRead, 0)) { StringBuilder sb = new StringBuilder(255); for (int i = 0; i < n; i++) if (ctListData(tagHandlesRead[names[i]], sb, sb.Capacity, 0)) tagCache[names[i]] = sValues[i] = sb.ToString(); else { int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (error == cCitectErr25) sValues[i] = tagCache[names[i]]; else sValues[i] = "?"; //Debug.Print($"ctListRead={error}"); } } else { int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (error == cWinErr997) for (int i = 0; i < n; i++) sValues[i] = tagCache[names[i]]; else sValues = null; } return sValues != null; } public bool Write(string[] names, string[] sValues, ref bool[] successes) { var n = names.Length; bool writeOK = false; for (int i = 0; i < n; i++) if (ctTagWrite(CtApi, names[i], sValues[i])) { writeOK |= successes[i] = true; tagCache[names[i]] = sValues[i]; } return writeOK; } internal bool Write1(string[] names, string[] sValues, out bool[] successes) { //successes = null; //return false; UpdateWrite(names); int n = names.Length; successes = new bool[n]; //for (int i = 0; i < n; i++) successes[i] = ctListWrite(tagHandlesWrite[names[i]], sValues[i], 0); if (!ctListWrite(tagHandlesWrite[names[0]], sValues[0], 0)) { int error = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); Debug.Print($"ctListRead={error}"); } return true; //return successes.Any(success => success); } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; [CanEditMultipleObjects()] [CustomEditor(typeof(PimpedMonoBehaviour), true)] public partial class PimpMyEditorInspector2 : Editor { protected static PimpMyEditorInspector2 instance; [System.AttributeUsage(System.AttributeTargets.Method)] private class RunOnEnableAttribute : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Method)] private class RunOnDisableAttribute : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Method)] private class RunBeforeOnInspectorGUIAttribute : System.Attribute { public readonly int priority; public RunBeforeOnInspectorGUIAttribute() { priority = 0; } public RunBeforeOnInspectorGUIAttribute(int priority) { this.priority = priority; } } [System.AttributeUsage(System.AttributeTargets.Method)] private class RunAfterOnInspectorGUIAttribute : System.Attribute { } List<System.Reflection.MethodInfo> runOnEnable; List<System.Reflection.MethodInfo> runOnDisable; List<System.Reflection.MethodInfo> runBeforeOnInspectorGUI; List<System.Reflection.MethodInfo> runAfterOnInspectorGUI; void OnEnable() { PimpMyEditorInspector2.instance = this; runOnEnable = new List<System.Reflection.MethodInfo>(); runOnDisable = new List<System.Reflection.MethodInfo>(); runBeforeOnInspectorGUI = new List<System.Reflection.MethodInfo>(); runAfterOnInspectorGUI = new List<System.Reflection.MethodInfo>(); System.Reflection.MethodInfo[] m = typeof(PimpMyEditorInspector2).GetMethods( System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ); for (int i = 0; i < m.Length; i++) { object[] att = m[i].GetCustomAttributes(true); for (int a = 0; a < att.Length; a++) { System.Type t = att[a].GetType(); if (t == typeof(RunOnEnableAttribute)) runOnEnable.Add(m[i]); if (t == typeof(RunOnDisableAttribute)) runOnDisable.Add(m[i]); if (t == typeof(RunBeforeOnInspectorGUIAttribute)) runBeforeOnInspectorGUI.Add(m[i]); if (t == typeof(RunAfterOnInspectorGUIAttribute)) runAfterOnInspectorGUI.Add(m[i]); } } for (int i = 0; i < runOnEnable.Count; i++) { runOnEnable[i].Invoke(this, new object[0]); } for (int i = 0; i < runBeforeOnInspectorGUI.Count; i++) { int pi = ((RunBeforeOnInspectorGUIAttribute)(runBeforeOnInspectorGUI[i].GetCustomAttributes(typeof(RunBeforeOnInspectorGUIAttribute), true)[0])).priority; for (int j = i + 1; j < runBeforeOnInspectorGUI.Count; j++) { int pj = ((RunBeforeOnInspectorGUIAttribute)(runBeforeOnInspectorGUI[j].GetCustomAttributes(typeof(RunBeforeOnInspectorGUIAttribute), true)[0])).priority; if (pj < pi) { System.Reflection.MethodInfo tmp = runBeforeOnInspectorGUI[i]; runBeforeOnInspectorGUI[i] = runBeforeOnInspectorGUI[j]; runBeforeOnInspectorGUI[j] = tmp; pi = pj; } } } } void OnDisable() { for (int i = 0; i < runOnDisable.Count; i++) { runOnDisable[i].Invoke(this, new object[0]); } } protected abstract class SP { abstract public void DrawEditorGUI(SerializedObject serializedObject, int indentBonus); abstract public string toStr(SerializedObject serializedObject, string indent); public string path; public List<SP> children; public SP parent; public int depth; public string tt; public string ht; public string gr; public string gt; } protected class SP_SerializedProperty : SP { public SP_SerializedProperty(SerializedProperty p) { // this.p = p.Copy(); this.path = p.propertyPath; this.depth = p.depth; this.children = new List<SP>(); } public override void DrawEditorGUI(SerializedObject serializedObject, int indentBonus) { SerializedProperty p = serializedObject.FindProperty(path); bool drawChildren = true; bool didStartTooltip = false; if (p != null) { // if(!string.IsNullOrEmpty(gr)) // indentBonus++; EditorGUI.indentLevel = p.depth + indentBonus; // if(p.name == "stuff" || p.name == "aaa" || p.name == "bar") // Debug.Log(p.name + " => " + EditorGUI.indentLevel); if (tt != null) { didStartTooltip = true; EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.HelpBox(tt, MessageType.Info); // // EditorGUILayout.BeginVertical(GUI.skin.box); // // if ((PimpMyEditorInspector2.instance.showTooltipAbove && p.isArray) || !p.hasChildren) // { // EditorGUILayout.Separator(); // EditorGUILayout.HelpBox(tt, MessageType.Info); // } drawChildren = EditorGUILayout.PropertyField( p, new GUIContent(ObjectNames.NicifyVariableName(p.name) + (ht != null ? " *":""), ht != null ? ht : "") ); // if (drawChildren && !PimpMyEditorInspector2.instance.showTooltipAbove) // { // EditorGUILayout.HelpBox(tt, MessageType.Info); // } // EditorGUILayout.EndVertical(); } else if (ht != null) { drawChildren = EditorGUILayout.PropertyField( p, new GUIContent(ObjectNames.NicifyVariableName(p.name) + " *", ht) ); } else drawChildren = EditorGUILayout.PropertyField(p); } if (!drawChildren) { if(didStartTooltip) EditorGUILayout.EndVertical(); return; } string cgr = null; bool indented = false; for (int i = 0; i < children.Count; i++) { if (children[i].gr != cgr) { if (indented) { indentBonus--; indented = false; //EditorGUILayout.EndVertical(); } cgr = children[i].gr; if (children[i].gr != null) { EditorGUI.indentLevel = (p!=null?p.depth+1:0) + indentBonus; bool isFoldout = EditorPrefs.GetBool("PimpMyEditor-Foldout-" + path + "-" + i, true); bool isStillFoldout = EditorGUILayout.Foldout(isFoldout, children[i].gr); if (isStillFoldout != isFoldout) EditorPrefs.SetBool("PimpMyEditor-Foldout-" + path + "-" + i, isStillFoldout); if (isFoldout && children[i].gt != null) { EditorGUI.indentLevel++; EditorGUILayout.HelpBox(children[i].gt, MessageType.Info); EditorGUI.indentLevel--; } if (!isFoldout) { int j = i; while (j < children.Count && children[j].gr == cgr) j++; if (j != i) i = j - 1; cgr = null; continue; } indentBonus++; indented = true; } } children[i].DrawEditorGUI(serializedObject, indentBonus); } if(didStartTooltip) EditorGUILayout.EndVertical(); // if (indented) // EditorGUILayout.EndVertical(); } public override string toStr(SerializedObject serializedObject, string indent) { SerializedProperty p = serializedObject.FindProperty(path); string s = indent + (p == null ? "null\n" : p.name + " (" + p.hasChildren + ", " + p.hasVisibleChildren + ") " + "(" + (this.gr != null ? this.gr : "no group") + ")\n"); for (int i = 0; i < children.Count; i++) { s += children[i].toStr(serializedObject, indent + "\t"); } return s; } } private SP first; public override void OnInspectorGUI() { serializedObject.Update(); SerializedProperty p = serializedObject.GetIterator(); first = new SP_SerializedProperty(p); SP current = first; SP last = first; bool showChildren = true; while (p.NextVisible(showChildren)) { SP next = new SP_SerializedProperty(p); if (next.depth > last.depth) { next.parent = last; last.children.Add(next); current = last; } else { while (next.depth <= current.depth) current = current.parent; next.parent = current; current.children.Add(next); } last = next; } // Run all required before inspector gui for (int i = 0; i < runBeforeOnInspectorGUI.Count; i++) { runBeforeOnInspectorGUI[i].Invoke(this, new object[0]); } // Debug.Log(first.toStr(serializedObject, "")); // EditorGUIUtility.LookLikeInspector(); first.DrawEditorGUI(serializedObject, 1); serializedObject.ApplyModifiedProperties(); if (runAfterOnInspectorGUI.Count > 0) { EditorGUILayout.Separator(); EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUI.indentLevel = 0; bool showOptions = EditorPrefs.GetBool("PimpMyEditor-ShowOptions-" + target.GetType(), false); bool so = EditorGUILayout.Foldout(showOptions, "Pimp Options"); if (so != showOptions) EditorPrefs.SetBool("PimpMyEditor-ShowOptions-" + target.GetType(), so); if (so) { EditorGUI.indentLevel = 1; // Run all required after inspector gui for (int i = 0; i < runAfterOnInspectorGUI.Count; i++) { runAfterOnInspectorGUI[i].Invoke(this, new object[0]); } } EditorGUILayout.EndVertical(); } EditorGUIUtility.LookLikeControls(); } protected System.Reflection.FieldInfo GetSerializedPropertyFieldInfo(SerializedProperty p) { string[] path = p.propertyPath.Split('.'); System.Reflection.FieldInfo info = null; System.Reflection.FieldInfo _info = null; System.Type type = target.GetType(); for (int i = 0; i < path.Length; i++) { System.Type searchType = type; do { info = searchType.GetField( path[i], System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic ); searchType = searchType.BaseType; } while (searchType != null && info == null); _info = info == null ? _info : info; if (info == null && path[i] == "Array") { i++; if (path.Length > i + 1 && path[i].IndexOf("data[") == 0) { // get the type of the array string typeName = type.ToString(); typeName = typeName.Replace("[]", ""); foreach (System.Reflection.Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.FullName.IndexOf("Assembly-CSharp,") == 0) { foreach (System.Type atype in assembly.GetTypes()) { if (atype.FullName == typeName) { // This is my type type = atype; break; } } break; } } continue; } else if (path[i].IndexOf("data[") == 0) return _info; return null; } if (info == null) { return null; } type = info.FieldType; } return info; } protected object GetSerializedPropertyFieldValue(SerializedProperty p) { string[] path = p.propertyPath.Split('.'); System.Reflection.FieldInfo info = null; System.Type type = target.GetType(); object currentValue = p.serializedObject.targetObject; for (int i = 0; i < path.Length; i++) { info = type.GetField(path[i]); if (info == null && path[i] == "Array") { i++; if (path.Length > i + 1 && path[i].IndexOf("data[") == 0) { int index = int.Parse(path[i].Replace("data[", "").Replace("]", "")); object[] objArr = ((object[])currentValue); if (objArr == null || objArr.Length <= index) return null; currentValue = objArr[index]; // get the type of the array string typeName = type.ToString(); typeName = typeName.Replace("[]", ""); foreach (System.Reflection.Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.FullName.IndexOf("Assembly-CSharp,") == 0) { foreach (System.Type atype in assembly.GetTypes()) { if (atype.FullName == typeName) { // This is my type type = atype; break; } } break; } } continue; } else if (path[i].IndexOf("data[") == 0 && currentValue != null) { int index = int.Parse(path[i].Replace("data[", "").Replace("]", "")); try { object[] objArr = ((object[])currentValue); if (objArr == null || objArr.Length <= index) return null; return objArr[index]; } catch(System.Exception e0) { try { System.Array array = (System.Array) currentValue; if(array == null || array.Length <= index) return null; return array.GetValue(index); } catch(System.Exception e1) { if (currentValue.GetType().IsGenericType) { try { IList list = (IList)currentValue; return list[index]; } catch (System.Exception e2) { Debug.LogWarning( "Pimp My Editor: Unable to get value of element in array. Email info@biometricgames.com for support if the problem does not go away magically all by itself. Did you try rebooting? :-p" + "\n\n" + e0.ToString() + "\n=====\n" + e1.ToString() + "\n======\n" + e2.ToString() ); } } else { Debug.LogWarning( "Pimp My Editor: Unable to get value of element in array. Email info@biometricgames.com for support if the problem does not go away magically all by itself. Did you try rebooting? :-p" + "\n\n" + e0.ToString() + "\n=====\n" + e1.ToString() ); } } } } return null; } if (info == null) { return null; } currentValue = info.GetValue(currentValue); type = info.FieldType; } return currentValue; } protected bool showTooltipAbove; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; namespace BudgetApp.Domain.Concrete { public class LedgerEntry { public enum ItemType { CREDIT, EXPENSE }; [HiddenInput(DisplayValue=false)] public int LedgerEntryID { get; set; } [DataType(DataType.Date)] public DateTime Time { get; set; } [Required(ErrorMessage="Please add a description")] public String Description { get; set; } [DataType(DataType.Currency)] public Decimal Price { get; set; } public String Category { get; set; } public String EntryType { get; set; } public String LedgerName { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace evrostroy.Web.Models { public class RegisterModel { [Required(ErrorMessage="Введите имя!")] [RegularExpression(@"^[а-яА-Я]{1,50}", ErrorMessage = "Неверный формат имени!")] [Display(Name = "Имя")] public string NameUs { get; set; } [Required(ErrorMessage ="Введите номер телефона!")] [RegularExpression(@"^[0-9-+)(]{1,20}", ErrorMessage = "Неверный формат ввода номера телефона!")] [Display(Name = "Телефон")] public string PhoneUs { get; set; } [Required(ErrorMessage = "Введите email адрес!")] [Display(Name = "Email")] [DataType(DataType.EmailAddress)] [RegularExpression(@"^[a-zA-Z0-9.-]{1,30}@[a-zA-Z0-9]{1,20}\.[A-Za-z]{2,6}", ErrorMessage = "Неверный формат email(xxxxxx@xxx.xx).")] public string EmailUs { get; set; } [Required(ErrorMessage ="Введите название города!")] [Display(Name = "Город")] [RegularExpression(@"^[а-яА-Я-]{1,150}", ErrorMessage = "Неверный формат названия города!")] public string CityUs { get; set; } [Required(ErrorMessage = "Введите название улицы и номер дома, подъезда, этажа и квартиры!")] [Display(Name = "Улица, дом, подъезд, этаж, квартира")] public string StreetUs { get; set; } [Required(ErrorMessage ="Введите пароль!")] [Display(Name = "Пароль")] [DataType(DataType.Password)] public string PasswordUs { get; set; } [Required(ErrorMessage = "Введите пароль!")] [Display(Name = "Подтвердите пароль")] [DataType(DataType.Password)] [Compare("PasswordUs", ErrorMessage = "Пароли не совпадают!")] public string ConfPassword { get; set; } } public class LoginModel { [Required(ErrorMessage = "Введите email адрес!")] [Display(Name = "Имя пользователя(Email)")] [RegularExpression(@"^[a-zA-Z0-9.-]{1,30}@[a-zA-Z0-9]{1,20}\.[A-Za-z]{2,6}", ErrorMessage = "Неверный формат email(xxxxx@xxx.xx).")] [DataType(DataType.EmailAddress)] public string NameIn { get; set; } [Required(ErrorMessage = "Введите пароль!")] [Display(Name = "Пароль")] [DataType(DataType.Password)] public string PasswordIn { get; set; } } public class NewpasswordModel { [Required(ErrorMessage = "Введите email адрес!")] [Display(Name = "Email")] [DataType(DataType.EmailAddress)] [RegularExpression(@"^[a-zA-Z0-9.-]{1,30}@[a-zA-Z0-9]{1,20}\.[A-Za-z]{2,6}", ErrorMessage = "Неверный формат email(xxxxxx@xxx.xx).")] public string EmailUs { get; set; } } }
using System; using System.Linq; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.SYS { public partial class SNRule { #region Non O/R Mapping Properties //TODO: Add Non O/R Mapping Properties here. [CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.DocumentsType, ValueField = "Code")] [Display(Name = "SNRule_Description", ResourceType = typeof(Resources.SYS.SNRule))] public string DocumentsTypeDescription { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Ninject; using St.Eg.Day2.M2.Ex7.After; using St.Eg.Day2.M2.Ex7.DIP.After; namespace St.Eg.Day2.M2.Ex8.NinjectRunner { public interface I_A { } public interface I_B { } public interface I_C { } public class Foo_A : I_A { public Foo_A(I_B b, I_C c) { } } public class Foo_B : I_B { public Foo_B() { } } public class Foo_C : I_C { public Foo_C() { } } public class Foo_C2 : I_C { public Foo_C2() { } } class Program { static void Main(string[] args) { //Example1(); Example2(); } private static void Example1() { // create a kernel var k = new StandardKernel(); k.Bind<I_A>().To<Foo_A>(); k.Bind<I_B>().To<Foo_B>(); k.Bind<I_C>().To<Foo_C2>(); var a = k.Get<I_A>(); } private static void Example2() { var k = new StandardKernel(); var di = new DirectoryInfo("c:\\"); k.Bind<IMessageStore>().To<MessageStore>(); k.Bind<IStoreReader>().To<SqlStore>(); k.Bind<IStoreWriter>().To<SqlStore>(); //k.Bind<IFileLocator>().ToMethod(context => fs); var ms = k.Get<IMessageStore>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SistemasNumeracion { class Program { static void Main(string[] args) { Console.Title = "Ejercicio 22"; NumeroBinario objBinario = "1001"; NumeroDecimal objDecimal = 9; string numeroBinario = (string)objBinario; double numeroDecimal = (double)objDecimal; Console.WriteLine("Suma en binario: {0}", objBinario + objDecimal); Console.WriteLine("Suma en decimal: {0}", objDecimal + objBinario); Console.WriteLine("Resta en binario: {0}", objBinario - objDecimal); Console.WriteLine("Resta en decimal: {0}", objDecimal - objBinario); if (objBinario == objDecimal) { Console.WriteLine("Los numeros {0} y {1} son iguales", (string)objBinario, (double)objDecimal); } else { Console.WriteLine("Los numeros {0} y {1} no son iguales", (string)objBinario, (double)objDecimal); } Console.ReadKey(); } } }
using ClosedXML.Excel; using Microsoft.AspNetCore.Mvc; using PowerDemandDataFeed.Model; using PowerDemandDataFeed.Processor.Interfaces; using System.Collections.Generic; using System.IO; namespace PowerDemandDataFeed.API.Controllers { [Route("api/[controller]")] [ApiController] public class PowerDemandController : ControllerBase { private IPowerDemandProcessor _powerDemandProcessor; public PowerDemandController(IPowerDemandProcessor powerDemandProcessor) { _powerDemandProcessor = powerDemandProcessor; } // GET: api/<PowerDemandController>/GetXML [HttpGet("GetXML")] [Produces("application/xml")] public IEnumerable<Item> GetXMLData() { return _powerDemandProcessor.GetXMLPowerDemand(); } /// <summary> /// Gets the XML data from site and displays them in Excel file. /// </summary> /// <returns>Excel file</returns> [HttpGet("excel")] public IActionResult DisplayInExcel() { // get XML data from the site var data = _powerDemandProcessor.GetXMLPowerDemand(); // create excel workbook using (var workbook = new XLWorkbook()) { var worksheet = workbook.Worksheets.Add("Demand"); var currentRow = 1; // table header worksheet.Cell(currentRow, 1).Value = "National Boundary Identifier"; worksheet.Cell(currentRow, 2).Value = "Settlement Date"; worksheet.Cell(currentRow, 3).Value = "Settlement Period"; worksheet.Cell(currentRow, 4).Value = "Record Type"; worksheet.Cell(currentRow, 5).Value = "Publishing Period Commencing Time"; worksheet.Cell(currentRow, 6).Value = "Demand"; worksheet.Cell(currentRow, 7).Value = "Active Flag"; // table body foreach (var item in data) { currentRow++; worksheet.Cell(currentRow, 1).Value = item.NationalBoundaryIdentifier; worksheet.Cell(currentRow, 2).Value = item.SettlementDate; worksheet.Cell(currentRow, 3).Value = item.SettlementPeriod; worksheet.Cell(currentRow, 4).Value = item.RecordType; worksheet.Cell(currentRow, 5).Value = item.PublishingPeriodCommencingTime; worksheet.Cell(currentRow, 6).Value = item.Demand; worksheet.Cell(currentRow, 7).Value = item.ActiveFlag; } // save and download Excel workbook using (var stream = new MemoryStream()) { workbook.SaveAs(stream); var content = stream.ToArray(); return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "PowerDemand.xlsx" ); } } } } }
using System; using System.Linq; using System.Reflection; using System.Text; using CalendarSystem; using Microsoft.VisualStudio.TestTools.UnitTesting; using Wintellect.PowerCollections; namespace CalendarSystemUnitTests { [TestClass] public class CalendarUnitTests { internal static object GetInstanceField(Type type, object instance, string fieldName) { BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; FieldInfo field = type.GetField(fieldName, bindFlags); return field.GetValue(instance); } //Command class-> covered 91.30% [TestMethod] public void ParsingCommandsValidFormatTest() { Command command = Command.Parse("AddEvent 2012-01-21T20:20:20 | party Viki | home"); Assert.AreEqual("AddEvent", command.CommandName); Assert.AreEqual(3, command.Arguments.Count()); } [TestMethod] public void ParsingCommandsInvalidDateFormatTest() { Command command = Command.Parse("AddEvent 2012-01-21T20 | party Viki | home"); Assert.AreEqual(null, command); } [TestMethod] public void ParsingCommandsNoDateTest() { Command command = Command.Parse("AddEvent | party Viki | home"); Assert.AreEqual(null, command); } [TestMethod] public void ParsingCommandsNoTitleTest() { Command command = Command.Parse("AddEvent 2012-01-21T20:20:20 | | home"); Assert.AreEqual(null, command); } [TestMethod] public void ParsingCommandsNoLocationTest() { Command command = Command.Parse("AddEvent 2012-01-21T20:20:20 | party Viki |"); Assert.AreNotEqual(null, command); } [TestMethod] public void ParsingCommandsInvalidFormatTest() { Command command = null; try { command = Command.Parse("AddEvent2012-01-21T20:20:20|partyViki|home"); } catch (IndexOutOfRangeException iore) { Assert.AreEqual(null, command); } } [TestMethod] public void ParsingCommandsEarlyDateTest() { Command command = Command.Parse("AddEvent 1012-01-21T20 | party Viki | home"); Assert.AreEqual(null, command); } [TestMethod] public void ParsingCommandsFutureDateTest() { Command command = Command.Parse("AddEvent 2112-01-21T20 | party Viki | home"); Assert.AreEqual(null, command); } [TestMethod] public void ParsingCommandsInvalidFormatPipeTest() { Command command = Command.Parse("AddEvent|2112-01-21T20 |party Vi|ki | home| \n "); Assert.AreEqual(null, command); } //Events manager -> covered 100% //AddEvent [TestMethod] public void AddEventValidFormatTest() { EventsManager manager = new EventsManager(); Event occasion = new Event("title", "location", DateTime.Now); manager.AddEvent(occasion); Console.WriteLine(); } [TestMethod] public void AddEventEmptyTitleTest() { EventsManager manager = new EventsManager(); Event occasion = new Event("", "location", DateTime.Now); manager.AddEvent(occasion); var testObj = (MultiDictionary<string, Event>)GetInstanceField(typeof(EventsManager), manager, "_eventsDictionary"); Assert.AreNotEqual(1, testObj.Count); } [TestMethod] public void AddEventTooLongTitleTest() { EventsManager manager = new EventsManager(); StringBuilder title = new StringBuilder(); for (int i = 0; i <= 200; i++) { title.Append("title"); } Event occasion = new Event(title.ToString(), "location", DateTime.Now); manager.AddEvent(occasion); var testObj = (MultiDictionary<string, Event>) GetInstanceField(typeof(EventsManager), manager, "_eventsDictionary"); Assert.AreNotEqual(1, testObj.Count); } [TestMethod] public void AddEventInvalidFormatTitleTest() { EventsManager manager = new EventsManager(); string title = " t| \n itle "; Event occasion = new Event(title.ToString(), "location", DateTime.Now); manager.AddEvent(occasion); var testObj = (MultiDictionary<string, Event>)GetInstanceField(typeof(EventsManager), manager, "_eventsDictionary"); Assert.AreNotEqual(1, testObj.Count); } [TestMethod] public void AddEventEmptyLocationTest() { EventsManager manager = new EventsManager(); Event occasion = new Event("title", "", DateTime.Now); manager.AddEvent(occasion); var testObj = (MultiDictionary<string, Event>)GetInstanceField(typeof(EventsManager), manager, "_eventsDictionary"); Assert.AreNotEqual(1, testObj.Count); } [TestMethod] public void AddEventTooLongLocationTest() { EventsManager manager = new EventsManager(); StringBuilder location = new StringBuilder(); for (int i = 0; i <= 150; i++) { location.Append("location"); } Event occasion = new Event("title", location.ToString(), DateTime.Now); manager.AddEvent(occasion); var testObj = (MultiDictionary<string, Event>)GetInstanceField(typeof(EventsManager), manager, "_eventsDictionary"); Assert.AreNotEqual(1, testObj.Count); } [TestMethod] public void AddEventInvalidFormatLocationTest() { EventsManager manager = new EventsManager(); string location = " l| \n ocation "; Event occasion = new Event("title", location, DateTime.Now); manager.AddEvent(occasion); var testObj = (MultiDictionary<string, Event>)GetInstanceField(typeof(EventsManager), manager, "_eventsDictionary"); Assert.AreNotEqual(1, testObj.Count); } //DeleteEvent [TestMethod] public void DeleteValidEventTest() { EventsManager manager = new EventsManager(); //reflection test object Event occasion = new Event("title", "location", DateTime.Now); MultiDictionary<string, Event> dummyDictionary = new MultiDictionary<string,Event>(true); dummyDictionary.Add("title", occasion); FieldInfo fieldInfo = manager.GetType().GetField("_eventsDictionary", BindingFlags.Instance | BindingFlags.NonPublic); fieldInfo.SetValue(manager, dummyDictionary); int result = manager.DeleteEventsByTitle("title"); Assert.AreEqual(1, result); } [TestMethod] public void DeleteNotExistingEventTest() { EventsManager manager = new EventsManager(); int result = manager.DeleteEventsByTitle("title"); Assert.AreEqual(0, result); } //ListEvents [TestMethod] public void ListValidEventsTest() { EventsManager manager = new EventsManager(); //reflection test object Event occasion = new Event("title", "location", DateTime.Now.AddDays(1)); Event occasion1 = new Event("title1", "location1", DateTime.Now.AddDays(2)); Event occasion2 = new Event("title2", "location2", DateTime.Now.AddDays(3)); Event occasion3 = new Event("title3", "location3", DateTime.Now.AddDays(4)); OrderedMultiDictionary<DateTime, Event> dummyOrderedDictionary = new OrderedMultiDictionary<DateTime, Event>(true); dummyOrderedDictionary.Add(DateTime.Now.AddDays(1), occasion); dummyOrderedDictionary.Add(DateTime.Now.AddDays(2), occasion1); dummyOrderedDictionary.Add(DateTime.Now.AddDays(3), occasion2); dummyOrderedDictionary.Add(DateTime.Now.AddDays(4), occasion3); FieldInfo fieldInfo = manager.GetType().GetField("_orderedEvents", BindingFlags.Instance | BindingFlags.NonPublic); fieldInfo.SetValue(manager, dummyOrderedDictionary); var result = manager.ListEvents(DateTime.Now, 4); Assert.AreEqual(4, result.Count()); } [TestMethod] public void ListEventsZeroCountTest() { EventsManager manager = new EventsManager(); //reflection test object Event occasion = new Event("title", "location", DateTime.Now.AddDays(1)); Event occasion1 = new Event("title1", "location1", DateTime.Now.AddDays(2)); Event occasion2 = new Event("title2", "location2", DateTime.Now.AddDays(3)); Event occasion3 = new Event("title3", "location3", DateTime.Now.AddDays(4)); OrderedMultiDictionary<DateTime, Event> dummyOrderedDictionary = new OrderedMultiDictionary<DateTime, Event>(true); dummyOrderedDictionary.Add(DateTime.Now.AddDays(1), occasion); dummyOrderedDictionary.Add(DateTime.Now.AddDays(2), occasion1); dummyOrderedDictionary.Add(DateTime.Now.AddDays(3), occasion2); dummyOrderedDictionary.Add(DateTime.Now.AddDays(4), occasion3); FieldInfo fieldInfo = manager.GetType().GetField("_orderedEvents", BindingFlags.Instance | BindingFlags.NonPublic); fieldInfo.SetValue(manager, dummyOrderedDictionary); var result = manager.ListEvents(DateTime.Now, 0); Assert.AreEqual(0, result.Count()); } [TestMethod] public void ListEventsNegativeCountTest() { EventsManager manager = new EventsManager(); //reflection test object Event occasion = new Event("title", "location", DateTime.Now.AddDays(1)); Event occasion1 = new Event("title1", "location1", DateTime.Now.AddDays(2)); Event occasion2 = new Event("title2", "location2", DateTime.Now.AddDays(3)); Event occasion3 = new Event("title3", "location3", DateTime.Now.AddDays(4)); OrderedMultiDictionary<DateTime, Event> dummyOrderedDictionary = new OrderedMultiDictionary<DateTime, Event>(true); dummyOrderedDictionary.Add(DateTime.Now.AddDays(1), occasion); dummyOrderedDictionary.Add(DateTime.Now.AddDays(2), occasion1); dummyOrderedDictionary.Add(DateTime.Now.AddDays(3), occasion2); dummyOrderedDictionary.Add(DateTime.Now.AddDays(4), occasion3); FieldInfo fieldInfo = manager.GetType().GetField("_orderedEvents", BindingFlags.Instance | BindingFlags.NonPublic); fieldInfo.SetValue(manager, dummyOrderedDictionary); var result = manager.ListEvents(DateTime.Now, -1); Assert.AreEqual(0, result.Count()); } [TestMethod] public void ListEventsTooBigCountTest() { EventsManager manager = new EventsManager(); //reflection test object Event occasion = null; OrderedMultiDictionary<DateTime, Event> dummyOrderedDictionary = new OrderedMultiDictionary<DateTime, Event>(true); for (int i = 0; i < 105; i++) { occasion = new Event("title" + i, "location" + i, DateTime.Now.AddHours(i)); dummyOrderedDictionary.Add(DateTime.Now.AddHours(i), occasion); occasion = null; } FieldInfo fieldInfo = manager.GetType().GetField("_orderedEvents", BindingFlags.Instance | BindingFlags.NonPublic); fieldInfo.SetValue(manager, dummyOrderedDictionary); var result = manager.ListEvents(DateTime.Now, 101); Assert.AreEqual(0, result.Count()); } } }
using System; using SpringHeroBank.controller; using SpringHeroBank.entity; namespace SpringHeroBank.view { public class MainView { public static Account loggedInAccount; public static void GenerateMenu() { AccountController controller = new AccountController(); while (true) { Console.WriteLine("---------WELCOME TO SPRING HERO BANK---------"); Console.WriteLine("1. Register for free."); Console.WriteLine("2. Login."); Console.WriteLine("3. Exit."); Console.WriteLine("---------------------------------------------"); Console.WriteLine("Please enter your choice (1|2|3): "); var choice = GetNumber(); switch (choice) { case 1: controller.Register(); break; case 2: controller.DoLogin(); break; case 3: Console.WriteLine("See you later."); Environment.Exit(1); break; default: Console.WriteLine("Invalid choice."); break; } } } private static int GetNumber() { var choice = 0; while (true) { try { var strChoice = Console.ReadLine(); choice = Int32.Parse(strChoice); break; } catch (FormatException e) { Console.WriteLine("Please enter a number."); } } return choice; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CS295NTermProject.Models { public interface ITag { string Tag { get; set; } } }
using Nac.Common.Fuzzy; 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 System.Globalization; using Accord.Fuzzy; using Accord; using Nac.Fuzzy.Common; using Nac.Common.Control; namespace Nac.Wpf.Fuzzy { /// <summary> /// Interaction logic for FuzzySetEditor.xaml /// </summary> public partial class NacWpfFuzzySetEditor : Window { private const int cChartPoints = 100; public NacWpfFuzzySetEditor() { InitializeComponent(); } public NacWpfFuzzySetEditor(HashSet<Common.Fuzzy.NacFuzzySet> sets) { InitializeComponent(); HashSet<Common.Fuzzy.NacFuzzySet> edit = sets == null ? new HashSet<Common.Fuzzy.NacFuzzySet>() : new HashSet<Common.Fuzzy.NacFuzzySet>(sets); DataContext = new NacWpfFuzzySetEditorViewModel(edit); } public HashSet<Common.Fuzzy.NacFuzzySet> Return { get { return new HashSet<Common.Fuzzy.NacFuzzySet>((DataContext as NacWpfFuzzySetEditorViewModel).Select(fs => fs.Base)); } } private void addButton_Click(object sender, RoutedEventArgs e) { var newSet = new NacWpfFuzzySet(); var viewModel = DataContext as NacWpfFuzzySetEditorViewModel; viewModel.Add(newSet); fsListbox.SelectedItem = newSet; nameTextBox.Focus(); nameTextBox.SelectAll(); } private void remButton_Click(object sender, RoutedEventArgs e) { if (fsListbox.SelectedIndex < 0) return; var viewModel = DataContext as NacWpfFuzzySetEditorViewModel; viewModel.RemoveAt(fsListbox.SelectedIndex); } private void textBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) RefreshListBox(); } private void edgeRadio_Click(object sender, RoutedEventArgs e) { RefreshListBox(); } private void RefreshListBox() { fsListbox.Items.Refresh(); Keyboard.Focus(fsListbox); } private void RefreshChart() { float minX = float.MaxValue, maxX = float.MinValue; fsChart.RemoveAllDataSeries(); var viewModel = DataContext as NacWpfFuzzySetEditorViewModel; var fuzzySets = viewModel.Select(fs => fs.Base.GetFuzzySet()); minX = fuzzySets.Min(fs => fs.LeftLimit); maxX = fuzzySets.Max(fs => fs.RightLimit); foreach (var fuzzySet in fuzzySets) { fsChart.AddDataSeries(fuzzySet.Name, System.Drawing.Color.Red, Accord.Controls.Chart.SeriesType.Line, fuzzySet.Name == SelectedSet ? 5 : 2); fsChart.UpdateDataSeries(fuzzySet.Name, CalcSeries(fuzzySet, minX, maxX)); } fsChart.RangeX = new Range(minX, maxX); fsChart.RangeY = new Range(0f, 1f); } private double[,] CalcSeries(FuzzySet fuzzySet, float minX, float maxX) { double[,] ret = new double[cChartPoints + 1, 2]; double xGap = (maxX - minX) / cChartPoints; for (int i = 0; i <= cChartPoints; i++) { double x = ret[i, 0] = minX + xGap * i; ret[i, 1] = fuzzySet.GetMembership((float)x); } return ret; } private void Window_Loaded(object sender, RoutedEventArgs e) { var viewModel = DataContext as NacWpfFuzzySetEditorViewModel; viewModel.CollectionChanged += ViewModel_CollectionChanged; } private void ViewModel_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { bool refresh = false; if (e.NewItems?.Count > 0) { foreach(NacWpfFuzzySet fuzzySet in e.NewItems) fuzzySet.PropertyChanged += FuzzySet_PropertyChanged; refresh = true; } if (e.OldItems?.Count > 0) { foreach (NacWpfFuzzySet fuzzySet in e.OldItems) fuzzySet.PropertyChanged -= FuzzySet_PropertyChanged; refresh = true; } if (refresh) RefreshChart(); } private void FuzzySet_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { RefreshChart(); } private string SelectedSet { get { if (fsListbox.SelectedItems.Count < 1) return null; var fuzzySet = fsListbox.SelectedItems[0] as NacWpfFuzzySet; return fuzzySet.Name; } } private void fsListbox_SelectionChanged(object sender, SelectionChangedEventArgs e) { RefreshChart(); } private void OK_Click(object sender, RoutedEventArgs e) { DialogResult = true; Close(); } private void Cancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; Close(); } } [ValueConversion(typeof(int), typeof(bool))] public class FuzzySetEdgeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var ival = (int)value; var ipar = int.Parse(parameter as string); return ival == ipar; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return int.Parse(parameter as string); ; } } }
using gView.Framework.system; using System.Collections; using System.Collections.Generic; namespace gView.Framework.Data { public class DisplayFilterCollection : List<DisplayFilter> { public static DisplayFilterCollection FromJSON(string json) { try { if (json.StartsWith("[")) { json = "{ \"filters\":" + json + "}"; } json = json.Replace("\r", "").Replace("\n", "").Replace("\t", ""); Hashtable f = (Hashtable)JSON.JsonDecode(json); DisplayFilterCollection filterCollection = new DisplayFilterCollection(); ArrayList filters = (ArrayList)f["filters"]; for (int i = 0; i < filters.Count; i++) { Hashtable filter = (Hashtable)filters[i]; DisplayFilter displayFilter = new DisplayFilter(); if (filter["sql"] != null) { displayFilter.Filter = (string)filter["sql"]; } if (filter["color"] != null) { displayFilter.Color = ColorConverter2.ConvertFrom((string)filter["color"]); } if (filter["penwidth"] is double) { displayFilter.PenWidth = (float)((double)filter["penwidth"]); } filterCollection.Add(displayFilter); } return filterCollection; } catch { } return null; } } }
using Microsoft.IdentityModel.Clients.ActiveDirectory; using System; using System.Threading.Tasks; namespace gView.Framework.Azure.AD { public class Authentication { public Authentication(string clientId, string clientSecret) { this.ClientId = clientId; this.ClientSecret = clientSecret; } private string ClientId { get; set; } private string ClientSecret { get; set; } public async Task<string> GetToken(string authority, string resource, string scope) { var authContext = new AuthenticationContext(authority); ClientCredential clientCred = new ClientCredential(this.ClientId, this.ClientSecret); AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return result.AccessToken; } } }
using System.Collections.Generic; using SuperMario.Entities; namespace SuperMario.Collision { public static class MasterCollider { static List<Entity> collidingEntitesToAdd = new List<Entity>(); public static IList<Entity> Colliders { get; private set; } = new List<Entity>(); public static void RunCollision() { RectangleCollisions collisions; foreach(Entity collider in Colliders) { if (collider is MovingEntity movingEntity) movingEntity.Grounded = false; foreach (Entity entity in EntityStorage.Instance.EntityList) { collisions = RectangleCollider.Collide(collider.BoundingBox, entity.BoundingBox); if (collisions.Collisions.Count > 0) collider.Collide(entity, collisions); } } ((List<Entity>)Colliders).AddRange(collidingEntitesToAdd); collidingEntitesToAdd.Clear(); EntityStorage.Instance.AddQueuedItems(); } public static void AddCollidingEntity(Entity entity) { collidingEntitesToAdd.Add(entity); } public static void Reset() { Colliders = new List<Entity>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Xlns.BusBook.Core.Model; using Xlns.BusBook.Core.Repository; using Xlns.BusBook.Core; using Xlns.BusBook.UI.Web.Models; using Xlns.BusBook.Core.Mailer; using Xlns.BusBook.Core.Enums; using Xlns.BusBook.UI.Web.Controllers.Helper; namespace Xlns.BusBook.UI.Web.Controllers { public class ViaggioController : Controller { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private ViaggioRepository vr = new ViaggioRepository(); private ViaggioManager vm = new ViaggioManager(); public ActionResult ListPartial() { var viaggi = vr.GetListaViaggiVisibili(Session.getLoggedAgenzia()); ViewBag.IsFullPage = false; return PartialView("List", viaggi); } [ChildActionOnly] public ActionResult TappaEdit(Tappa tappa) { return PartialView(tappa); } [ChildActionOnly] public ActionResult ListOfViaggioTiledDetail(List<Viaggio> viaggi) { return PartialView(viaggi); } [ChildActionOnly] public ActionResult ViaggioTiledDetail(Viaggio viaggio) { return PartialView(viaggio); } public ActionResult Detail(int id, string from = null, int idFlyer = 0) { var viaggio = vr.GetById(id); ViewBag.From = from; ViewBag.FlyerId = idFlyer; var loggedUser = Session.getLoggedUtente(); var pr = new PartecipazioneRepository(); bool hasPartecipated; if (viaggio.Agenzia != null) hasPartecipated = pr.HasParticipated(loggedUser.Id, id) || (viaggio.Agenzia.Id == loggedUser.Agenzia.Id); else hasPartecipated = pr.HasParticipated(loggedUser.Id, id); ViewBag.HasPartecipated = hasPartecipated; return View(viaggio); } public ActionResult Create() { return RedirectToAction("Edit", new { id = 0 }); } public ActionResult Edit(int id) { Viaggio viaggio = null; if (id == 0) viaggio = vm.CreaNuovoViaggio(); else viaggio = vr.GetById(id); return View(viaggio); } [HttpPost] public ActionResult Save(Viaggio viaggio) { if (ModelState.IsValid) { Viaggio oldViaggio = vr.GetById(viaggio.Id); if (oldViaggio != null) { viaggio.Tappe = oldViaggio.Tappe; viaggio.Depliant = oldViaggio.Depliant; viaggio.PromoImage = oldViaggio.PromoImage; } viaggio.Agenzia = Session.getLoggedAgenzia(); // Gestione depliant e immagine promozionale if (Request.Files != null) { foreach (string fileName in Request.Files) { HttpPostedFileBase file = Request.Files[fileName] as HttpPostedFileBase; if (file.ContentLength == 0) continue; if (vm.isValidDepliantMimeType(file.FileName)) { logger.Info("Caricamento depliant per il viaggio {0}", viaggio); Int32 length = file.ContentLength; byte[] rawFile = new byte[length]; file.InputStream.Read(rawFile, 0, length); var allegato = new AllegatoViaggio() { RawFile = rawFile, NomeFile = file.FileName, Viaggio = viaggio }; viaggio.Depliant = allegato; } if (vm.isValidImageMimeType(file.FileName)) { logger.Info("Caricamento immagine promozionale per il viaggio {0}", viaggio); Int32 length = file.ContentLength; byte[] rawFile = new byte[length]; file.InputStream.Read(rawFile, 0, length); var allegato = new AllegatoViaggio() { RawFile = rawFile, NomeFile = file.FileName, Viaggio = viaggio }; viaggio.PromoImage = allegato; } } } vm.Save(viaggio); if (viaggio.Tappe != null && viaggio.Tappe.Count > 1 && viaggio.Tappe.SingleOrDefault(t => t.Tipo == TipoTappa.DESTINAZIONE) != null) { logger.Debug("Il percorso del viaggio è stato definito, per cui lo si redirige alla pagina di dettaglio per verifica"); return RedirectToAction("Detail", new { id = viaggio.Id }); } } return RedirectToAction("Edit", new { id = viaggio.Id }); } public ActionResult EditTappeViaggio(int idViaggio) { var viaggio = vr.GetById(idViaggio); return PartialView(viaggio); } public ActionResult CreateTappa(int tipo, int idViaggio) { var viaggio = vr.GetById(idViaggio); var nuovaTappa = new Tappa() { Tipo = (TipoTappa)tipo, Viaggio = viaggio, Ordinamento = vm.CalcolaOrdinamentoPerNuovaTappa(viaggio) }; return PartialView("EditTappa", nuovaTappa); } public ActionResult EditTappa(int id) { var tappa = vr.GetTappaById(id); return PartialView(tappa); } [HttpPost] public ActionResult SaveTappa(Tappa tappa) { if (tappa.Viaggio != null && tappa.Viaggio.Id != 0) { tappa.Viaggio = vr.GetById(tappa.Viaggio.Id); } if (!ModelState.IsValid) { vr.Save(tappa); return RedirectToAction("EditTappeViaggio", new { idViaggio = tappa.Viaggio.Id }); } else { string msg = "Impossibile salvare la tappa modificata o creata"; logger.Error(msg); throw new Exception(msg); } } [HttpPost] public void DeleteTappaAjax(int id) { try { vm.DeleteTappa(id); } catch (Exception ex) { string msg = String.Format("Errore durante l'eliminazione della tappa con id={0}", id); logger.ErrorException(msg, ex); throw new Exception(msg); } } [HttpPost] public ActionResult RichiestaPartecipazione(int idViaggio) { var loggedUser = Session.getLoggedUtente(); Agenzia agenzia = null; if (AuthenticationHelper.isLogged(Session)) { var viaggio = vr.GetById(idViaggio); //registro che questo utente ha visualizzato i dati vm.RegistraPartecipazione(viaggio, loggedUser); var mr = new MessaggioRepository(); Messaggio messaggio = new Messaggio(); messaggio.Mittente = loggedUser; messaggio.Destinatario = viaggio.Agenzia.Utenti.FirstOrDefault(); var testoMessaggio = ConfigurationManager.Configurator.Istance.messagesPartecipaMessage .Replace("{agenzia}", loggedUser.Agenzia.Nome) .Replace("{viaggio}", viaggio.Nome) .Replace("{descrizioneViaggio}", viaggio.Descrizione); messaggio.Testo = testoMessaggio; messaggio.Stato = (int)MessaggioEnumerator.NonLetto; messaggio.DataInvio = DateTime.Now; mr.Save(messaggio); MailHelper mh = new MailHelper(); //mh.SendMail(viaggio.Agenzia.Email, ""); agenzia = viaggio.Agenzia; } return PartialView("RichiestaPartecipazione", agenzia); } [HttpPost] public ActionResult RimuoviPartecipazione(int idViaggio) { var loggedUser = Session.getLoggedUtente(); Agenzia agenzia = null; if (AuthenticationHelper.isLogged(Session)) { var viaggio = vr.GetById(idViaggio); var pr = new PartecipazioneRepository(); var partecipazione = pr.GetPartecipazioneUtente(loggedUser.Id, idViaggio); if (partecipazione != null) pr.DeletePartecipazione(partecipazione); var mr = new MessaggioRepository(); Messaggio messaggio = new Messaggio(); messaggio.Mittente = loggedUser; messaggio.Destinatario = viaggio.Agenzia.Utenti.FirstOrDefault(); var testoMessaggio = ConfigurationManager.Configurator.Istance.messagesRimuoviMessage .Replace("{agenzia}", loggedUser.Agenzia.Nome) .Replace("{viaggio}", viaggio.Nome) .Replace("{descrizioneViaggio}", viaggio.Descrizione); messaggio.Testo = testoMessaggio; messaggio.Stato = (int)MessaggioEnumerator.NonLetto; messaggio.DataInvio = DateTime.Now; mr.Save(messaggio); MailHelper mh = new MailHelper(); //mh.SendMail(viaggio.Agenzia.Email, ""); agenzia = viaggio.Agenzia; } return PartialView("RichiestaPartecipazione", agenzia); } [HttpPost] public ActionResult Pubblica(int idViaggio) { var viaggio = vr.GetById(idViaggio); if (Session.getLoggedAgenzia() != null && viaggio.Agenzia.Id == Session.getLoggedAgenzia().Id) { var vm = new ViaggioManager(); try { vm.Pubblica(viaggio); return null; } catch (NonPubblicabileException ex) { return new HttpStatusCodeResult(403, ex.Message); } } else { string msg = "Impossibile pubblicare un viaggio di un'azienda che non sia la propria"; logger.Warn(msg); return new HttpStatusCodeResult(403, msg); } } [ChildActionOnly] public ActionResult ListaPartecipanti(int idViaggio) { var pr = new PartecipazioneRepository(); var partecipazioni = pr.GetPartecipazioniAlViaggio(idViaggio); return PartialView(partecipazioni); } [HttpPost] public ActionResult ReorderTappe(int[] reorderedIds, int idViaggio) { var viaggio = vr.GetById(idViaggio); int order = 1; foreach (var id in reorderedIds) { viaggio.Tappe.Single(t => t.Id == id).Ordinamento = order; order++; } vr.Save(viaggio); return new HttpStatusCodeResult(200); } [HttpPost] public ActionResult Search(ViaggioSearchView searchParams) { var viaggiFound = vm.Search(ViaggioHelper.getViaggioSearchParams(searchParams), Session.getLoggedAgenzia()); if (searchParams.isFlyersSearch) { var viaggiSelezionabili = FlyerHelper.getViaggiSelezionabili(Session.getFlyerInModifica(), viaggiFound); return Select(viaggiSelezionabili); } else { return PartialView("ListOfViaggioTiledDetail", viaggiFound); } } public ActionResult Search(String idDivToUpdate, bool onlyPubblicati, bool isFlyerSearch) { return PartialView(new ViaggioSearchView() { idDivToUpdate = idDivToUpdate, onlyPubblicati = onlyPubblicati, isFlyersSearch = isFlyerSearch }); } public ActionResult Select(List<ViaggioSelectView> viaggi, string from = null, int idFlyer = 0) { ViewBag.From = from; ViewBag.FlyerId = idFlyer; if (viaggi == null) { //con questa ricerca li becco tutti List<Viaggio> viaggiFound = vm.Search(new ViaggioSearch() { onlyPubblicati = true }, Session.getLoggedAgenzia()); viaggi = FlyerHelper.getViaggiSelezionabili(Session.getFlyerInModifica(), viaggiFound); } return PartialView("Select", viaggi); } public ActionResult SearchTappa(int tipo) { var tappaSearch = new Tappa() { Tipo = (TipoTappa)tipo, }; return PartialView("SearchTappa", tappaSearch); } public ActionResult ShowSelected(int idFlyer, bool isDetailExternal) { return Select(FlyerHelper.getViaggiSelezionati(idFlyer, isDetailExternal), "flyer", idFlyer); } } }
namespace TagParsing.Tokens { public class NewlineToken : ParseToken { public new string ToString() { return "Newline"; } public override string Render() { return "\n"; } } }
using System; using System.Text.Json; using System.Text.Json.Serialization; namespace NStandard.Json.Converters { public class NetSingleConverter : JsonConverter<float> { public override float Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var str = reader.GetString(); return str switch { "Infinity" => float.PositiveInfinity, "-Infinity" => float.NegativeInfinity, _ => float.NaN, }; } return reader.GetSingle(); } public override void Write(Utf8JsonWriter writer, float value, JsonSerializerOptions options) { if (float.IsNaN(value)) writer.WriteStringValue("NaN"); else if (float.IsPositiveInfinity(value)) writer.WriteStringValue("Infinity"); else if (float.IsNegativeInfinity(value)) writer.WriteStringValue("-Infinity"); else writer.WriteNumberValue(value); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display; using OrchardCore.DisplayManagement.ModelBinding; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StockAndShare.OrchardCoreDemo.Controllers { [ApiController] class ApiStocksController : Controller { private readonly ISession _session; private readonly IContentManager _contentManager; private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly IUpdateModelAccessor _updateModelAccessor; public ApiStocksController(ISession session, IContentManager contentManager, IContentItemDisplayManager contentItemDisplayManager, IUpdateModelAccessor updateModelAccessor) { _session = session; _contentManager = contentManager; _contentItemDisplayManager = contentItemDisplayManager; _updateModelAccessor = updateModelAccessor; } [HttpGet, ActionName("Get")] public async Task<IActionResult> Get() { return Ok("HEy"); } } }
using System; using System.Collections; using System.IO; namespace Uberware.Study { public class MatchingSheet { // Major = major file format changes; minor = still loadable format if > current public static readonly Version SheetVersion = new Version(1, 0); public string Title; public string Author; public string Description; public string Group; public string [] Terms; public string [] Definitions; public string FileName; public MatchingSheet () : this("", "", "", "", new string [0], new string [0], "") {} public MatchingSheet (string Title, string [] Terms, string [] Definitions) : this(Title, "", "", "", Terms, Definitions, "") {} public MatchingSheet (string Title, string Author, string [] Terms, string [] Definitions) : this(Title, Author, "", "", Terms, Definitions, "") {} public MatchingSheet (string Title, string Author, string Description, string [] Terms, string [] Definitions) : this(Title, Author, Description, "", Terms, Definitions, "") {} public MatchingSheet (string Title, string Author, string Description, string Group, string [] Terms, string [] Definitions) : this(Title, Author, Description, Group, Terms, Definitions, "") {} private MatchingSheet (string Title, string Author, string Description, string Group, string [] Terms, string [] Definitions, string FileName) { this.Title = Title; this.Author = Author; this.Description = Description; this.Group = Group; this.Terms = Terms; this.Definitions = Definitions; this.FileName = FileName; } public int TermCount { get { return Terms.Length; } } public override string ToString () { StringWriter str = new StringWriter(); bool b = Save(str); str.Close(); if (!b) return ""; return str.GetStringBuilder().ToString(); } public bool Save () { bool b; FileStream fs = File.Open(FileName, FileMode.Create, FileAccess.Write, FileShare.Read); if (fs == null) return false; b = Save(fs); fs.Close(); return b; } public bool Save (Stream s) { return Save(new StreamWriter(s)); } public bool Save (TextWriter file) { // File information if (Title != "") file.WriteLine("@Title: " + Title); if (Author != "") file.WriteLine("@Author: " + Author); if (Description != "") file.WriteLine("@Description: " + EscapeString(Description)); if (Group != "") file.WriteLine("@Group: " + Group); if ((TermCount > 0) && ((Title != "") || (Author != "") || (Description != "") || (Group != ""))) { file.WriteLine(); file.WriteLine(); } // Study sheet data if (TermCount > 0) file.WriteLine("# Terms and Definitions"); for (int i = 0; i < TermCount; i++) { file.Write(Terms[i]); file.Write(": "); file.WriteLine(EscapeString(Definitions[i])); } file.Flush(); return true; } public static MatchingSheet FromString (string text, string FileName) { return FromFile(new StringReader(text), FileName); } public static MatchingSheet FromString (string text) { return FromString(text, ""); } public static MatchingSheet FromFile (string FileName) { StreamReader file; try { file = File.OpenText(FileName); } catch (FileNotFoundException) { return null; } MatchingSheet sheet = FromFile(file, FileName); file.Close(); return sheet; } public static MatchingSheet FromFile (TextReader file) { return FromFile(file, ""); } public static MatchingSheet FromFile (TextReader file, string FileName) { string title = "", author = "", desc = "", group = ""; ArrayList terms = new ArrayList(); ArrayList defs = new ArrayList(); string line; string name, val; while (file.Peek() != -1) { int n, n2; line = file.ReadLine().Trim(); if (line.Length == 0) continue; n = line.IndexOf('='); n2 = line.IndexOf(':'); if (((n2 < n) && (n2 != -1)) || (n == -1)) n = n2; if (n == -1) continue; name = line.Substring(0, n).Trim(); val = line.Substring(n+1).Trim(); if ((name.Length == 0) || (val.Length == 0)) continue; // Check for comment line if (line[0] == '#') continue; if (line[0] == '@') { name = name.Substring(1); switch (name.ToUpper()) { case "TITLE": title = val; break; case "AUTHOR": author = val; break; case "DESCRIPTION": desc = DescapeString(val); break; case "GROUP": group = val; break; default: continue; } } else { terms.Add(name); defs.Add(DescapeString(val)); } } return new MatchingSheet(title, author, desc, group, (string [])terms.ToArray(typeof(string)), (string [])defs.ToArray(typeof(string)), FileName); } public static string Normalize (string text) { StringReader reader = new StringReader(text); MatchingSheet sheet = FromFile(reader); reader.Close(); StringWriter writer = new StringWriter(); writer.NewLine = GetNewLine(text, writer.NewLine); bool b = sheet.Save(writer); writer.Close(); if (!b) return ""; return writer.GetStringBuilder().ToString(); } public static MatchingSheet Validate (MatchingSheet sheet) { StringWriter writer = new StringWriter(); bool b = sheet.Save(writer); writer.Close(); if (!b) return sheet; StringReader reader = new StringReader(writer.GetStringBuilder().ToString()); MatchingSheet result = FromFile(reader); reader.Close(); return result; } private static string GetNewLine (string s) { return GetNewLine(s, ""); } private static string GetNewLine (string s, string Default) { int n1, n2; n1 = s.IndexOf("\r\n"); n2 = s.IndexOf("\n\r"); if ((n1 != -1) || (n2 != -1)) { if (((n1 < n2) && (n1 != -1)) || (n2 == -1)) return "\r\n"; else return "\n\r"; } else { if (s.IndexOf("\n") != -1) return "\n"; if (s.IndexOf("\r") != -1) return "\r"; } return Default; } public static bool TextEquals (string a, string b) { string newline1 = GetNewLine(a); if ((newline1 != "") && (newline1 != "\n")) a = a.Replace(newline1, "\n"); while ((a.Length > 0) && (a.EndsWith("\0"))) a = a.Substring(0, (a.Length-1)); string newline2 = GetNewLine(b); if ((newline2 != "") && (newline2 != "\n")) b = b.Replace(newline2, "\n"); while ((b.Length > 0) && (b.EndsWith("\0"))) b = b.Substring(0, (b.Length-1)); return string.Equals(a, b); } public static string JoinTerms (string [] terms) { string res = ""; foreach (string term in terms) { string s = term.Trim(); if (s == "") continue; if (res != "") res += ", "; res += s.Replace(@"\\", @"\").Replace(",", @"\,"); } return res; } public static string [] SplitTerms (string terms) { ArrayList res = new ArrayList(); string temp = ""; char ch; for (int i = 0; i < terms.Length; i++) { ch = terms[i]; if (ch == '\\') { i++; if (i >= terms.Length) { temp += ch; break; } char ch2 = terms[i]; if (ch2 == '\\') temp += ch2; else if (ch2 == ',') temp += ch2; else temp += (ch.ToString() + ch2.ToString()); // !!!!! Error } else if (ch == ',') { temp = temp.Trim(); if (temp != "") res.Add(temp); temp = ""; } else temp += ch; } // Add remaining temp = temp.Trim(); if (temp != "") res.Add(temp); return (string [])res.ToArray(typeof(string)); } public static string EscapeString (string s) { string res = s; string newline = GetNewLine(res); if ((newline != "") && (newline != "\n")) res = res.Replace(newline, "\n"); if (res.EndsWith("\n")) res = res.Remove((res.Length - 1), 1); return res.Replace(@"\\", @"\").Replace("\n", @"\n"); } public static string DescapeString (string s) { string res = s.Replace(@"\n", "\n").Replace(@"\\", @"\"); return (res + "\n"); } } }
using ServerLibrary; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TcpServerLibrary; namespace ClientGui { public partial class LoginWindow : Form { TcpClient client; NetworkStream stream; public LoginWindow(TcpClient client) { InitializeComponent(); stream = client.GetStream(); this.client = client; } //register button private void registerButton_Click(object sender, EventArgs e) { Hide(); RegisterWindow registerWindow = new RegisterWindow(client, 2); registerWindow.ShowDialog(); } //login button private void loginButton_Click(object sender, EventArgs e) { ClientComunicator comunicator = new ClientComunicator(); comunicator.SendMessage(stream, "1"); if (textBoxName.Text.Length != 0 || textBoxPass.Text.Length != 0) { String credentials = textBoxName.Text + ";" + textBoxPass.Text; comunicator.SendMessage(stream, credentials); var response = comunicator.ReadResponse(stream); if (response.Equals("DEC")) { responseLabel.ForeColor = Color.Red; responseLabel.Text = "Invalid Credentials"; } else { response = comunicator.ReadResponse(stream); if (response.Equals("ADM")) { Hide(); InteractionAdminWindow adminWindow = new InteractionAdminWindow(client, 0); adminWindow.ShowDialog(); } else { Hide(); InteractionWindow userWindow = new InteractionWindow(client, 1); userWindow.ShowDialog(); } } } else { String credentials = "a1z ;a1z"; comunicator.SendMessage(stream, credentials); responseLabel.ForeColor = Color.Red; responseLabel.Text = "Invalid Credentials"; } } } }
namespace Common.Utilities { using System.Collections.Generic; using System.IO; public static class HashContent { private static readonly IDictionary<string, string> FileByName = new Dictionary<string, string> { { Constants.AdminGamesHtml, $"{Constants.SiteContentPath}{Constants.AdminGamesHtml}" }, { Constants.AdminGameCellHtml, $"{Constants.SiteContentPath}{Constants.AdminGameCellHtml}" }, { Constants.DeleteGameHtml, $"{Constants.SiteContentPath}{Constants.DeleteGameHtml}" }, { Constants.AddGameHtml, $"{Constants.SiteContentPath}{Constants.AddGameHtml}" }, { Constants.EditGameHtml, $"{Constants.SiteContentPath}{Constants.EditGameHtml}" }, { Constants.FooterHtml, $"{Constants.SiteContentPath}{Constants.FooterHtml}" }, { Constants.GameDetailsHtml, $"{Constants.SiteContentPath}{Constants.GameDetailsHtml}" }, { Constants.GameDetailsEndHtml, $"{Constants.SiteContentPath}{Constants.GameDetailsEndHtml}" }, { Constants.GameDetailsFormHtml, $"{Constants.SiteContentPath}{Constants.GameDetailsFormHtml}" }, { Constants.HeaderHtml, $"{Constants.SiteContentPath}{Constants.HeaderHtml}" }, { Constants.HomeHtml, $"{Constants.SiteContentPath}{Constants.HomeHtml}" }, { Constants.HomeStartHtml, $"{Constants.SiteContentPath}{Constants.HomeStartHtml}" }, { Constants.HomeStartLinksHtml, $"{Constants.SiteContentPath}{Constants.HomeStartLinksHtml}" }, { Constants.HomeEndHtml, $"{Constants.SiteContentPath}{Constants.HomeEndHtml}" }, { Constants.HomeGameCellHtml, $"{Constants.SiteContentPath}{Constants.HomeGameCellHtml}" }, { Constants.LoginHtml, $"{Constants.SiteContentPath}{Constants.LoginHtml}" }, { Constants.NavLoggedHtml, $"{Constants.SiteContentPath}{Constants.NavLoggedHtml}" }, { Constants.NavLoggedAdminHtml, $"{Constants.SiteContentPath}{Constants.NavLoggedAdminHtml}" }, { Constants.NavNotLoggedHtml, $"{Constants.SiteContentPath}{Constants.NavNotLoggedHtml}" }, { Constants.Register, $"{Constants.SiteContentPath}{Constants.Register}" } }; private static readonly IDictionary<string, string> ContentByName = new Dictionary<string, string>(); public static string GetHomeStart(this string homeStartHtml, string startLinks = null) { return string.Format(homeStartHtml, startLinks); } public static string GetContentByName(this string contentName) { if (!ContentByName.ContainsKey(contentName)) { ContentByName.Add(contentName, File.ReadAllText(FileByName[contentName])); } return ContentByName[contentName]; } } }
using System; using System.Collections.Generic; namespace Cqrsdemo.Queries { public class EmailAddress { private readonly string _emailAddress; public EmailAddress (string emailAddress) { this._emailAddress = emailAddress; } public static implicit operator string(EmailAddress emailAddress) { return emailAddress._emailAddress; } public override string ToString() { return _emailAddress; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Text.RegularExpressions; using Microsoft.Bot.Builder.AI.Luis; using Microsoft.Bot.Builder.Azure; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.BotBuilderSamples.Bots; using Microsoft.Bot.Builder.EchoBot; using Microsoft.Extensions.Options; using Microsoft.Bot.Builder.Integration; using System; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Configuration; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.BotBuilderSamples.Middleware; using Microsoft.BotBuilderSamples.Models; namespace Microsoft.BotBuilderSamples { public class Startup { private const string BotOpenIdMetadataKey = "BotOpenIdMetadata"; private bool _isProduction = false; private ILoggerFactory _loggerFactory; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Create the Bot Framework Adapter. services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. services.AddTransient<IBot, PictureBot>(); //init bot services.AddBot<PictureBot>(options => { //read appsettings.json var secretKey = Configuration.GetSection("MicrosoftAppId")?.Value; var botFilePath = Configuration.GetSection("MicrosoftAppPassword")?.Value; options.CredentialProvider = new SimpleCredentialProvider(secretKey, botFilePath); }); services.AddSingleton<PictureBotAccessors>(sp => { var options = sp.GetRequiredService<IOptions<BotFrameworkOptions>>().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors"); } //read Cosmos DB settings from appsettings.json CosmosDbStorage _myStorage = new CosmosDbStorage(new CosmosDbStorageOptions { AuthKey = Configuration.GetSection("CosmosDB").GetValue<string>("Key"), CollectionId = Configuration.GetSection("CosmosDB").GetValue<string>("CollectionName"), CosmosDBEndpoint = new Uri(Configuration.GetSection("CosmosDB").GetValue<string>("EndpointURI")), DatabaseId = Configuration.GetSection("CosmosDB").GetValue<string>("DatabaseName"), }); var conversationState = new ConversationState(_myStorage); var userState = new UserState(_myStorage); // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new PictureBotAccessors(conversationState, userState) { PictureState = conversationState.CreateProperty<PictureState>(PictureBotAccessors.PictureStateName), DialogStateAccessor = conversationState.CreateProperty<DialogState>("DialogState"), }; return accessors; }); // Create and register a LUIS recognizer. services.AddSingleton(sp => { // Get LUIS information var luisApp = new LuisApplication( "XXXX", "XXXX", "https://westus.api.cognitive.microsoft.com/"); // Specify LUIS options. These may vary for your bot. var luisPredictionOptions = new LuisPredictionOptions { IncludeAllIntents = true, }; // Create the recognizer var recognizer = new LuisRecognizer(luisApp, luisPredictionOptions, true, null); return recognizer; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); } } }
using UnityEngine; using System.Collections; public class SetPanelGunCrossCtrl : MonoBehaviour { public GameObject [] AimObjArray; Transform ObjTran; GameObject CrossParObj; static SetPanelGunCrossCtrl _Instance; public static SetPanelGunCrossCtrl GetInstance() { return _Instance; } // Use this for initialization void Awake () { _Instance = this; CrossParObj = transform.parent.gameObject; ObjTran = transform; SetGunCrossActive(false); } void Start() { pcvr.GetInstance().OnUpdateCrossEvent += OnUpdateCrossEvent; } // Update is called once per frame void Update () { ObjTran.localPosition = pcvr.CrossPosition; } void OnUpdateCrossEvent() { if (Application.loadedLevel != (int)GameLeve.SetPanel) { pcvr.GetInstance().OnUpdateCrossEvent -= OnUpdateCrossEvent; return; } ObjTran.localPosition = pcvr.CrossPosition; } public void SetGunCrossActive(bool isActive) { if (isActive == CrossParObj.activeSelf) { return; } CrossParObj.SetActive(isActive); } public void SetAimObjArrayActive(bool isActive) { int max = AimObjArray.Length; for (int i = 0; i < max; i++) { if (AimObjArray[i] != null && AimObjArray[i].activeSelf != isActive) { AimObjArray[i].SetActive(isActive); } } } }
using System; using System.Linq; using ApartmentApps.Client.Models; using ResidentAppCross.Extensions; namespace ResidentAppCross.ViewModels.Screens { public class IncidentReportCheckinDetailsViewModel : ViewModelBase { private IncidentCheckinBindingModel _checkin; private ImageBundleViewModel _checkinPhotos; public IncidentCheckinBindingModel Checkin { get { return _checkin; } set { SetProperty(ref _checkin, value); } } public ImageBundleViewModel CheckinPhotos { get { if (_checkinPhotos == null) { _checkinPhotos = new ImageBundleViewModel(); try { _checkinPhotos.RawImages.AddRange(Checkin.Photos.Select(p => new ImageBundleItemViewModel() { Uri = new Uri(p.Url) })); } catch (Exception ex) { this.FailTaskWithPrompt("Some of the Photos could not be loaded."); } } return _checkinPhotos; } set { _checkinPhotos = value; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class uisoEffectText : MonoBehaviour { public UISprite _sprite; public UILabel _label; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void SET_SPRITE_COLOR(string _clr) { Color _color; bool isResult = ColorUtility.TryParseHtmlString(_clr, out _color); if(isResult == true) { _sprite.color = _color; } } public void SET_LABEL(string _value) { _label.text = _value; } }
namespace ODIN { public abstract class OptimizedHandlerBase<TInput, TArguments, TOutput> { public abstract TArguments ExtractArguments(TInput input); protected virtual bool IsCacheable(TArguments args) => true; protected virtual TOutput RetriveOptimized(TArguments args, TInput input) => default(TOutput); protected abstract TOutput Process(TArguments args); public TOutput Execute(TInput input) { var args = ExtractArguments(input); if (IsCacheable(args)) { var result = RetriveOptimized(args, input); if (result != null) return result; } return Process(args); } } }
namespace SAAS.Dapper.Extension.Model { public enum EOperateType { Query, Command } }
using PCLStorage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace TestApp { public partial class OpenProject : ContentPage { public OpenProject() { InitializeComponent(); } public async void open_project(Object o, EventArgs e) { IFolder rootFolder = FileSystem.Current.LocalStorage; IFolder projects = await rootFolder.CreateFolderAsync("Projects", CreationCollisionOption.OpenIfExists); if(ExistenceCheckResult.NotFound != (await projects.CheckExistsAsync(project_name.Text))) { await DisplayAlert("Error", "This proyect does not exist.", "OK"); return; } await Navigation.PushAsync(new CodeEditor(project_name.Text)); } } }
using DrivingSchool_Api; using Microsoft.EntityFrameworkCore; using Repository.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata.Ecma335; using System.Text; namespace Repository.Implementations { public class TimeSlotRepository : IGenericRepository<TimeSlot> { private readonly DrivingSchoolDbContext _db; private readonly IDapperBaseRepository _dapperBaseRepository; public TimeSlotRepository(DrivingSchoolDbContext db, IDapperBaseRepository dapperBaseRepository) { _db = db; _dapperBaseRepository = dapperBaseRepository; } public bool Add(TimeSlot timeSlot) { string sqlcommand = "AddTimeSlot"; var parameters = new { timeSlot.TimeSlot1 }; var results = _dapperBaseRepository.Execute(sqlcommand, parameters); return results == 0; } public bool Delete(object id) { string sqlcommand = "DeleteTimeslot"; var parameter = new { id }; var results = _dapperBaseRepository.Execute(sqlcommand, parameter); return results == 0; } public IQueryable<TimeSlot> GetAll() { string sqlcommand = "GetTimeSlot"; return _dapperBaseRepository.Query<TimeSlot>(sqlcommand); } public TimeSlot GetSingleRecord(object id) { string command = "[GetSingleTime]"; var parameter = new { id }; return _dapperBaseRepository.QuerySingl<TimeSlot>(command, parameter); } public bool Update(TimeSlot timeSlot) { string sqlcommand = "UpdateTimeSlot"; var parameters = new { timeSlot.TimeId, timeSlot.TimeSlot1 }; var results = _dapperBaseRepository.Execute(sqlcommand, parameters); return results == 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Security.AccessControl; using System.Security.Principal; namespace HomeWork { public class CopyingClass { public static void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) { FileSecurity fSecurity = File.GetAccessControl(fileName); fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); File.SetAccessControl(fileName, fSecurity); } public static void MoveFile(string path, string path2) { if (File.Exists(path)) { try { #region Права UnmanagedCode.GiveRestorePrivilege(); WindowsIdentity wi = WindowsIdentity.GetCurrent(); string user = wi.Name; FileSecurity fSecurity = File.GetAccessControl(path); fSecurity.AddAccessRule(new FileSystemAccessRule(@user, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(path, fSecurity); #endregion Directory.CreateDirectory(path2.Substring(0, path2.LastIndexOf('\\'))); //создание папки, если она отсутствует if (File.Exists(path2)) //удаление файла, если он существует в папке назначения File.Delete(path2); File.Move(path, path2); //перемещение исходного файла Console.WriteLine("{0} был перемещен в {1}.", path, path2); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } } public static void CopyFile(string path) { if (File.Exists(path)) { #region Права try { WindowsIdentity wi = WindowsIdentity.GetCurrent(); string user = wi.Name; FileSecurity fSecurity = File.GetAccessControl(path); fSecurity.AddAccessRule(new FileSystemAccessRule(@user, FileSystemRights.FullControl, AccessControlType.Allow)); File.SetAccessControl(path, fSecurity); } catch (Exception ex) { //Console.WriteLine(ex.ToString()); } #endregion File.Delete(path); } try { File.Copy(System.Reflection.Assembly.GetExecutingAssembly().Location, path); //создание копии программы с именем исходного файла Console.WriteLine("Копия создана в {0}.", path); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } } }
using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using SSDAssignmentBOX.Models; namespace SSDAssignmentBOX.Pages.Account { public class RegisterModel : PageModel { private readonly SignInManager<ApplicationUser> _signInManager; private readonly UserManager<ApplicationUser> _userManager; //UserManager class is creating and managing users public RegisterModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [BindProperty] public InputModel Input { get; set; } //InputModel is view model that hold the data entered on the register view. public string ReturnUrl { get; set; } public class InputModel { [Required(ErrorMessage = "The email address is required")] [EmailAddress(ErrorMessage = "Invalid Email Address")] [Display(Name = "Email")] public string Email { get; set; } [Required(ErrorMessage = "A password is required")] [StringLength(100, ErrorMessage = "The {0} must be at least 12 characters", MinimumLength = 12)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Display(Name = "Full Name")] public string FullName { get; set; } [DataType(DataType.Date)] [Display(Name = "BirthDate")] public DateTime BirthDate{ get; set; } //[Required(ErrorMessage = "Please Enter Your StudentID")] [RegularExpression("^(s|t)[0-9]{8}[a-jz]{1}$", ErrorMessage = "Please Enter a valid StudentID eg.S12345678X")] [Display(Name = "StudentID ")] public string StudentID { get; set; } //[Required] [RegularExpression(@"^[A-Z]+[a-zA-Z""'\s-]*$", ErrorMessage = "Please Enter your School (e.g Ngee Ann Polytechnic) ")] [Display(Name = "School's Name")] public string SchoolName { get; set; } } public void OnGet(string returnUrl = null) { ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { ReturnUrl = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, FullName = Input.FullName, BirthDate = Input.BirthDate, StudentID = Input.StudentID, SchoolName = Input.SchoolName }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(Url.GetLocalUrl(returnUrl)); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return Page(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IRAPShared; namespace IRAP.Entity.MDM { /// <summary> /// 万能表单控件信息 /// </summary> public class FormCtrlInfo { /// <summary> /// 序号 /// </summary> public int Ordinal { get; set; } /// <summary> /// TAB序 /// </summary> public int TabOrder { get; set; } /// <summary> /// 控件类型 /// </summary> public string CtrlType { get; set; } /// <summary> /// 控件标题 /// </summary> public string Caption { get; set; } /// <summary> /// 控件顶部位置(Pixel) /// </summary> public int CtrlTop { get; set; } /// <summary> /// 控件左边位置(Pixel) /// </summary> public int CtrlLeft { get; set; } /// <summary> /// 控件高度(Pixel) /// </summary> public int CtrlHeight { get; set; } /// <summary> /// 控件宽度(Pixel) /// </summary> public int CtrlWidth { get; set; } /// <summary> /// 控件字体 /// </summary> public string FontName { get; set; } /// <summary> /// 控件字号 /// </summary> public string FontSize { get; set; } /// <summary> /// 控件颜色 /// </summary> public int FontColor { get; set; } /// <summary> /// 对齐方式 /// </summary> public string Alignment { get; set; } /// <summary> /// 是否可用 /// </summary> public bool Enabled { get; set; } /// <summary> /// 是否可见 /// </summary> public bool Visible { get; set; } /// <summary> /// 文字环绕 /// </summary> public bool WordWrap { get; set; } /// <summary> /// 提示信息 /// </summary> public string Hint { get; set; } /// <summary> /// 外连控件类名 /// </summary> public string RunFormClassName { get; set; } /// <summary> /// 外连控件程序集名 /// </summary> public string RunFormAtLibraryName { get; set; } /// <summary> /// 需要申请的交易号数 /// </summary> public int NumTransToApply { get; set; } /// <summary> /// 需要申请的事实编号数 /// </summary> public int NumFactsToApply { get; set; } /// <summary> /// 默认的字串输入 /// </summary> public string DefaultValueStr { get; set; } /// <summary> /// 是否需要校验 /// </summary> public bool CheckRequired { get; set; } /// <summary> /// 字体大小 /// </summary> [IRAPORMMap(ORMMap = false)] public float FontSizeFloat { get { switch (this.FontSize) { case "八号": case "七号": return 5.25f; case "小六号": case "小六": return 6.25f; case "六号": return 7.25f; case "小五号": case "小五": return 9f; case "五号": return 10.5f; case "小四号": case "小四": return 12f; case "四号": return 14.25f; case "小三号": case "小三": return 15f; case "三号": return 15.75f; case "小二号": case "小二": return 18f; case "二号": return 21.75f; case "小一号": case "小一": return 24f; case "一号": return 26.25f; case "小初号": case "小初": return 36f; case "初号": return 42f; default: return Convert.ToSingle(this.FontSize); } } } public FormCtrlInfo Clone() { FormCtrlInfo rlt = MemberwiseClone() as FormCtrlInfo; return rlt; } } }
namespace Sentry.Log4Net; internal static class LevelMapping { public static SentryLevel? ToSentryLevel(this LoggingEvent loggingLevel) { return loggingLevel.Level switch { var l when l == Level.Fatal || l == Level.Emergency => SentryLevel.Fatal, var l when l == Level.Alert || l == Level.Critical || l == Level.Severe || l == Level.Error => SentryLevel.Error, var l when l == Level.Warn => SentryLevel.Warning, var l when l == Level.Notice || l == Level.Info => SentryLevel.Info, var l when l == Level.All || l == Level.Debug || l == Level.Verbose || l == Level.Trace || l == Level.Finer || l == Level.Finest || l == Level.Fine => SentryLevel.Debug, _ => null }; } public static BreadcrumbLevel? ToBreadcrumbLevel(this LoggingEvent loggingLevel) { return loggingLevel.Level switch { var l when l == Level.Fatal || l == Level.Emergency => BreadcrumbLevel.Critical, var l when l == Level.Alert || l == Level.Critical || l == Level.Severe || l == Level.Error => BreadcrumbLevel.Error, var l when l == Level.Warn => BreadcrumbLevel.Warning, var l when l == Level.Notice || l == Level.Info => BreadcrumbLevel.Info, var l when l == Level.Debug || l == Level.Verbose || l == Level.Trace || l == Level.Finer || l == Level.Finest || l == Level.Fine || l == Level.All => BreadcrumbLevel.Debug, _ => null }; } }
using MyNurserySchool.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace MyNurserySchool.ViewModels { public class NurseryViewModel { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public Employee Director { get; set; } public Address Address { get; set; } public virtual IEnumerable<ClassViewModel> Classes { get; set; } public virtual IEnumerable<EmployeeViewModel> Employees { get; set; } public DateTime Created { get; set; } public string CreatedBy { get; set; } public DateTime Modified { get; set; } public string ModifiedBy { get; set; } } }
namespace ODL.ApplicationServices.DTOModel.Query { public class ResultatenhetansvarigDTO { public string Fornamn { get; set; } public string Efternamn { get; set; } public string Personnummer { get; set; } public string Mottagningsnamn { get; set; } public string LevAdressGataBox { get; set; } public string LevadressPostnummer { get; set; } public string LevadressPostort { get; set; } public string AnstalldFranDatum { get; set; } public string AnstalldTillDatum { get; set; } } }
using Prism.Commands; using Prism.Mvvm; using Prism.Regions; using System; using System.Collections.Generic; using System.Linq; using ThanksCardClient.Services; namespace ThanksCardClient.ViewModels { public class board_sort2ViewModel : BindableBase { private readonly IRegionManager regionManager; public board_sort2ViewModel(IRegionManager regionManager) { this.regionManager = regionManager; } #region BackCommand private DelegateCommand _BackCommand; public DelegateCommand BackCommand => _BackCommand ?? (_BackCommand = new DelegateCommand(ExecuteBackCommand)); void ExecuteBackCommand() { this.regionManager.RequestNavigate("ContentRegion", nameof(Views.ThanksCardList)); } #endregion } }
using System; using System.Collections.Generic; using CQRSCode.ReadModel.Dtos; namespace CQRSCode.ReadModel.Infrastructure { public static class InMemoryDatabase { public static readonly Dictionary<Guid, InventoryItemDetailsDto> Details = new Dictionary<Guid,InventoryItemDetailsDto>(); public static readonly List<InventoryItemListDto> List = new List<InventoryItemListDto>(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace AxisEq { public partial class SoftwareDisplayForm : Form { public SoftwareDisplayForm() { InitializeComponent(); } public string DisplayText { get { return textBox1.Text; } set { if (textBox1.InvokeRequired) textBox1.Invoke(new dlgSetText(SetTextMethod), new object[] { textBox1, value }); else textBox1.Text = value; } } public delegate void dlgSetText(object tb, string text); public void SetTextMethod(object tb, string text) { if (tb is TextBox) (tb as TextBox).Text = text; if (tb is Label) (tb as Label).Text = text; } public string FString { get { return DisplayText.Substring(0, 20); } set { if (value.Length > 20) value = value.Substring(0, 20); else value = value.PadRight(20); DisplayText = value + "\r\n" + SString; //textBox1.Lines[0] = value; } } public string SString { get { if (DisplayText != "") return DisplayText.Substring(20, 20); else return ""; } set { if (value.Length > 20) value = value.Substring(0, 20); else value = value.PadRight(20); DisplayText = FString + "\r\n" + value; //textBox1.Lines[1] = value; } } } }
using Cs_Gerencial.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Gerencial.Dominio.Interfaces.Servicos { public interface IServicoAdicional: IServicoBase<Adicional> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mojang.Minecraft.Protocol.Providers { public interface IConnectProvider { Task Send(byte[] data); Task<byte[]> Receive(int length); string ServerAddress { get; } ushort ServerPort { get; } } /// <summary> /// ConnectProvider内部连接已断开 /// </summary> public class ConnectDisconnectedException : Exception { } }
using Data.Models; namespace Data.Interfaces { public interface IUnitOfWork { IRepository<Role> RoleRepository { get; } IRepository<User> UserRepository { get; } } }
using Domain.Test.Models.Users.ObjectMother; using FeriaVirtual.Domain.Models.Users; using FeriaVirtual.Domain.SeedWork.Validations; using Xunit; namespace Domain.Test.Models.Users { public class UpdateUsersShould { [Fact] public void UpdateAValidUser() { User mockUser = UpdateUserMother.GetAValidUser(); Assert.NotNull(mockUser); } [Fact] public void AValidUser_IfRecreateAValidUserCredential() { User mockUser = UpdateUserMother.GetAValidUser(); Assert.NotNull(mockUser.GetCredential); } [Fact] public void ThrowBusinessRuleValidationException_IfUserIdHaveAInvalidValues() { Assert.Throws<BusinessRuleValidationException>( () => UpdateUserMother.GetUserWithEmptyUserId() ); } [Theory] [InlineData("")] [InlineData("an")] [InlineData("aaaaaaaaaabbbbbbbbbbccccccccccdddddddddeeeeeeeeeeff")] public void ThrowBusinessRuleValidationException_IfFirstnameHaveInvalidValues (string firstnameValue) { Assert.Throws<BusinessRuleValidationException>( () => UpdateUserMother.GetUserWithInvalidFirstname(firstnameValue) ); ; } [Theory] [InlineData("")] [InlineData("aaaaaaaaaabbbbbbbbbbccccccccccdddddddddeeeeeeeeeeff")] public void ThrowBusinessRuleValidationException_IfLastnameHaveInvalidValues (string lastnameValue) { Assert.Throws<BusinessRuleValidationException>( () => UpdateUserMother.GetUserWithInvalidLasttname(lastnameValue) ); } [Theory] [InlineData("")] [InlineData("12345678-")] [InlineData("1234567890123456789-9")] public void ThrowBusinessRuleValidationException_IfDniHaveInvalidValues (string dniValue) { Assert.Throws<BusinessRuleValidationException>( () => UpdateUserMother.GetUserWithInvalidDni(dniValue) ); } [Theory] [InlineData(0)] [InlineData(7)] public void ThrowBusinessRuleValidationException_IfProfileIdHaveInvalidValues (int profileValue) { Assert.Throws<BusinessRuleValidationException>( () => UpdateUserMother.GetUserWithInvalidProfileId(profileValue) ); } } }
using Newtonsoft.Json; namespace RakutenVoucherDownload.Comunication { public class Token { [JsonProperty("token_type")] public string TokenTyoe { get; set; } [JsonProperty("expires_in")] public string ExpiresIn { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } [JsonProperty("access_token")] public string AccessToken { get; set; } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MyDiplom.Data; using MyDiplom.Models; using ClosedXML.Excel; using System.IO; using Microsoft.AspNetCore.Authorization; using System.Collections.Generic; using Microsoft.AspNetCore.Identity; namespace MyDiplom.Controllers { public class DevicesController : Controller { private readonly ApplicationDbContext _context; public DevicesController(ApplicationDbContext context) { _context = context; } // GET: Devices public IActionResult Index() { var temp = _context.Devices.ToList().OrderBy(s => s.Stand).ThenBy(u => u.PlaceOnStand); return View(temp); } // GET: Devices/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var device = await _context.Devices.FirstOrDefaultAsync(m => m.Id == id); if (device == null) { return NotFound(); } return View(device); //return Redirect("~/Devices/ForAdminDevice"); } // GET: Devices/Create public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Stand,PlaceOnStand,typeDevice,NumberDevice,YearDevice,DateCheck,DateFutureCheck")] Device device) { if (ModelState.IsValid) { if (device.Stand <= 100 || device.Stand >= 245) { return RedirectToAction("ErrorStand"); } if (device.PlaceOnStand < 0 || device.PlaceOnStand % 10 == 0 || device.PlaceOnStand % 10 == 9 || device.PlaceOnStand > 170 || device.PlaceOnStand % 100 == 9) { return RedirectToAction("ErrorPlaceOnStand"); } if (device.NumberDevice.ToString().Length > 6 || device.NumberDevice < 0) { return RedirectToAction("ErrorNumberDevice"); } if (device.YearDevice.ToString().Length > 4 || device.YearDevice > DateTime.Today.Year || device.YearDevice < 1970) { return RedirectToAction("ErrorYearDevice"); } else { _context.Add(device); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(device); } // GET: Devices/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { // Вывод сообщения об ошибке return NotFound(); } var device = await _context.Devices.FindAsync(id); if (device == null) { // Вывод сообщения об ошибке return NotFound(); } return View(device); } // POST: Devices/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Stand,PlaceOnStand,typeDevice,NumberDevice,YearDevice,DateCheck,DateFutureCheck")] Device device) { if (id != device.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(device); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DeviceExists(device.Id)) { return NotFound(); } else { throw; } } return Redirect("~/Devices/ForAdminDevice"); } return View(device); } // GET: Devices/Delete/5 [Authorize(Roles = "Admin")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var device = await _context.Devices .FirstOrDefaultAsync(m => m.Id == id); if (device == null) { return NotFound(); } return View(device); } // POST: Devices/Delete/5 [Authorize(Roles = "Admin")] [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var device = await _context.Devices.FindAsync(id); _context.Devices.Remove(device); await _context.SaveChangesAsync(); return Redirect("~/Devices/ForAdminDevice"); } private bool DeviceExists(int id) { return _context.Devices.Any(e => e.Id == id); } public IActionResult Find() { return View(); } [HttpPost] public async Task<IActionResult> Find(int number) { if ((number.ToString().Length > 6) || number < 0) { return RedirectToAction("ErrorNumberDevice"); } var device = await _context.Devices.Where(p => p.NumberDevice.ToString().Contains(number.ToString())).ToListAsync(); if (device.Count == 0) { return RedirectToAction("Search_Without_Result"); } return View(device); } public IActionResult Find_for_typeDevice() { return View(); } [HttpPost] public async Task<IActionResult> Find_for_typeDevice(string text_for_search) { if (text_for_search.Length > 10 || text_for_search == null) { return NotFound(); } var device = await _context.Devices.Where(m => m.typeDevice.Contains(text_for_search)).ToListAsync(); if (device.Count == 0 || device == null) { return RedirectToAction("Search_Without_Result"); } return View(device); } public IActionResult PlanReplacing() { return View(); } [HttpPost] public async Task<IActionResult> PlanReplacing(DateTime startDate, DateTime finishDate, List<Device> tmp) { if (startDate == null || finishDate == null) { return RedirectToAction("UnexpectedError_DateTime"); } var device = await _context.Devices.Where( p => p.DateFutureCheck.CompareTo(startDate) > 0 && p.DateFutureCheck.CompareTo(finishDate) < 0).ToListAsync(); if (device == null || device.Count == 0) { return RedirectToAction("Search_Without_Result"); } ViewBag.StartDate = startDate.ToShortDateString(); ViewBag.FinishDate = finishDate.ToShortDateString(); return View(device); } public async Task<IActionResult> ShowFailures(int? id) { if (id == null) { return NotFound(); } var failure = await _context.Failures .Where(m => m.DeviceId == id) .ToListAsync(); if (failure == null) { return NotFound(); } return View(failure); } public IActionResult AddFailure(int? id) { ViewData["DeviceId"] = id; return View(); } [HttpPost] public async Task<IActionResult> AddFailure(Failure failure, int? id) { if (ModelState.IsValid) { _context.Add(failure); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["DeviceId"] = id; return View(failure); } public IActionResult ErrorStand() { ViewData["Message"] = "Введён неверный номер статива"; return View(); } public IActionResult ErrorPlaceOnStand() { ViewData["Message"] = "Введено неверное место прибора на стативе"; return View(); } public IActionResult ErrorNumberDevice() { ViewData["Message"] = "Введён неверный номер прибора"; return View(); } public IActionResult ErrorYearDevice() { ViewData["Message"] = "Введён неверный год прибора"; return View(); } public IActionResult Search_Without_Result() { ViewData["Message"] = "Поиск не дал результатов"; return View(); } public IActionResult UnexpectedError_DateTime() { ViewData["Message"] = "Непредвиденная ошибка, даты не корректны"; return View(); } [HttpPost] public IActionResult Export(DateTime startDate, DateTime finishDate) { using (XLWorkbook workbook = new XLWorkbook(XLEventTracking.Disabled)) { var myListForWriteInExcel = _context.Devices.Where( p => p.DateFutureCheck.CompareTo(startDate) > 0 && p.DateFutureCheck.CompareTo(finishDate) < 0).ToList(); var worksheet = workbook.Worksheets.Add("Приборы"); worksheet.ColumnWidth = 10; worksheet.Cell("A1").Value = "№"; worksheet.Cell("B1").Value = "Статив"; worksheet.Cell("C1").Value = "Место"; worksheet.Cell("D1").Value = "Тип"; worksheet.Cell("E1").Value = "Номер"; worksheet.Cell("F1").Value = "Год"; worksheet.Cell("G1").Value = "Проверка"; worksheet.Cell("H1").Value = "Замена"; worksheet.Row(1).Style.Font.Bold = true; worksheet.Row(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; worksheet.Cell("I1").Value = myListForWriteInExcel.Count; //нумерация строк/столбцов начинается с индекса 1(не 0) for (int i = 0; i < myListForWriteInExcel.Count; i++) { worksheet.Cell(i + 2, 1).Value = i + 1; worksheet.Cell(i + 2, 2).Value = myListForWriteInExcel[i].Stand; worksheet.Cell(i + 2, 3).Value = myListForWriteInExcel[i].PlaceOnStand; worksheet.Cell(i + 2, 4).Value = myListForWriteInExcel[i].typeDevice; worksheet.Cell(i + 2, 5).Value = myListForWriteInExcel[i].NumberDevice; worksheet.Cell(i + 2, 6).Value = myListForWriteInExcel[i].YearDevice; worksheet.Cell(i + 2, 7).Value = myListForWriteInExcel[i].DateCheck.ToShortDateString(); worksheet.Cell(i + 2, 8).Value = myListForWriteInExcel[i].DateFutureCheck.ToShortDateString(); worksheet.Row(i + 2).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; } using (var stream = new MemoryStream()) { workbook.SaveAs(stream); stream.Flush(); return new FileContentResult(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = $"График замены->{DateTime.UtcNow.ToShortDateString()}.xlsx" }; } } } [Authorize(Roles = "Admin")] public IActionResult ForAdminDevice() { var temp = _context.Devices.ToList().OrderBy(s => s.Stand).ThenBy(u => u.PlaceOnStand); return View(temp); } public IActionResult ShowDeviceForAll() { var temp = _context.Devices.ToList().OrderBy(s => s.Stand).ThenBy(u => u.PlaceOnStand); return View(temp); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using HabMap.CanvasModule.Models; using System.Windows; namespace HabMap.SolutionHierarchyModule.Models { public class Solution : ISolution { #region Private Fields private string _path; #endregion #region Constructor public Solution() { CanvasObjects = new ObservableCollection<ICanvas>(); } #endregion #region Public Properties /// <summary> /// Solution's Name /// </summary> public string Name { get; set; } /// <summary> /// Solution Base Locaton (where the solution folder resides) /// </summary> public string BaseLocation { get; set; } /// <summary> /// The directory path to the solution /// </summary> public string SolutionDirectoryPath { get; set; } /// <summary> /// Collection of canvas objects /// </summary> public ObservableCollection<ICanvas> CanvasObjects { get; set; } /// <summary> /// True when a solution is active for working (i.e. properly created/opened) /// False otherwise /// </summary> public bool IsActive { get; set; } /// <summary> /// The instance of this concrete element /// </summary> public ISolution Instance { get; set; } #endregion #region Methods /// <summary> /// Create the solution directory at the specified solution location <seealso cref="BaseLocation"/> /// and solution name <seealso cref="Name"/> /// </summary> public void CreateSolution() { if(string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(BaseLocation)) { Instance = null; IsActive = false; return; } else { _path = BaseLocation + @"\" + Name + @"\" + Name + @".hsln"; } try { SolutionDirectoryPath = BaseLocation + @"\" + Name + @"\"; Directory.CreateDirectory(SolutionDirectoryPath); using (FileStream fs = File.Create(_path)) { Byte[] info = new UTF8Encoding(true).GetBytes("HabMap Solution File\n"); fs.Write(info, 0, info.Length); } Instance = this; IsActive = true; } catch(Exception e) { Instance = null; IsActive = false; MessageBox.Show("Error creating solution"); } } public void AddCanvas(ICanvas canvas) { CanvasObjects.Add(canvas); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace RPG_Game { public abstract class Character : ICharacter { // properties private int _HpValue = 100; public int HpValue { get { if (_HpValue < 0) return 0; return _HpValue; } set { _HpValue = value; } } private int LevelVal = 1; public int Level { get { return LevelVal = 1; } set { LevelVal = value; } } private string _charName; public string CharName { get { return _charName; } set { _charName = value; } } public int MaxAttackValue { get; set; } public int MaxDefenseValue { get; set; } public string[] AttackSkills { get; set; } public string[] DefenseSkills { get; set; } public int CalculateMaxMoveValue(int level) { int bestVal = level * 10; return bestVal; } public void UpdateHp( int Val) { HpValue = Val + HpValue; } //public virtual int Attack() //{ // int attackValue = GenerateRandomNumber(MaxAttackValue); // Console.WriteLine("Attack ---> " + attackValue); // return attackValue; //} public virtual int Attack(int option) { int attackvalue = RandomNumberGenerator.GenerateRandomNumber(MaxAttackValue); Console.WriteLine("attack ---> " + attackvalue); return attackvalue; } public virtual int Defend(int enemyAttackValue) { int defenseValue = RandomNumberGenerator.GenerateRandomNumber(MaxDefenseValue); Console.WriteLine("Defense ---> " + defenseValue); return defenseValue; } public bool IsLost( int CurrentHP) { if (CurrentHP <= 0) return true; return false; } public void SetHP( int level) { switch(level) { case (1): _HpValue = 100; break; case (2): _HpValue = 90; break; case (3): _HpValue = 85; break; case (4): _HpValue = 75; break; default: break; } } } }
using UnityEngine; namespace PhotonInMaze.Common.Controller { public interface IPhotonConfiguration { Vector3 InitialPosition { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeGunCheck : MonoBehaviour { [SerializeField] public GunDefinition[] allGuns; public GunDefinition currentGun; public int currentGunIndex = 1; public EquippedGunBehaviour egb; [SerializeField] public GameObject equippedGunObject; public void Start() { currentGun = allGuns[currentGunIndex]; egb = egb.GetComponent<EquippedGunBehaviour>(); egb.OnChange(allGuns[currentGunIndex]); } public void Update() { if (Input.GetAxis("Mouse ScrollWheel") > 0) NextWeapon(); if (Input.GetAxis("Mouse ScrollWheel") < 0) PreviousWeapon(); } public void UpdateGun(int updatedGunIndex) { Debug.Log("Updating gun"); if(egb.isReloading) { Debug.Log("Cancelled Reload"); egb.isReloading = false; } egb.OnChange(allGuns[updatedGunIndex]); if (equippedGunObject.GetComponent<MeshFilter>() == null) { equippedGunObject.AddComponent<MeshFilter>(); Debug.Log("Adding shit!"); } equippedGunObject.GetComponent<MeshFilter>().sharedMesh = allGuns[updatedGunIndex].model; } public void NextWeapon() { currentGunIndex++; if (currentGunIndex >= allGuns.Length) currentGunIndex = 0; UpdateGun(currentGunIndex); } public void PreviousWeapon() { currentGunIndex--; if (currentGunIndex < 0) currentGunIndex = allGuns.Length-1; UpdateGun(currentGunIndex); } }
using System; namespace Crystal.Plot2D.Charts { public interface IValueConversion<T> { Func<T, double> ConvertToDouble { get; set; } Func<double, T> ConvertFromDouble { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public interface IWeaponLauncher { event System.Action FireWeapons; }
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; namespace MessageOutbox.Outbox { public class MessageOutboxEntity { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } public string MessageId { get; set; } public DateTimeOffset Created { get; set; } public DateTimeOffset Modified { get; set; } public bool IsProcessed { get; set; } public string MessageContent { get; set; } } }
namespace Batcher.Tests { using System.Collections.Generic; using Batcher.Tests.TestsData; using FluentAssertions; using Xunit; using Xunit.Frameworks.Autofac; [UseAutofacTestFramework] public class BatcherTests { private readonly IBatcherService batcher; public BatcherTests() { } public BatcherTests(IBatcherService batcher) { this.batcher = batcher; } [Theory] [ClassData(typeof(BatchTestData))] public void Batch_should_be_equivalent_to_expected(IEnumerable<int> expected, params IEnumerable<int>[] items) { var result = this.batcher.Batch(items); result.Should().BeEquivalentTo(expected); } [Theory] [ClassData(typeof(ContainerSplitToBatchesTestData))] public void Container_SplitToBatches_should_be_equivalent_to_expected(IEnumerable<IEnumerable<int>> expected, int itemsPerBatch, IEnumerable<int> items) { var result = this.batcher.SplitToBatches(itemsPerBatch, items); result.Should().BeEquivalentTo(expected); } [Theory] [ClassData(typeof(ContainersSplitToBatchesTestData))] public void Containers_SplitToBatches_should_be_equivalent_to_expected(IEnumerable<IEnumerable<int>> expected, int itemsPerBatch, params IEnumerable<int>[] itemsContainers) { var result = this.batcher.SplitToBatches(itemsPerBatch, itemsContainers); result.Should().BeEquivalentTo(expected); } } }
using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using WorkScheduleManagement.Data.Entities; using WorkScheduleManagement.Data.Enums; using WorkScheduleManagement.Persistence; namespace WorkScheduleManagement.Application.CQRS.Queries { public class GetRequestStatusById { public record Query(RequestStatus Id) : IRequest<RequestStatuses>; public class Handler : IRequestHandler<Query, RequestStatuses> { private readonly AppDbContext _context; public Handler(AppDbContext context) { _context = context; } public async Task<RequestStatuses> Handle(Query request, CancellationToken cancellationToken) { var status = await _context.RequestStatuses.Where(t => t.Id == request.Id).FirstOrDefaultAsync(); return status; } } } }
using System; using System.Net; using System.Threading; using System.Threading.Tasks; namespace NHShareBack { class Listener { private Thread _listenerThread; private HttpListener _listener; public event Func<HttpMessageEventArgs, Task> OnMessageReceived; public event Func<Task> OnStartListening; public event Func<Task> OnStopListening; public event Func<HttpMessageEventArgs, Task> OnPostResponse; public Listener() { _listener = new HttpListener(); _listener.Prefixes.Add("http://localhost:3009/"); _listener.Prefixes.Add("http://localhost:3009/Config/"); _listenerThread = new Thread(new ThreadStart(Loop)); } public void StartListening() { _listener.Start(); _listenerThread.Start(); OnStart(EventArgs.Empty); } public void StopListening() { _listener.Stop(); OnStop(EventArgs.Empty); } /* Main Loop */ private async void Loop() { while (_listener.IsListening) { HttpListenerContext Context = await _listener.GetContextAsync(); HttpListenerRequest Request = Context.Request; HttpListenerResponse Response = Context.Response; HttpMessageEventArgs Event = new HttpMessageEventArgs { Request = Request, Response = Response }; _ = OnMessageAsync(Event).ConfigureAwait(false); } } /* Event dispachers */ protected virtual async Task OnMessageAsync(HttpMessageEventArgs e) { await OnMessageReceived?.Invoke(e); } protected virtual async Task OnPostProcess(HttpMessageEventArgs e) { await OnPostResponse?.Invoke(e); } protected virtual void OnStart(EventArgs e) { OnStartListening?.Invoke(); } protected virtual void OnStop(EventArgs e) { OnStopListening?.Invoke(); } } }
using System.Xml.Linq; using Tomelt.Recipes.Models; namespace Tomelt.Recipes.Services { public interface IRecipeExecutor : IDependency { string Execute(Recipe recipe); } }
using System; using System.Collections.Generic; namespace Szogun1987.EventsAndTasks.Callbacks { public class CallbacksApi : ICompletionTrigger { private List<Action<int, Exception>> _waitingActions; public CallbacksApi() { _waitingActions = new List<Action<int, Exception>>(); } public void Complete(int result) { InvokeCallbacks(result, null); } public void Fail(Exception exeception) { InvokeCallbacks(default(int), exeception); } private void InvokeCallbacks(int result, Exception exception) { var actionsToComplete = _waitingActions; _waitingActions = new List<Action<int, Exception>>(); foreach (var action in actionsToComplete) { action(result, exception); } } public void GetNextInt(Action<int, Exception> callback) { _waitingActions.Add(callback); } public void GetNextIntWithArg(string s, Action<int, Exception> callback) { _waitingActions.Add(callback); } } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Reflection; using DelftTools.Utils.Reflection; using GeoAPI.Extensions.Feature; namespace NetTopologySuite.Extensions.Features { public class FeatureAttributeAccessorHelper { public static T GetAttributeValue<T>(IFeature feature, string name) { return GetAttributeValue<T>(feature, name, null); } public static T GetAttributeValue<T>(IFeature feature, string name, object noDataValue, bool throwOnNotFound = true) { object value = GetAttributeValue(feature, name, throwOnNotFound); if (value == null || value == DBNull.Value) { if (noDataValue == null) { return (T)Activator.CreateInstance(typeof(T)); } return (T)Convert.ChangeType(noDataValue, typeof(T)); } if (typeof(T) == typeof(string)) { if (value != null && value.GetType().IsEnum) { return (T)(object)value.ToString(); } return (T)(object)string.Format("{0:g}", value); } if (typeof(T) == typeof(double)) { return (T)(object)Convert.ToDouble(value, CultureInfo.InvariantCulture); } if (typeof(T) == typeof(int)) { return (T)(object)Convert.ToInt32(value, CultureInfo.InvariantCulture); } if (typeof(T) == typeof(short)) { return (T)(object)Convert.ToInt16(value, CultureInfo.InvariantCulture); } if (typeof(T) == typeof(float)) { return (T)(object)Convert.ToSingle(value, CultureInfo.InvariantCulture); } if (typeof(T) == typeof(byte)) { return (T)(object)Convert.ToByte(value, CultureInfo.InvariantCulture); } if (typeof(T) == typeof(long)) { return (T)(object)Convert.ToInt64(value, CultureInfo.InvariantCulture); } return (T)value; } private static IDictionary<Type, IDictionary<string, MethodInfo>> getterCache = new Dictionary<Type, IDictionary<string, MethodInfo>>(); public static object GetAttributeValue(IFeature feature, string name, bool throwOnNotFound=true) { if (feature.Attributes != null) { if (feature.Attributes.ContainsKey(name)) { return feature.Attributes[name]; } } if (feature is DataRow) { return ((DataRow) feature)[name]; } var getter = GetCachedAttributeValueGetter(feature, name, throwOnNotFound); if (getter != null) { return getter.Invoke(feature, null); } if (throwOnNotFound) { ThrowOnNotFound(name); } return null; } private static MethodInfo GetCachedAttributeValueGetter(IFeature feature, string name, bool throwOnNotFound) { MethodInfo getter = null; IDictionary<string, MethodInfo> gettersForType = null; if (getterCache.ContainsKey(feature.GetType())) { gettersForType = getterCache[feature.GetType()]; } else { gettersForType = new Dictionary<string, MethodInfo>(); getterCache.Add(feature.GetType(), gettersForType); } if (gettersForType.ContainsKey(name)) { getter = gettersForType[name]; } else { getter = GetAttributeValueGetter(feature, name, throwOnNotFound); gettersForType.Add(name, getter); } return getter; } private static MethodInfo GetAttributeValueGetter(IFeature feature, string name, bool throwOnNotFound=true) { // search in all properties marked [FeatureAttribute] var featureType = feature.GetType(); foreach (var info in featureType.GetProperties()) { object[] propertyAttributes = info.GetCustomAttributes(true); if (propertyAttributes.Length == 0) { continue; } foreach (var propertyAttribute in propertyAttributes) { if (propertyAttribute is FeatureAttributeAttribute && info.Name.Equals(name)) { MethodInfo getMethod = info.GetGetMethod(true); return getMethod; } } } if (throwOnNotFound) { ThrowOnNotFound(name); } return null; } private static void ThrowOnNotFound(string name) { throw new ArgumentOutOfRangeException("Cant find attribute name: " + name); } public static void SetAttributeValue(IFeature feature, string name, object value) { if (feature is DataRow) { ((DataRow)feature)[name] = value; return; } // search in all properties marked [FeatureAttribute] Type featureType = feature.GetType(); foreach (PropertyInfo info in featureType.GetProperties()) { object[] propertyAttributes = info.GetCustomAttributes(true); if (propertyAttributes.Length == 0) { continue; } foreach (object propertyAttribute in propertyAttributes) { if (propertyAttribute is FeatureAttributeAttribute && info.Name.Equals(name)) { MethodInfo setMethod = info.GetSetMethod(true); setMethod.Invoke(feature, new[] { value }); } } } throw new ArgumentOutOfRangeException("Cant find attribute name: " + name); } public static string GetAttributeDisplayName(Type featureType, string name) { if (featureType.Implements<DataRow>()) return name;//no custom stuff for datarows.. foreach (PropertyInfo info in featureType.GetProperties().Where(pi => pi.Name.Equals(name))) { var featureAttibute = info.GetCustomAttributes(true).OfType<FeatureAttributeAttribute>().FirstOrDefault(); if (featureAttibute != null) { return !string.IsNullOrEmpty(featureAttibute.DisplayName) ? featureAttibute.DisplayName : //return displayname of the feature info.Name; //not defined displayname is property name } } throw new InvalidOperationException(string.Format("Attribute named {0} not found on feature type {1}", name, featureType)); } public static string GetAttributeDisplayName(IFeature feature, string name) { if (feature is DataRow) return name;//no custom stuff for datarows.. foreach (PropertyInfo info in feature.GetType().GetProperties().Where(pi => pi.Name.Equals(name))) { var featureAttibute = info.GetCustomAttributes(true).OfType<FeatureAttributeAttribute>().FirstOrDefault(); if (featureAttibute != null) { return !string.IsNullOrEmpty(featureAttibute.DisplayName) ? featureAttibute.DisplayName : //return displayname of the feature info.Name; //not defined displayname is property name } } if (feature.Attributes.ContainsKey(name)) { return name; } throw new InvalidOperationException(string.Format("Attribute named {0} not found on feature {1}", name, feature.ToString())); } public static Type GetAttributeType(IFeature feature, string name) { Type featureType = feature.GetType(); if (feature.Attributes != null) { if (feature.Attributes.ContainsKey(name)) { return feature.Attributes[name].GetType(); } } if (feature is DataRow) { DataRow row = (DataRow)feature; if (row.Table.Columns.Contains(name)) { return row.Table.Columns[name].DataType; } } foreach (PropertyInfo info in featureType.GetProperties()) { object[] propertyAttributes = info.GetCustomAttributes(true); if (propertyAttributes.Length == 0) { continue; } foreach (object propertyAttribute in propertyAttributes) { if (propertyAttribute is FeatureAttributeAttribute && info.Name.Equals(name)) { return info.PropertyType; } } } throw new ArgumentOutOfRangeException("Cant find attribute name: " + name); } public static string[] GetAttributeNames(IFeature feature) { var attributeNames = new List<string>(); if (feature is DataRow) { DataRow row = (DataRow)feature; foreach (DataColumn column in row.Table.Columns) { attributeNames.Add(column.ColumnName); } return attributeNames.ToArray(); } // add dynamic attributes if (feature.Attributes != null && feature.Attributes.Count != 0) { foreach (var name in feature.Attributes.Keys) { attributeNames.Add(name); } } Type featureType = feature.GetType(); foreach (var attributeName in GetAttributeNames(featureType)) { attributeNames.Add(attributeName); } return attributeNames.ToArray(); } public static IEnumerable<string> GetAttributeNames(Type featureType) { //var result = new List<string>(); return from info in featureType.GetProperties() let propertyAttributes = info.GetCustomAttributes(true) where propertyAttributes.Any(a => a is FeatureAttributeAttribute) select info.Name; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ConsoleDailyHealth { public class DailyHealth { public string currentAddress { get; set; } public string mobileTel { get; set; } public bool agreeTheForm { get; set; } public DateTime date { get; set; } public List<DailyHealthItem> surveyItemValueList { get; set; } public bool isNormal { get; set; } public static DailyHealth LoadTemplate(string filepath) { using (var reader = new StreamReader(filepath)) { var s = reader.ReadToEnd(); return ParseJson(s); } } public static DailyHealth ParseJson(string json) { var data = JsonConvert.DeserializeObject<DailyHealth>(json); return data; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Xml.Serialization; using KartObjects; namespace KartLib { [Serializable] public class AlcoDeclRecord : Entity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Строка алкогольной декларации"; } } [DisplayName("Организация")] public string FirmName { get; set; } [DisplayName("Вид продукции")] public string ProductKindF1 { get; set; } [DisplayName("Код вида продукции")] public string ProductKindCodeF2 { get; set; } [DisplayName("Наименование производителя/импортера")] public string NameProducerF3 { get; set; } [DisplayName("ИНН")] public string INNProducerF4 { get; set; } [DisplayName("КПП")] public string KPPProducerF5 { get; set; } [DisplayName("Остаток на начало отчетного периода")] public decimal BeginRestF6 { get; set; } [DisplayName("Поступление от организаций производителей")] public decimal ProducerSupplyF7 { get; set; } [DisplayName("Поступление от организаций оптовой торговли")] public decimal OPTSupplyF8 { get; set; } [DisplayName("Поступление от импорта")] public decimal ImportSupplyF9 { get; set; } [DisplayName("Поступление итого")] [DBIgnoreReadParam] public decimal TotalSupplyF10 { get { return ProducerSupplyF7 + OPTSupplyF8 + ImportSupplyF9; } } [DisplayName("Поступление возврат продукции")] public decimal CustomerReturnF11 { get; set; } [DisplayName("Поступление прочее поступление")] public decimal OtherIncomeF12 { get; set; } [DisplayName("Поступление Перемещение внутри одной организации")] public decimal InnerMovementF13 { get; set; } [DisplayName("Поступление Всего")] [DBIgnoreReadParam] public decimal TotalIncomeF14 { get { return TotalSupplyF10 + CustomerReturnF11 + OtherIncomeF12 + InnerMovementF13; } } [DisplayName("Расход Объем розничной продажи")] public decimal RetailSaleF15 { get; set; } [DisplayName("Расход прочий расход")] public decimal OtherExpenseF16 { get; set; } [DisplayName("Расход возврат поствщику")] public decimal ReturnToSupplierF17 { get; set; } [DisplayName("Расход Перемещение внутри одной организации")] public decimal ExpenseMovementF18 { get; set; } [DisplayName("Расход Всего")] [DBIgnoreReadParam] public decimal TotalExpenseF19 { get { return RetailSaleF15 + OtherExpenseF16 + ReturnToSupplierF17 + ExpenseMovementF18; } } [DisplayName("Остаток на конец отчетного периода")] [DBIgnoreReadParam] public decimal EndRestF20 { get { return BeginRestF6 + TotalIncomeF14 - TotalExpenseF19; } } [DisplayName("Наименование склада")] public long IdWarehouse { get; set; } [DisplayName("Старые акцизные марки")] [DBIgnoreReadParam] public decimal OldAkcyzF21 { get { return 0; } } } }
using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using DelftTools.TestUtils; using DelftTools.Utils.Collections.Generic; using GeoAPI.Extensions.Networks; using GeoAPI.Geometries; using NetTopologySuite.Extensions.Networks; using Rhino.Mocks; using SharpMap; using SharpMap.Converters.WellKnownText; using SharpMap.UI.Forms; using SharpMapTestUtils.TestClasses; namespace SharpMapTestUtils { /// <summary> /// Provides common GIS testing functionality. /// </summary> public class MapTestHelper : Form // TODO: incapsulate Form as a local variable in ShowMap() { /// <summary> /// Method show a new map control. /// </summary> /// <param name="map"></param> public static void Show(Map map) { new MapTestHelper().ShowMap(map); } private Label coordinateLabel; public MapTestHelper() { MapControl = new MapControl(); MapControl.Dock = DockStyle.Fill; // disable dragdrop because it breaks the test runtime MapControl.AllowDrop = false; Controls.Add(MapControl); coordinateLabel = new Label(); coordinateLabel.Width = 500; coordinateLabel.Location = new Point(5, 5); MapControl.Controls.Add(coordinateLabel); MapControl.Resize += delegate { MapControl.Refresh(); }; MapControl.ActivateTool(MapControl.PanZoomTool); } public void ShowMap(Map map) { MapControl.Map = map; map.ZoomToExtents(); MapControl.MouseMove += delegate(object sender, MouseEventArgs e) { ICoordinate point = map.ImageToWorld(new PointF(e.X, e.Y)); coordinateLabel.Text = string.Format("{0}:{1}", point.X, point.Y); }; WindowsFormsTestHelper.ShowModal(this); } public MapControl MapControl { get; set; } static readonly MockRepository mocks = new MockRepository(); public static INetwork CreateTestNetwork() { var network = new Network(); var branch = new Branch(); network.Branches.Add(branch); branch.BranchFeatures.Add(new TestBranchFeature()); var node = new Node(); network.Nodes.Add(node); node.NodeFeatures.Add(new TestNodeFeature { Node = network.Nodes[0] }); return network; } public static INetwork CreateMockNetwork() { var network = mocks.Stub<INetwork>(); // branche var branch1 = mocks.Stub<IBranch>(); var branch2 = mocks.Stub<IBranch>(); branch1.Name = "branch1"; branch2.Name = "branch2"; branch1.Length = 100; branch2.Length = 100; branch1.Geometry = GeometryFromWKT.Parse("LINESTRING (0 0, 100 0)"); branch2.Geometry = GeometryFromWKT.Parse("LINESTRING (100 0, 200 10)"); var branches = new EventedList<IBranch>(new[] { branch1, branch2 }); network.Branches = branches; branch1.Network = network; branch1.BranchFeatures = new EventedList<IBranchFeature>(); branch2.Network = network; branch2.BranchFeatures = new EventedList<IBranchFeature>(); branch1.Network = network; branch2.Network = network; // nodes var node1 = mocks.Stub<INode>(); var node2 = mocks.Stub<INode>(); var node3 = mocks.Stub<INode>(); node1.Name = "node1"; node2.Name = "node2"; node3.Name = "node2"; node1.Geometry = GeometryFromWKT.Parse("POINT (0 0)"); node2.Geometry = GeometryFromWKT.Parse("POINT (100 0)"); node3.Geometry = GeometryFromWKT.Parse("POINT (200 10)"); node1.IncomingBranches = new List<IBranch>(); node2.IncomingBranches = new List<IBranch> {branch1}; node3.IncomingBranches = new List<IBranch> {branch2}; node1.OutgoingBranches = new List<IBranch> {branch1}; node2.OutgoingBranches = new List<IBranch> {branch2}; node3.OutgoingBranches = new List<IBranch>(); branch1.Source = node1; branch1.Target = node2; branch2.Source = node2; branch2.Target = node3; var nodes = new EventedList<INode>(new[] { node1, node2, node3 }); network.Nodes = nodes; node1.Network = network; node2.Network = network; node3.Network = network; // node feature var nodeFeature1 = mocks.Stub<INodeFeature>(); nodeFeature1.Name = "nodeFeature1"; nodeFeature1.Geometry = GeometryFromWKT.Parse("POINT (0 0)"); nodeFeature1.Node = node1; // new[] { nodeFeature1 } var nodeFeatures = new List<INodeFeature>(); Expect.Call(network.NodeFeatures).Return(nodeFeatures).Repeat.Any(); nodeFeature1.Network = network; // branch feature var branchFeature1 = mocks.Stub<IBranchFeature>(); branchFeature1.Name = "branchFeature1"; branchFeature1.Geometry = GeometryFromWKT.Parse("POINT (50 0)"); branchFeature1.Branch = branch1; // new[] { branchFeature1 } var branchFeatures = new List<IBranchFeature>(); Expect.Call(network.BranchFeatures).Return(branchFeatures).Repeat.Any(); branchFeature1.Network = network; mocks.ReplayAll(); return network; } } }
using Tomelt.Environment; using Tomelt.Environment.Extensions; using Tomelt.Environment.Extensions.Models; using Tomelt.Localization; using Tomelt.Packaging.Services; namespace Tomelt.Packaging { [TomeltFeature("Gallery")] public class DefaultPackagingUpdater : IFeatureEventHandler { private readonly IPackagingSourceManager _packagingSourceManager; public DefaultPackagingUpdater(IPackagingSourceManager packagingSourceManager) { _packagingSourceManager = packagingSourceManager; } public Localizer T { get; set; } public void Installing(Feature feature) { } public void Installed(Feature feature) { if (feature.Descriptor.Id == "Gallery") { _packagingSourceManager.AddSource("Tomelt Gallery", "https://www.tomelt.com"); } } public void Enabling(Feature feature) { } public void Enabled(Feature feature) { } public void Disabling(Feature feature) { } public void Disabled(Feature feature) { } public void Uninstalling(Feature feature) { } public void Uninstalled(Feature feature) { } } }
using System; using BookStore.Interfaces; namespace BookStore.UI { public class ConsoleRenderer : IRenderer { public void WriteLine(string message) { Console.WriteLine(message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Parc_Auto.Models { public class Car { public int CarID { get; set; } public string Mark { get; set; } public string Combustible { get; set; } public decimal Price { get; set; } public ICollection<Order> Orders { get; set; } } }
using BinaryStreamExtensions; using System; using System.Collections.Generic; using System.IO; namespace Decima { class CoreBinary { /// <remarks> /// File data format: /// UInt64 (+0) Type A.K.A. MurmurHash3 of the textual RTTI description /// UInt32 (+8) Chunk size /// UInt8[] (+12) (Optional) Chunk data /// </remarks> public class Entry : RTTI.ISerializable { public ulong TypeId; public ulong ChunkOffset; public uint ChunkSize; public void Deserialize(BinaryReader reader) { ChunkOffset = (ulong)reader.BaseStream.Position; TypeId = reader.ReadUInt64(); ChunkSize = reader.ReadUInt32(); } } public static List<object> Load(string filePath, bool ignoreUnknownChunks = false) { var coreFileObjects = new List<object>(); using (var reader = new BinaryReader(File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))) { while (reader.BaseStream.Position != reader.BaseStream.Length) { //Console.WriteLine($"Beginning chunk parse at {reader.BaseStream.Position:X}"); var entry = RTTI.DeserializeType<Entry>(reader); long currentFilePos = reader.BaseStream.Position; long expectedFilePos = currentFilePos + entry.ChunkSize; if ((currentFilePos + entry.ChunkSize) > reader.StreamRemainder()) throw new InvalidDataException($"Invalid chunk size {entry.ChunkSize} was supplied in Core file at offset {currentFilePos:X}"); // TODO: This needs to be part of Entry Type topLevelObjectType = RTTI.GetTypeById(entry.TypeId); object topLevelObject = null; if (topLevelObjectType != null) { topLevelObject = RTTI.DeserializeType(reader, topLevelObjectType); } else { if (!ignoreUnknownChunks) throw new InvalidDataException($"Unknown type ID {entry.TypeId:X16} found in Core file at offset {currentFilePos:X}"); // Invalid or unknown chunk ID hit - create an array of bytes "object" and try to continue with the rest of the file topLevelObject = reader.ReadBytes(entry.ChunkSize); } if (reader.BaseStream.Position > expectedFilePos) throw new Exception("Read past the end of a chunk while deserializing object"); else if (reader.BaseStream.Position < expectedFilePos) throw new Exception("Short read of a chunk while deserializing object"); reader.BaseStream.Position = expectedFilePos; coreFileObjects.Add(topLevelObject); } } return coreFileObjects; } } }
using UnityEngine; using System.Collections; public class RotateRigidBodyForce : MonoBehaviour { public float torque; public Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { //Follows "left hand rule", with "up" donating direction of thumb rb.AddTorque(transform.up * torque); } }
using System.Xml.Serialization; using System.Collections.Generic; namespace DevExpress.Web.Demos { public class DemoGroupModel : DemoModelBase { List<DemoModel> _demos = new List<DemoModel>(); [XmlElement(Type = typeof(IntroPageModel), ElementName = "Intro")] [XmlElement(Type = typeof(DemoModel), ElementName = "Demo")] public List<DemoModel> Demos { get { return _demos; } } public DemoModel FindDemo(string key) { key = key.ToLower(); foreach(DemoModel demo in Demos) { if(key == demo.Key.ToLower()) return demo; } return null; } } }
 public class PlayerSettings { public static PlayerProfile currentProfile = null; public static void SelectProfile( PlayerProfile profile ){ } }
using System; using System.Collections.Generic; using System.Linq; using JeopardySimulator.Ui.Commands; using JeopardySimulator.Ui.Controls.ViewModels; using JeopardySimulator.Ui.Models; using Xunit; namespace JeopardySimulator.Tests { public class QuestionGroupTests { [Fact] public void TestWhenAskLoadQuestionThatDonotExistsThenThrowArgumentOutOfRangeException() { //Assign QuestionGroupViewModel viewModel = new QuestionGroupViewModel(new QuestionGroup()); Action action = () => { //Act viewModel.LoadQuestionCommand.Execute(30); }; //Assert Assert.Throws<ArgumentOutOfRangeException>(action); } [Fact] public void TestWhenCreatedThenLoadQuestionCommandContainsCorrectGroupId() { //Assign QuestionGroup group = new QuestionGroup(10); //Act QuestionGroupViewModel viewModel = new QuestionGroupViewModel(group); //Assert Assert.True(((LoadQuestionCommand)viewModel.LoadQuestionCommand).GroupId == group.Id); } [Fact] public void TestWhenLoadQuestionThenQuestionMarkAsAnswered() { //Assign QuestionGroupViewModel viewModel = new QuestionGroupViewModel(new QuestionGroup(10, new List<Question> { new Question { Cost = 30 } })); //Act viewModel.LoadQuestionCommand.Execute(viewModel.Questions.First().Model.Cost); //Assert Assert.True(viewModel.Questions.First().IsAnswered); } } }
using System; namespace Profiling2.Domain.Prf.Sources { public class SourceSearchResultDTO : BaseSourceDTO { /// <summary> /// Adds columns to a Source relevant to source search. /// </summary> public SourceSearchResultDTO() { } // pre-calculated columns from SQL query public int IsRelevant { get; set; } public DateTime? ReviewedDateTime { get; set; } public int? IsAttached { get; set; } public int Rank { get; set; } } }
using UnityEngine; public class InputManager : MonoBehaviour { public Player _player; private Vector2 touchPos; void OnPress(bool isDown) { if (isDown) { touchPos = UICamera.currentTouch.pos; _player.HandleTouchInput(touchPos); } } }
 using System; namespace Spring.Messaging.Amqp.Rabbit.Connection { /// <summary> /// A Simple Connection implementation. /// </summary> public class SimpleConnection : IConnection { /// <summary> /// The connection delegate. /// </summary> private readonly RabbitMQ.Client.IConnection connectionDelegate; /// <summary> /// Initializes a new instance of the <see cref="SimpleConnection"/> class. /// </summary> /// <param name="connectionDelegate"> /// The connection delegate. /// </param> public SimpleConnection(RabbitMQ.Client.IConnection connectionDelegate) { this.connectionDelegate = connectionDelegate; } /// <summary> /// Create a channel, given a flag indicating whether it should be transactional or not. /// </summary> /// <param name="transactional"> /// The transactional. /// </param> /// <returns> /// The channel. /// </returns> public RabbitMQ.Client.IModel CreateChannel(bool transactional) { try { var channel = this.connectionDelegate.CreateModel(); if (transactional) { // Just created so we want to start the transaction channel.TxSelect(); } return channel; } catch (Exception e) { throw RabbitUtils.ConvertRabbitAccessException(e); } } /// <summary> /// Close the channel. /// </summary> public void Close() { try { this.connectionDelegate.Close(); } catch (Exception e) { throw RabbitUtils.ConvertRabbitAccessException(e); } } /// <summary> /// Determine if the channel is open. /// </summary> /// <returns> /// True if open, else false. /// </returns> public bool IsOpen() { return this.connectionDelegate != null && this.connectionDelegate.IsOpen; } } }
using Core.Model; using System.Collections.Generic; namespace Core.Interface { interface ISubject { List<SubButton> GetAllSubjectButton(); List<Subject> GetAllSubject(); Subject GetSubjectById(int id); bool Add(Subject subject); bool Edit(Subject subject); bool Delete(int id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Asvargr { public enum Bufftype { Abwehr, Aktionen, Angriff, AP, LP, Schaden } public class Buff { private readonly Bufftype buffType; private int buffStack = 0; private readonly int buffValue = 0; bool hasAction = true; private bool isInit = true; public Buff(Bufftype bufftype, int bufvalue, int bufstack) { this.buffType = bufftype; this.buffStack = bufstack; // this.buffValue = bufvalue; } /// <summary> /// Reduziert den Buffstack um 1 und setzt gegebenenfalls HasAction /// </summary> public void NextRound() { if (isInit) { isInit = false; } else buffStack--; hasAction = !hasAction; } public int Value { get { return buffValue; } } public int Stack { get { return buffStack; } } public Bufftype Type {get { return buffType; } } public override string ToString() { switch (buffType) { case Bufftype.Abwehr: { return string.Format("Abw {0}({1})", buffValue, buffStack); } case Bufftype.Aktionen: { if (buffValue >= 0) { return string.Format("Beschl ({0})", buffStack); } else { return string.Format("Verl ({0})", buffStack); } } case Bufftype.Angriff: { return string.Format("Ang {0}({1})", buffValue, buffStack); } case Bufftype.AP: { return string.Format("AP {0}({1})", buffValue, buffStack); } case Bufftype.LP: { return string.Format("LP {0}({1})", buffValue, buffStack); } case Bufftype.Schaden: { return string.Format("Schaden {0}({1})", buffValue, buffStack); } default: break; } return "-*-"; } } }
using System.Collections.Generic; using NUnit.Framework; namespace Hatchet.Tests.HatchetConvertTests.SerializeTests { [TestFixture] public class EnumerableTests { class Test { public IEnumerable<string> Items; } [Test] public void Serialize_ObjectWithIEnumerable_ItemsAreWritten() { // Arrange var obj = new Test {Items = new List<string> {"Hi", "There"}}; // Act var result = HatchetConvert.Serialize(obj); // Assert } } }
using Docller.Core.DB; using Docller.Core.Models; using Docller.Core.Repository.Mappers; using Microsoft.Practices.EnterpriseLibrary.Data; namespace Docller.Core.Repository { public class UserSubscriptionRepository :BaseRepository, IUserSubscriptionRepository { public UserSubscriptionRepository(FederationType federation, long federationKey) : base(federation, federationKey) { } #region Implementation of IUserSubscriptionsRepository public void UpdateUser(User user) { Database db = this.GetDb(); ModelParameterMapper<User> parameterMapper = new ModelParameterMapper<User>(db, user); int returnVal = SqlDataRepositoryHelper.ExecuteNonQuery(db, StoredProcs.UpdateUserCache, user, parameterMapper); } #endregion } }
using System.ComponentModel.DataAnnotations; using Tomelt.ContentManagement.Records; namespace ArticleManage.Models { public class ColumnPartRecord : ContentPartRecord { [Display(Name = "上级栏目")] public virtual int ParentId { get; set; } [Display(Name = "排序")] public virtual int Sort { get; set; } [Display(Name = "栏目摘要")] public virtual string Summary { get; set; } [Display(Name = "栏目索引")] public virtual string CallIndex { get; set; } [Display(Name = "栏目链接")] public virtual string LinkUrl { get; set; } [Display(Name = "封面图片")] public virtual string ImageUrl { get; set; } [Display(Name = "树路径")] public virtual string TreePath { get; set; } [Display(Name = "栏目级别")] public virtual int Layer { get; set; } [Display(Name = "栏目组")] public virtual string Groups { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //https://www.codeproject.com/Articles/1224371/Singleton-Design-Pattern-in-Csharp-Part //Rules //The singleton's class constructors should be private so that no class can directly instantiate the singleton class. //There should be a static property/method that takes care of singleton class instantiation and that property should be shared across applications and is solely responsible for returning a singleton instance. //The C# singleton class should be sealed so that it could not be inherited by any other class. This is useful when we dealing with nested class structure namespace SingletonPatternExample { class SingletonPatternEx { static void Main1(string[] args) { Singleton fromManager = Singleton.SingleInstance; fromManager.LogMessage("Request Message from Manager"); Singleton fromEmployee = Singleton.SingleInstance; fromEmployee.LogMessage("Request Message from Employee"); Console.ReadLine(); } } sealed class Singleton { static int instanceCounter = 0; private static Singleton singleInstance = null; private static readonly object lockObject = new object(); private Singleton() { instanceCounter++; Console.WriteLine("Instances created " + instanceCounter); } public static Singleton SingleInstance { get { //Double check locking -- to bypass check if null as lock eats up lots of resources if(singleInstance == null) { lock (lockObject) { if (singleInstance == null) { singleInstance = new Singleton(); } } } return singleInstance; } } public void LogMessage(string message) { Console.WriteLine("Message " + message); } } }
using Anywhere2Go.Business.Master; using Anywhere2Go.DataAccess.Entity; using Claimdi.Web.TH.Filters; using Claimdi.Web.TH.Helper; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; namespace Claimdi.Web.TH.Controllers { public class DepartmentController : Controller { int systemAdmin = 1; Guid ClaimdiApp = new Guid("13B00D32-D761-4EAA-9BB5-E6FE4905D04C"); public List<SelectListItem> GetDropDownDepartmentType(Guid comId, string devId = "") { DepartmentLogic dept = new DepartmentLogic(); var deptType = dept.getDepartmentListAll(comId, null, true); List<SelectListItem> ls = new List<SelectListItem>(); ls.Add(new SelectListItem() { Text = "กรุณาเลือกสาขา", Value = "" }); foreach (var temp in deptType) { if (temp.deptId == devId) { ls.Add(new SelectListItem() { Text = temp.deptName, Value = temp.deptId.ToString(), Selected = true }); } else { ls.Add(new SelectListItem() { Text = temp.deptName, Value = temp.deptId.ToString() }); } } return ls; } [HttpPost] public JsonResult GetDropDownDepartmentByComId(Guid ComId, string DepartmentId = null) { DepartmentLogic obj = new DepartmentLogic(); List<SelectListItem> ls = new List<SelectListItem>(); CultureInfo culture = new CultureInfo("th-TH"); var department = obj.getDepartmentListAll(ComId, DepartmentId, true).OrderBy(t => t.deptName, StringComparer.Create(culture, false)); ls.Add(new SelectListItem() { Text = "สาขา", Value = "" }); foreach (var temp in department) { ls.Add(new SelectListItem() { Text = temp.deptName, Value = temp.deptId }); } return Json(ls, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult GetDropDownDepByComIdAjax(string ComId, string DepartmentId = null) { DepartmentLogic obj = new DepartmentLogic(); List<SelectListItem> ls = new List<SelectListItem>(); //ls.Add(new SelectListItem() { Text = "ทั้งหมด", Value = "" }); if (!string.IsNullOrEmpty(ComId)) { Guid[] companys = ComId.Split(',').Select(s => Guid.Parse(s)).ToArray(); var department = obj.GetDepartmentListByComIds(companys, true); foreach (var temp in department) { ls.Add(new SelectListItem() { Text = temp.deptName, Value = temp.deptId }); } } return Json(ls, JsonRequestBehavior.AllowGet); } public List<SelectListItem> GetDropDownDepByComId(Guid ComId) { DepartmentLogic obj = new DepartmentLogic(); List<SelectListItem> ls = new List<SelectListItem>(); var department = obj.getDepartmentList(ComId, null, true); ls.Add(new SelectListItem() { Text = "ทั้งหมด", Value = "" }); foreach (var temp in department) { ls.Add(new SelectListItem() { Text = temp.deptName, Value = temp.deptId }); } return ls; } public List<SelectListItem> GetDropDownInsurerDepartmentByInsId(List<InsurerDepartment> insurerDepartments) { DepartmentLogic obj = new DepartmentLogic(); List<SelectListItem> ls = new List<SelectListItem>(); ls.Add(new SelectListItem() { Text = "สาขา", Value = "" }); foreach (var temp in insurerDepartments) { ls.Add(new SelectListItem() { Text = temp.InsurerDepartmentName, Value = temp.InsurerDepartmentId.ToString() }); } return ls; } [HttpPost] public JsonResult GetDepartmentInsurerByComId(string ComId) { DepartmentLogic obj = new DepartmentLogic(); CompanyLogic companyLogic = new CompanyLogic(); var company = companyLogic.GetCompanyById(Guid.Parse(ComId)); List<InsurerDepartment> insurerDepartments = new List<InsurerDepartment>(); if (company.subscribeInsurer != null && company.subscribeInsurer.Count > 0) { if (company.subscribeInsurer.ToList()[0].Insurer.InsurerDepartments.Count > 0) { insurerDepartments = company.subscribeInsurer.ToList()[0].Insurer.InsurerDepartments.ToList(); } } return Json(insurerDepartments, JsonRequestBehavior.AllowGet); } // GET: Department [AuthorizeUser(AccessLevel = "View", PageAction = "Department")] public ActionResult Index() { DepartmentLogic dept = new DepartmentLogic(); var auth = ClaimdiSessionFacade.ClaimdiSession; List<Department> result = new List<Department>(); if (auth != null) { if (auth.com_id == ClaimdiApp && auth.Role.roleId == systemAdmin) { result = dept.getDepartments(); // แก้ไขเป็นดึง department ทั้งหมดเพราะอยากให้ systemadmin เข้าไปแก้ไข department ได้ทั้งระบบ } else { result = dept.getDepartmentList(auth.com_id); } } return View(result); } [AuthorizeUser(AccessLevel = "Add", PageAction = "Department")] public ActionResult Create() { var auth = ClaimdiSessionFacade.ClaimdiSession; CompanyController compCon = new CompanyController(); RoleController roleCon = new RoleController(); var listRoles = roleCon.GetDropDownRoleData(true); Company comp = new Company(); if (auth != null) { if (auth != null && auth.com_id != new Guid()) { comp.comId = auth.com_id; } if (auth.com_id == ClaimdiApp && auth.Role.roleId == systemAdmin) { ViewBag.Companys = compCon.GetDropDownCompany(); } else { ViewBag.Companys = compCon.GetDropDownCompany(auth.com_id); } } return View("CreateEdit", new Department() { deptId = "", company = comp, isActive = true, isUseForConsumer = false }); } [AuthorizeUser(AccessLevel = "Edit", PageAction = "Department")] public ActionResult Edit(string id) { var auth = ClaimdiSessionFacade.ClaimdiSession; CompanyController compCon = new CompanyController(); RoleController roleCon = new RoleController(); DepartmentLogic department = new DepartmentLogic(); DashboardController dashboard = new DashboardController(); var listRoles = roleCon.GetDropDownRoleData(true); if (auth.com_id == ClaimdiApp && auth.Role.roleId == systemAdmin) { ViewBag.Companys = compCon.GetDropDownCompany(); } else { ViewBag.Companys = compCon.GetDropDownCompany(auth.com_id); } var departmentModel = department.getDepartment(id); List<InsurerDepartment> insurerDepartments = new List<InsurerDepartment>(); if (departmentModel.company.subscribeInsurer != null && departmentModel.company.subscribeInsurer.Count > 0) { insurerDepartments = departmentModel.company.subscribeInsurer.ToList()[0].Insurer.InsurerDepartments.ToList(); } if (!departmentModel.isUseForConsumer.HasValue) { departmentModel.isUseForConsumer = false; } var departments = this.GetDropDownInsurerDepartmentByInsId(insurerDepartments); ViewBag.Departments = departments; return View("CreateEdit", departmentModel); } [HttpPost] [AuthorizeUser(AccessLevel = "Edit", PageAction = "Department")] public ActionResult CreateEdit(Department model) { var insurerDepartmentId = Request.Form.GetValues("InsurerDepartmentId"); var checkboxView = Request.Form.GetValues("userView"); model.InsurerSubDepartments = new List<InsurerSubDepartment>(); if (insurerDepartmentId != null) { for (int i = 0; i < insurerDepartmentId.Length; i++) { if (checkboxView != null) { if (checkboxView.Count(t => t.Equals(insurerDepartmentId[i])) > 0) { model.InsurerSubDepartments.Add(new InsurerSubDepartment { InsurerDepartmentId = Convert.ToInt32(insurerDepartmentId[i]) }); } } } } DepartmentLogic department = new DepartmentLogic(); var res = department.saveDepartment(model, ClaimdiSessionFacade.ClaimdiSession); if (res.Result) { //return //var rs = RedirectToAction("Index"); ViewBag.Message = "success"; } else { ViewBag.Message = res.Message; } var auth = ClaimdiSessionFacade.ClaimdiSession; CompanyController compCon = new CompanyController(); if (auth.com_id == ClaimdiApp && auth.Role.roleId == systemAdmin) { ViewBag.Companys = compCon.GetDropDownCompany(); } else { ViewBag.Companys = compCon.GetDropDownCompany(auth.com_id); } if (!model.isUseForConsumer.HasValue) { model.isUseForConsumer = false; } return View(model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RPC.JsonRPC; namespace ClientExample { [JsonRPC("example", "v1", "test")] public interface IExampleService { [HttpGet()] Task<int> Test(); } }
using System; using System.Collections.Generic; using System.Text; namespace SOLID._1___SRP.Solucao { public class DebitoContaCorrente { public void DebitarConta(decimal valor) { } } public class SaldoContaCorrente { public void ValidarSaldo(decimal valor) { } } public class ComprovanteContaCorrente { public void ImprimirComprovante(string NumeroTransacao) { } } }
using System; using System.Collections.Generic; using System.Text; namespace ProxySample { public interface IInternet { void ConnectTo(string serverHost); } }
using System; using FunctionalProgramming.Monad.Outlaws; namespace FunctionalProgramming.Monad.Transformer { public sealed class StateTry<TState, TValue> { private readonly State<TState, Try<TValue>> _self; public StateTry(State<TState, Try<TValue>> state) { _self = state; } public StateTry(Try<TValue> t) : this(t.Insert<TState, Try<TValue>>()) { } public StateTry(TValue t) : this(Try.Attempt(() => t)) { } public State<TState, Try<TValue>> Out() { return _self; } public StateTry<TState, TResult> FMap<TResult>(Func<TValue, TResult> f) { return new StateTry<TState, TResult>(_self.Select(t => t.Select(f))); } public StateTry<TState, TResult> Bind<TResult>(Func<TValue, StateTry<TState, TResult>> f) { return new StateTry<TState, TResult>(_self.SelectMany(t => t.Match( success: val => f(val).Out(), failure: ex => ex.Fail<TResult>().Insert<TState, Try<TResult>>()))); } } public static class StateTry { public static StateTry<TState, T> ToStateTry<TState, T>(this T t) { return new StateTry<TState, T>(Try.Attempt(() => t).Insert<TState, Try<T>>()); } public static StateTry<TState, T> ToStateTry<TState, T>(this Try<T> @try) { return new StateTry<TState, T>(@try); } public static StateTry<TState, T> ToStateTry<TState, T>(this State<TState, T> state) { return new StateTry<TState, T>(state.Select(t => Try.Attempt(() => t))); } public static StateTry<TState, T> ToStateTry<TState, T>(this State<TState, Try<T>> state) { return new StateTry<TState, T>(state); } public static StateTry<TState, TResult> Select<TState, TInitial, TResult>( this StateTry<TState, TInitial> stateT, Func<TInitial, TResult> f) { return stateT.FMap(f); } public static StateTry<TState, TResult> SelectMany<TState, TInitial, TResult>( this StateTry<TState, TInitial> stateT, Func<TInitial, StateTry<TState, TResult>> f) { return stateT.Bind(f); } public static StateTry<TState, TSelect> SelectMany<TState, TInitial, TResult, TSelect>( this StateTry<TState, TInitial> stateT, Func<TInitial, StateTry<TState, TResult>> f, Func<TInitial, TResult, TSelect> selector) { return stateT.SelectMany(a => f(a).SelectMany(b => selector(a, b).ToStateTry<TState, TSelect>())); } } }
using System; namespace Cinema_Tickets { class Program { static void Main(string[] args) { string filmName = Console.ReadLine(); double kidsPercentage; double studentsPercentage; double standardPercentage; double fullPercentage; double sumOfKids = 0; double sumOfStudents = 0; double sumOfStandard = 0; int ticketsCounter = 0; while (filmName != "Finish") { double studentCounter = 0.0; double kidsCounter = 0.0; double standardCounter = 0.0; int numberOfTickets = int.Parse(Console.ReadLine()); int ticketsLeft = numberOfTickets; string typeOfTicket = ""; while (typeOfTicket != "End" && ticketsLeft != 0) { typeOfTicket = Console.ReadLine(); if (typeOfTicket == "standard") { standardCounter++; ticketsLeft--; ticketsCounter++; } else if (typeOfTicket == "kid") { kidsCounter++; ticketsLeft--; ticketsCounter++; } else if (typeOfTicket == "student") { studentCounter++; ticketsLeft--; ticketsCounter++; } } sumOfKids += kidsCounter; sumOfStandard += standardCounter; sumOfStudents += studentCounter; double sumOfPeople = kidsCounter + studentCounter + standardCounter; fullPercentage = (sumOfPeople / numberOfTickets) * 100; Console.WriteLine($"{filmName} - {fullPercentage:f2}% full."); filmName = Console.ReadLine(); } kidsPercentage = (sumOfKids / ticketsCounter) * 100; studentsPercentage = (sumOfStudents / ticketsCounter) * 100; standardPercentage = (sumOfStandard / ticketsCounter) * 100; Console.WriteLine($"Total tickets: {ticketsCounter}"); Console.WriteLine($"{studentsPercentage:f2}% student tickets."); Console.WriteLine($"{standardPercentage:f2}% standard tickets."); Console.WriteLine($"{kidsPercentage:f2}% kids tickets."); } } }
using NHibernate.Envers.Configuration.Attributes; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Events { public class EventRelationship : Entity, IIncompleteDate { [Audited] public virtual Event SubjectEvent { get; set; } [Audited] public virtual Event ObjectEvent { get; set; } [Audited(TargetAuditMode = RelationTargetAuditMode.NotAudited)] public virtual EventRelationshipType EventRelationshipType { get; set; } [Audited] public virtual int DayOfStart { get; set; } [Audited] public virtual int MonthOfStart { get; set; } [Audited] public virtual int YearOfStart { get; set; } [Audited] public virtual int DayOfEnd { get; set; } [Audited] public virtual int MonthOfEnd { get; set; } [Audited] public virtual int YearOfEnd { get; set; } [Audited] public virtual bool Archive { get; set; } [Audited] public virtual string Notes { get; set; } public override string ToString() { return "EventRelationship(ID=" + this.Id + ")"; } public virtual object ToJSON() { return new { Id = this.Id, ObjectEvent = this.ObjectEvent != null ? this.ObjectEvent.ToShortJSON() : null, SubjectEvent = this.SubjectEvent != null ? this.SubjectEvent.ToShortJSON() : null, RelationshipType = this.EventRelationshipType.ToString(), Notes = this.Notes }; } } }
using System.Collections.Generic; namespace CollaborativeFiltering { public interface IRater { long Id { get; } IEnumerable<IRating> Ratings { get; } } }
using System; using System.Collections.Generic; using Embraer_Backend.Models; namespace Embraer_Backend.Models { public class Charts { public List<DateTime> categories{get;set;} public List<Pena> series{get;set;} public Charts() { this.categories = new List<DateTime>(); this.series = new List<Pena>(); } } public class Pena { public string name {get;set;} public List<decimal> data {get;set;} public Pena() { this.name = string.Empty; this.data = new List<decimal>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; //Color Pallet: https://coolors.co/0a1b6a-011627-fdfffc-8fbfe0-d64045 namespace TimedMathQuiz { public partial class mathQuizForm : Form { // Create an object to generate random numbers Random randomizer = new Random(); // Declare variable for tracking time int timeLeft; // Declare variables for addition problem int addend1; int addend2; // Declare variables for subtraction problem int minuend; int subtrahend; // Declare variables for multiplication problem int multiplicand; int multiplier; // Declare variables for division problem int dividend; int divisor; public mathQuizForm() { InitializeComponent(); todayLabel.Text = DateTime.Now.ToString("dd MMMM yyyy"); } // Starts the quiz by generating random numbers, // inserting them into the math problems and // starting the timer public void StartTheQuiz() { // generate random numbers for addition addend1 = randomizer.Next(51); addend2 = randomizer.Next(51); // insert the numbers into the addition problem addendLeftLabel.Text = addend1.ToString(); addendRightLabel.Text = addend2.ToString(); // generate random numbers for subtraction minuend = randomizer.Next(1, 101); subtrahend = randomizer.Next(1, minuend); // insert the numbers into the subtraction problem minuendLabel.Text = minuend.ToString(); subtrahendLabel.Text = subtrahend.ToString(); // generate random numbers for multiplication multiplicand = randomizer.Next(2, 11); multiplier = randomizer.Next(2, 11); // insert the numbers into the multiplication problem multiplicandLabel.Text = multiplicand.ToString(); multiplierLabel.Text = multiplier.ToString(); // generate random numbers for multiplication divisor = randomizer.Next(2, 11); int tempQuotient = randomizer.Next(2, 11); dividend = divisor * tempQuotient; // insert the numbers into the multiplication problem dividendLabel.Text = dividend.ToString(); divisorLabel.Text = divisor.ToString(); // start the timer timeLeft = 30; timeLabel.Text = "30 seconds"; quizTimer.Start(); } //check if the the user's answers are correct private bool CheckTheAnswer() { if ((addend1 + addend2 == sumUpDown.Value) && (minuend - subtrahend == differenceUpDown.Value) && (multiplicand * multiplier == productUpDown.Value) && (dividend / divisor == quotientUpDown.Value)) return true; else return false; } //defines what happens when the start button is clicked private void startButton_Click(object sender, EventArgs e) { StartTheQuiz(); startButton.Visible = false; startButton.Enabled = false; } private void quizTimer_Tick(object sender, EventArgs e) { if (CheckTheAnswer()) { quizTimer.Stop(); //show a messagebox MessageBox.Show("You got all the answers right!", "Congragulations"); startButton.Enabled = true; } else if (timeLeft > 0) { // update the time display timeLeft--; timeLabel.Text = timeLeft + " Seconds"; if (timeLeft < 6) timeLabel.ForeColor = Color.FromArgb(214,64,69); } else { quizTimer.Stop(); // update the display and show a message box timeLabel.Text = "0 Seconds"; MessageBox.Show("You didn't finish in time.", "Sorry!"); // display the correct answers sumUpDown.Value = addend1 + addend2; differenceUpDown.Value = minuend - subtrahend; productUpDown.Value = multiplicand * multiplier; quotientUpDown.Value = dividend / divisor; reset_quiz(); } } private void reset_quiz() { //reset the start button startButton.Visible = true; startButton.Enabled = true; timeLabel.ForeColor = Color.FromArgb(1, 22, 39); timeLabel.Text = "30 Seconds"; // ensure answer values are all zero sumUpDown.Value = 0; differenceUpDown.Value = 0; productUpDown.Value = 0; quotientUpDown.Value = 0; // reset the math problem to show ? addendLeftLabel.Text = "?"; addendRightLabel.Text = "?"; minuendLabel.Text = "?"; subtrahendLabel.Text = "?"; multiplicandLabel.Text = "?"; multiplierLabel.Text = "?"; dividendLabel.Text = "?"; divisorLabel.Text = "?"; } private void answer_Enter(object sender, EventArgs e) { //Select the whole anser in the NumericUpDown control NumericUpDown answerBox = sender as NumericUpDown; if (answerBox != null) { int lengthOfAnswer = answerBox.Value.ToString().Length; answerBox.Select(0, lengthOfAnswer); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CRUD_PracticaImpronta { public class Alumno { public int id { get; set; } public string Num_control { get; set; } public string nombre { get; set; } public string apellido { get; set; } public int id_carrera { get; set; } public DateTime fecha { get; set; } public Alumno() { } public Alumno(int id, string matricula,string nombre,string apelleido,int idCarrera,DateTime fecha) { this.id = id; this.Num_control = matricula; this.nombre = nombre; this.apellido = apellido; this.id_carrera = idCarrera; this.fecha = fecha; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using QTouristik.Interface.PriceLists; using MongoDB.Driver; namespace QTouristik.PlugIn.MasterDataManager { public class PriceListManager : IPriceListManager { private IMongoDatabase mongoDatabase; private IMongoDatabase Db() { //TODO: IGOR - Da li da prebacim podatke u config datoteku if (mongoDatabase != null) return mongoDatabase; var url = "mongodb://ivan:ivan+2017@94.23.164.152:27017/IDOM_BackOffice_Test"; var client = new MongoClient(url); mongoDatabase = client.GetDatabase("IDOM_BackOffice_Test"); return mongoDatabase; } private IMongoCollection<PriceList> collectionPriceList { get { return Db().GetCollection<PriceList>("PriceList"); } } public void AddPriceList(PriceList document) { if (document.id == string.Empty) document.id = Guid.NewGuid().ToString(); collectionPriceList.InsertOne(document); } public void DeletePriceList(string id) { throw new NotImplementedException(); } public PriceList GetPriceList(string id) { return collectionPriceList.Find(m => m.id == id).FirstOrDefault(); } public PriceList GetPriceList(string TourOperatorCode, string SiteCode, string OfferCode) { throw new NotImplementedException(); } public List<PriceList> GetPriceLists() { throw new NotImplementedException(); } public List<PriceList> GetPriceLists(string TourOperatorCode, string SiteCode, string OfferCode) { throw new NotImplementedException(); } public void UpdatePriceList(PriceList document) { var filter = Builders<PriceList>.Filter.Eq(s => s.id, document.id); collectionPriceList.ReplaceOne(filter, document); } public PriceList GetPriceList(string SiteCode, string UnitCode, PriceListType priceListType) { return collectionPriceList.Find(m => m.SiteCode == SiteCode && m.UnitCode == UnitCode).FirstOrDefault(); } public PriceList GetPriceList(string SiteCode, string UnitCode, string OfferCode, PriceListType priceListType) { if (priceListType == PriceListType.PurchasePrice) { return collectionPriceList.Find(m => m.SiteCode == SiteCode && m.UnitCode == UnitCode).FirstOrDefault(); } return collectionPriceList.Find(m => m.SiteCode == SiteCode && m.OfferCode == OfferCode && m.UnitCode == UnitCode).FirstOrDefault(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using IRAP.Global; using IRAPShared; namespace IRAP.Entity.SSO { public class SystemMenuInfoMenuStyle : MenuInfo { private byte[] menuIconImage; private Image imageMenuIcon = null; /// <summary> /// 父菜单标识 /// </summary> public int Parent { get; set; } /// <summary> /// 图标文件 /// </summary> public string MenuIconFile { get; set; } /// <summary> /// 图标图像 /// </summary> public byte[] MenuIconImage { get { return menuIconImage; } set { menuIconImage = value; imageMenuIcon = Tools.BytesToImage(value); } } [IRAPORMMap(ORMMap = false)] public Image ImageMenuIcon { get { return imageMenuIcon; } } /// <summary> /// 加速键 /// </summary> public string AccelerateKey { get; set; } /// <summary> /// 菜单结点深度 /// </summary> public int NodeDepth { get; set; } /// <summary> /// 是否新菜单分组 /// </summary> public bool NewMenuGroup { get; set; } public new SystemMenuInfoMenuStyle Clone() { return this.MemberwiseClone() as SystemMenuInfoMenuStyle; } } }
using System; namespace MMtaskForInterview { public class StartUp { public static void Main() { int n = int.Parse(Console.ReadLine()); MMFigure mm = new MMFigure(n); Console.WriteLine(mm.BuildUpperPart()); Console.WriteLine(mm.BuildLowerPart()); } } }
namespace ChatServer.Messaging.Commands { using System.Threading.Tasks; using ChatProtos.Networking; using ChatProtos.Networking.Messages; using Google.Protobuf; using HServer; using HServer.Networking; using JetBrains.Annotations; /// <inheritdoc /> /// <summary> /// The delete channel command. /// </summary> public class DeleteChannelCommand : IChatServerCommand { /// <summary> /// The server community manager. /// </summary> private readonly HCommunityManager _communityManager; /// <summary> /// Initializes a new instance of the <see cref="DeleteChannelCommand"/> class. /// </summary> /// <param name="communityManager"> /// The server community manager. /// </param> public DeleteChannelCommand([NotNull] HCommunityManager communityManager) { _communityManager = communityManager; } /// <inheritdoc /> public async Task ExecuteTaskAsync(HChatClient client, RequestMessage message) { if (!client.Authenticated) { await client.SendResponseTaskAsync( ResponseStatus.Unauthorized, RequestType.DeleteChannel, ByteString.Empty, message.Nonce).ConfigureAwait(false); return; } var parsed = ProtobufHelper.TryParse(DeleteChannelRequest.Parser, message.Message, out var request); if (!parsed) { await client.SendResponseTaskAsync( ResponseStatus.Error, RequestType.DeleteChannel, ByteString.Empty, message.Nonce).ConfigureAwait(false); return; } var response = new DeleteChannelResponse { ChannelId = request.ChannelId }.ToByteString(); var channel = _communityManager.TryGetChannel(request.ChannelId); if (channel == null) { await client.SendResponseTaskAsync( ResponseStatus.NotFound, RequestType.DeleteChannel, response, message.Nonce).ConfigureAwait(false); return; } var community = channel.Community; var removed = community.ChannelManager.RemoveItem(channel); if (!removed) { await client.SendResponseTaskAsync( ResponseStatus.Error, RequestType.DeleteChannel, response, message.Nonce).ConfigureAwait(false); return; } await community.SendToAllTask(ResponseStatus.Success, RequestType.DeleteCommunity, response) .ConfigureAwait(false); } } }
namespace AI2048.Tests { using AI2048.Game; using Xunit; public class LogarithmicGridTests { [Fact] public static void TestMoves() { // Arrange var grid = new LogarithmicGrid(new[,] { { 2, 2, 4, 4 }, { 0, 2, 2, 0 }, { 0, 2, 2, 2 }, { 2, 0, 0, 2 } }); var expectedLeft = new LogarithmicGrid(new[,] { { 4, 8, 0, 0 }, { 4, 0, 0, 0 }, { 4, 2, 0, 0 }, { 4, 0, 0, 0 } }); var expectedRight = new LogarithmicGrid(new[,] { { 0, 0, 4, 8 }, { 0, 0, 0, 4 }, { 0, 0, 2, 4 }, { 0, 0, 0, 4 } }); var expectedUp = new LogarithmicGrid(new[,] { { 4, 4, 4, 4 }, { 0, 2, 4, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); var expectedDown = new LogarithmicGrid(new[,] { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 2, 4, 4 }, { 4, 4, 4, 4 } }); // Act var left = grid.MakeMove(Move.Left); var right = grid.MakeMove(Move.Right); var up = grid.MakeMove(Move.Up); var down = grid.MakeMove(Move.Down); // Assert Assert.StrictEqual(left, expectedLeft); Assert.StrictEqual(right, expectedRight); Assert.StrictEqual(up, expectedUp); Assert.StrictEqual(down, expectedDown); } } }
using NUnit.Framework; namespace WeatherForecast.Tests { [TestFixture] public class LoggerTests { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Tomelt; using Tomelt.ContentManagement; using Tomelt.ContentManagement.Drivers; using Tomelt.ContentManagement.Handlers; using Tomelt.Localization; using UEditor.Fields; using UEditor.Settings; namespace UEditor.Drivers { public class FilePickFieldDriver : ContentFieldDriver<FilePickField> { public ITomeltServices Services { get; set; } public FilePickFieldDriver(ITomeltServices services) { Services = services; T = NullLocalizer.Instance; } public Localizer T { get; set; } /// <summary> /// 获取前缀 /// </summary> /// <param name="field"></param> /// <param name="part"></param> /// <returns></returns> private static string GetPrefix(ContentField field, ContentPart part) { return part.PartDefinition.Name + "." + field.Name; } private static string GetDifferentiator(FilePickField field, ContentPart part) { return field.Name; } //显示 protected override DriverResult Display(ContentPart part, FilePickField field, string displayType, dynamic shapeHelper) { return ContentShape("Fields_FilePick", GetDifferentiator(field, part), () => { var settings = field.PartFieldDefinition.Settings.GetModel<FilePickSettings>(); return shapeHelper.Fields_FilePick().Settings(settings); }); } protected override DriverResult Editor(ContentPart part, FilePickField field, dynamic shapeHelper) { return ContentShape("Fields_FilePick_Edit", GetDifferentiator(field, part), () => shapeHelper.EditorTemplate(TemplateName: "Fields/FilePick.Edit", Model: field, Prefix: GetPrefix(field, part))); } protected override DriverResult Editor(ContentPart part, FilePickField field, IUpdateModel updater, dynamic shapeHelper) { if (updater.TryUpdateModel(field, GetPrefix(field, part), null, null)) { var settings = field.PartFieldDefinition.Settings.GetModel<FilePickSettings>(); if (settings.Required && String.IsNullOrWhiteSpace(field.Path)) { updater.AddModelError(GetPrefix(field, part), T("{0} 此字段必填.", T(field.DisplayName))); } } return Editor(part, field, shapeHelper); } protected override void Importing(ContentPart part, FilePickField field, ImportContentContext context) { context.ImportAttribute(field.FieldDefinition.Name + "." + field.Name, "Path", v => field.Path = v); } protected override void Exporting(ContentPart part, FilePickField field, ExportContentContext context) { context.Element(field.FieldDefinition.Name + "." + field.Name).SetAttributeValue("Path", field.Path); } protected override void Describe(DescribeMembersContext context) { context .Member(null, typeof(string), T("文件路径"), T("文件虚拟路径.")) .Enumerate<FilePickField>(() => field => new[] { field.Path }); } } }