text
stringlengths
13
6.01M
using System; using Domain; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace Persistence { public class DataContext : IdentityDbContext<AppUser> { public DataContext(DbContextOptions options) : base(options) { // } public DbSet<Activity> Activities { get; set; } public DbSet<ActivityAttendee> ActivityAttendees { get; set; } public DbSet<Photo> Photos { get; set; } public DbSet<Comment> Comments { get; set; } public DbSet<UserFollowing> UserFollowings { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<ActivityAttendee>(x => x.HasKey(activityAttendee => new { activityAttendee.AppUserId, activityAttendee.ActivityId })); builder.Entity<ActivityAttendee>() .HasOne(activityAttendee => activityAttendee.AppUser) .WithMany(activities => activities.Activities) .HasForeignKey(activityAttendee => activityAttendee.AppUserId); builder.Entity<ActivityAttendee>() .HasOne(activityAttendee => activityAttendee.Activity) .WithMany(activities => activities.Attendees) .HasForeignKey(activityAttendee => activityAttendee.ActivityId); builder.Entity<Comment>() .HasOne(comment => comment.Activity) .WithMany(activity => activity.Comments) .OnDelete(DeleteBehavior.Cascade); builder.Entity<UserFollowing>(builder => { builder.HasKey(userFollowing => new { userFollowing.ObserverId, userFollowing.TargetId }); builder.HasOne(userFollowing => userFollowing.Observer) .WithMany(appUser => appUser.Followings) .HasForeignKey(userFollowing => userFollowing.ObserverId) .OnDelete(DeleteBehavior.Cascade); builder.HasOne(userFollowing => userFollowing.Target) .WithMany(appUser => appUser.Followers) .HasForeignKey(userFollowing => userFollowing.TargetId) .OnDelete(DeleteBehavior.Cascade); }); } } }
using System; namespace Server { public static partial class StartupExtensions { internal class InvokeOnDispose : IDisposable { private readonly Action _onDispose; public InvokeOnDispose(Action onDispose) { _onDispose = onDispose; } public void Dispose() { _onDispose?.Invoke(); } } } }
using System.Windows; using System.Windows.Controls; using Torshify.Radio.Framework; namespace Torshify.Radio.EchoNest.Views.Favorites.Tabs { public class FavoritesItemTemplateSelector : DataTemplateSelector { #region Properties public DataTemplate TrackFavorite { get; set; } public DataTemplate TrackContainerFavorite { get; set; } public DataTemplate TrackStreamFavorite { get; set; } #endregion Properties #region Methods public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is TrackFavorite) { return TrackFavorite; } if (item is TrackContainerFavorite) { return TrackContainerFavorite; } if (item is TrackStreamFavorite) { return TrackStreamFavorite; } return base.SelectTemplate(item, container); } #endregion Methods } }
/* Project Prolog * Name: Spencer Carter * CS 1400 Section 3 * Lab #9 - Coding Farmer John's Pseudo-Code * Date: 02/26/2015 * * I declare that the following code was written by me, assisted with * by the lovely people in the drop in lab provided by the instructior * for this project. I understand that copying source code from any other * source constitutes cheating, and that I will recieve a zero on this * project if I am found in violation of this policy. */ using System; namespace Lab_09 { static class Program { #region Const private const int FOUR = 4; private const int TWO = 2; private const char CHAR_FALSE = 'F'; private const char CHAR_YES = 'Y'; private const double ACRE_SQ_METERS = 4046.85642; #endregion Const /// <summary> /// Purpose: Entry point to this C# program /// </summary> static void Main() { FieldSprinklerSystem(); }//End Main() /// <summary> /// Purpose: This will be the method that calculates the watered and non watered areas of the field in Lab_08 /// </summary> static void FieldSprinklerSystem() { SizeWindow(); #region Psudocode /* The following psudocode is for a method that will work in this program * Switched unit of measure to meters. (will convert to acres easyer). * 01) set up a do while loop / post test loop. Put everything inside * 02) Ask the user to input the radius of a single circle * 03) store that input as a double _radius * 04) calculate area for a single circle * _areaCircle = PI * (_radius * _radius) * 05) Calculate the area of the square * _areaSquare = 4 * _radius // 4 is a magic number and will need to be a const * 06) calculate the unwaterd middle section by - 4 90~degree sectiions = 1 360 degree = 1 circle * _areaNoWater = _areaSquare - _areaCicle * 07) calculate the watered sections * _areaWater = _areaCircle * 4 * 08) Display the totals to the user, be sure to include what measure we are using * 09) reach the post test, see if the user wants to try again * 10) Catch any errors in the yes or no with another post test loop and prompt again if needed * 11) if not ask the user to press a key to exit * 12) read key press to close */ #endregion Psudocode #region Initialized Var string _userInput = ""; // for error correction char _userChoice = '\n'; // will be used to determine if the user wants to try again. double _radius = 0.0; // user input #endregion Initialized Var do { do { Console.Clear(); // clearing the garbage to keep things looking clean when we loop back _userChoice = '\n'; // reset to null character so we can escape the if loop Console.WriteLine("Coding Farmer John's Pseudo-Code\n"); // the title of the project Console.Write("Enter the Sprinkler Radius in Meters: "); _userInput = Console.ReadLine(); double.TryParse(_userInput, out _radius); if (_radius <= 0) { Console.WriteLine("{0} is an invalad input, please try again.", _userInput); MakeReady(); _userChoice = CHAR_FALSE; } else { continue; } }while(_userChoice == CHAR_FALSE); double _areaCircle = Math.PI * (_radius * _radius); _areaCircle = _areaCircle / ACRE_SQ_METERS; double _areaSquare = (TWO * _radius) * (TWO * _radius); // L = r + r, W = r + r, A = L * W _areaSquare = _areaSquare / ACRE_SQ_METERS; double _areaDrought = _areaSquare - _areaCircle; double _areaWetness = FOUR * _areaCircle; Console.WriteLine("\nBased off your input, we will display the area of your field in Acres."); Console.WriteLine("Press Any Key to Continue... "); Console.ReadKey(true); Console.WriteLine("\nYour sprinkler system waters {0} conjoined circular fields, with an area of {1:f3} acres each." + "\nThe total watered section is {2:f3} acres, and the unwatered section is {3:f3} acres.", FOUR, _areaCircle, _areaWetness, _areaDrought); Console.Write("\nDo you want to try again? Enter Yes or No: "); _userChoice = ((_userInput = Console.ReadLine()) == "" ? CHAR_FALSE : char.ToUpper(_userInput[0])); }while(_userChoice == CHAR_YES); MakeReady(); }//End FieldSprinklerSystem() /// <summary> /// Purpose: to clean up the console and to either move to the next method or close the console. /// </summary> static void MakeReady() { Console.Write("Press Any Key to Continue... "); Console.ReadKey(true); Console.Clear(); }//End ConsoleMakeReady() /// <summary> /// Purpose: to make the window a proper size /// </summary> private static void SizeWindow() { Console.SetWindowSize(Console.LargestWindowWidth / TWO, Console.LargestWindowHeight / TWO); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.DarkBlue; Console.Clear(); }//End SizeWindow() }//End class Program }//End namespace Lab_09
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("SpellGeneratedTarget")] public class SpellGeneratedTarget : MonoBehaviour { public SpellGeneratedTarget(IntPtr address) : this(address, "SpellGeneratedTarget") { } public SpellGeneratedTarget(IntPtr address, string className) : base(address, className) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace POG.Werewolf { public class BadSQLiteFileVersionException : Exception { public Int32 FileVersion { get; private set; } public Int32 SchemaVersion { get; private set; } internal BadSQLiteFileVersionException(int dbVersion, int schemaVersion) { FileVersion = dbVersion; SchemaVersion = schemaVersion; } } }
using System; using System.Linq; namespace KT.DB.CRUD { public class GeneratedAnswersRepository: ICrud<GeneratedAnswer> { public GeneratedAnswer Create(GeneratedAnswer entity) { using (var db = new KTEntities()) { db.GeneratedAnswers.AddObject(entity); db.SaveChanges(); return entity; } } public GeneratedAnswer Read(Predicate<GeneratedAnswer> predicate, string[] relatedObjects = null) { using (var db = new KTEntities()) { var test = db.GeneratedAnswers.Include(relatedObjects).AsEnumerable().DefaultIfEmpty(null).FirstOrDefault(a => predicate(a)); return test; } } public GeneratedAnswer[] ReadArray(Predicate<GeneratedAnswer> predicate, string[] relatedObjects = null) { using (var db = new KTEntities()) { var test = db.GeneratedAnswers.Include(relatedObjects).AsEnumerable().Where(a => predicate(a)); return test.ToArray(); } } public GeneratedAnswer Update(GeneratedAnswer entity) { using (var db = new KTEntities()) { var val = db.GeneratedAnswers.DefaultIfEmpty(null).FirstOrDefault(a => a.Id == entity.Id); if (val != null) { val.GeneratedQuestionId = entity.GeneratedQuestionId; val.AnswerId = entity.AnswerId; val.IsSelected = entity.IsSelected; db.SaveChanges(); } return val; } } public void Delete(Predicate<GeneratedAnswer> predicate) { using (var db = new KTEntities()) { var answers = db.GeneratedAnswers.AsEnumerable().Where(a => predicate(a)); foreach (var answer in answers) { db.GeneratedAnswers.DeleteObject(answer); } db.SaveChanges(); } } } }
using System; namespace Algorithms { //implement circular queue class Queue { const int MAX_SIZE = 4; public string[] queue = new string[MAX_SIZE]; public int Head { get; set; } public int Tail { get; set; } public Queue() { Head = -1; Tail = 0; } public void EnQueue(string data) { if (Head == -1) { Head = 0; Tail = 0; } else { Tail++; if (Tail > MAX_SIZE - 1) Tail = 0; } queue [Tail] = data; } public string Dequeue() { string data = queue [Head]; queue [Head] = string.Empty; Head++; if (Head > MAX_SIZE - 1) Head = 0; return data; } public override string ToString() { string output = "Head=" + Head + " Tail=" + Tail + "\n"; foreach (var item in queue) { if (item != "") output += item + ","; } return output; } } }
using Dapper; using EP.CrudModalDDD.Domain.ValueObjects; using System.Data; namespace EP.CrudModalDDD.Infra.Data.DapperHandlers { public class CpfTypeHandler : SqlMapper.TypeHandler<CPF> { public override void SetValue(IDbDataParameter parameter, CPF value) { parameter.Value = value.Numero; } public override CPF Parse(object value) { return new CPF((string)value); } } }
using System; using Logs.Data.Contracts; using Logs.Data.Tests.EfGenericRepositoryTests.Fakes; using Moq; using NUnit.Framework; namespace Logs.Data.Tests.EfGenericRepositoryTests { [TestFixture] public class ConstructorTests { [Test] public void TestConstructor_PassDbContextNull_ShouldThrowArgumentNullException() { // Arrange, Act, Assert Assert.Throws<ArgumentNullException>(() => new EntityFrameworkRepository<FakeGenericRepositoryType>(null)); } [Test] public void TestConstructor_PassDbContextCorrectly_ShouldNotThrow() { // Arrange var mockedDbContext = new Mock<ILogsDbContext>(); // Act, Assert Assert.DoesNotThrow(() => new EntityFrameworkRepository<FakeGenericRepositoryType>(mockedDbContext.Object)); } [Test] public void TestConstructor_PassDbContextCorrectly_ShouldInitializeCorrectly() { // Arrange var mockedDbContext = new Mock<ILogsDbContext>(); // Act var repository = new EntityFrameworkRepository<FakeGenericRepositoryType>(mockedDbContext.Object); // Assert Assert.IsNotNull(repository); } } }
int Max (int arg1, int arg2, int arg3) { int result = arg1; if (arg2> result) result = arg2; if (arg3>result) result = arg3; return result; } int[] array = {11,21,31,41,15,61,17,18,19}; array [0]=12; Console.WriteLine(array [4]); int result = Max( Max (array [0], array [1], array [2]), Max (array [3], array [4], array [5]), Max (array [6], array [7], array [8]) ); Console.WriteLine(result);
namespace LOD.After { public class Person { public string Name { get; private set; } public JoB Designation { get; private set; } public Person(string name, JoB jobDetails) { Name = name; Designation = jobDetails; } public void ChangeJobPositionTo(string newDesignatioName) { Designation.ChangeJobPositionTo(newDesignatioName); } } }
using cn.bmob.io; using cn.bmob.api; using cn.bmob.json; using cn.bmob.tools; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace cn.bmob.example { //Game表对应的模型类 class GameObject : BmobTable { private String fTable; //以下对应云端字段名称 public BmobInt score { get; set; } public String playerName { get; set; } public BmobBoolean cheatMode { get; set; } //构造函数 public GameObject() { } //构造函数 public GameObject(String tableName) { this.fTable = tableName; } public override string table { get { if (fTable != null) { return fTable; } return base.table; } } //读字段信息 public override void readFields(BmobInput input) { base.readFields(input); this.score = input.getInt("score"); this.cheatMode = input.getBoolean("cheatMode"); this.playerName = input.getString("playerName"); } //写字段信息 public override void write(BmobOutput output, bool all) { base.write(output, all); output.Put("score", this.score); output.Put("cheatMode", this.cheatMode); output.Put("playerName", this.playerName); } } }
using PicoShelter_DesktopApp.Services.AppSettings.Enums; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Windows.Data; namespace PicoShelter_DesktopApp.Converters { public class EnumConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is IEnumerable array && !(array is string)) return array.Cast<object>().Select(t => ConvertSingle(t, targetType, parameter, culture)).ToArray(); return ConvertSingle(value, targetType, parameter, culture); } private object ConvertSingle(object value, Type targetType, object parameter, CultureInfo culture) { if (value is LocaleOptions lang) return new CultureInfo(lang.ToString().Replace("_", "-")).EnglishName; return ApplicationViewModel.LanguageResolve($"Enum.{value.GetType().Name}.{value}"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value is IEnumerable array && !(array is string)) return array.Cast<object>().Select(t => ConvertBackSingle(t, targetType.GetElementType(), parameter, culture)).ToArray(); return ConvertBackSingle(value, targetType, parameter, culture); } private object ConvertBackSingle(object value, Type targetType, object parameter, CultureInfo culture) { if (targetType == typeof(LocaleOptions)) return Enum.Parse<LocaleOptions>(CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(t => t.EnglishName == value.ToString()).Name.Replace("-", "_")); string startsWith = $"Enum.{targetType.Name}."; var dictionaries = App.Current.Resources.MergedDictionaries .Where(d => d.Source != null && d.Source.OriginalString.StartsWith("Resources/Locales/lang.")) .Select( t => t.Keys .Cast<string>() .Select(x => new KeyValuePair<string, string>(x, t[x].ToString())) .ToDictionary(t => t.Key, t => t.Value) ); var targetDictionary = dictionaries .Select( t => t.Where( t => t.Key.StartsWith(startsWith) ) .ToDictionary( t => t.Key.Substring(startsWith.Length), t => t.Value ) ) .LastOrDefault( t => t.ContainsValue(value.ToString()) ); var res = targetDictionary?.FirstOrDefault(t => t.Value == value.ToString()).Key; if (res == null) { if (value.ToString().StartsWith(startsWith)) res = value.ToString().Substring(startsWith.Length); else return null; } return Enum.Parse(targetType, res); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace CloudinaryDotNet.Actions { [DataContract] public class UpdateResourceAccessModeResult : BaseResult { [DataMember(Name = "updated")] public List<object> Updated { get; protected set; } [DataMember(Name = "failed")] public List<object> Failed { get; protected set; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using ReturnOfThePioneers.Common.Models; using ReturnOfThePioneers.Common.System; using ReturnOfThePioneers.MasterData; using System.Collections.Generic; namespace ReturnOfThePioneers.Controllers { [Route("graph/master-data")] public class MasterDataController : Controller { private readonly MasterDataService masterDataService; private readonly FamilyInitialSettings familyInitialSettings; public MasterDataController(MasterDataService masterDataService, IOptions<AppSettings> appSettings) { this.masterDataService = masterDataService; familyInitialSettings = appSettings.Value.Family.Initial; } // GET graph/master-data/card [HttpGet("card")] public Response GetCards() { var cards = masterDataService.FindAll<Card>(); var response = new Response(); response.Add("Cards", masterDataService.FindAll<Card>()); response.Add("FamilyInitial", familyInitialSettings); return response; } // GET graph/master-data/equip [HttpGet("equip")] public IEnumerable<Equip> GetEquips() => masterDataService.FindAll<Equip>(); // GET graph/master-data/item [HttpGet("item")] public IEnumerable<Item> GetItems() => masterDataService.FindAll<Item>(); } }
using System; using System.Configuration; namespace NorthwindReglasNegocio { public class brGeneral { public string CadenaConexion { get; set; } public brGeneral() { CadenaConexion = ConfigurationManager.ConnectionStrings["conNW"].ConnectionString; } public void GrabarLog(Exception ex) { } } } /* esto sirve para generar la cadena de conexion y despues heredarla a las distintas clases para hacer la conexion una sola vez */
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum CommandEvent { //保存事件 ChangeDir, CamCW,//镜头顺时针旋转 CamCCW//镜头逆时针选择 }
using NUnit.Framework; using UnityEngine; /// <summary> /// Tests for the Player class /// </summary> [TestFixture] public class PlayerTest { #region Fields /// <summary> /// Character controller for the player /// </summary> private CharacterController pc; /// <summary> /// The model /// </summary> private GameObject model; /// <summary> /// The hip /// </summary> private GameObject hip; /// <summary> /// The left foot /// </summary> private GameObject leftFoot; /// <summary> /// The right foot /// </summary> private GameObject rightFoot; /// <summary> /// The player /// </summary> private Player player; /// <summary> /// The position of the left foot /// </summary> private Vector3 posLeft; /// <summary> /// The position of the right foot /// </summary> private Vector3 posRight; /// <summary> /// The initial pc position /// </summary> private Vector3 initialPcPosition; #endregion Fields #region Methods /// <summary> /// setup for the instances. /// </summary> [SetUp] public void Setup() { model = GameObject.Find("KinectPointMan"); hip = GameObject.Find("00_Hip_Center"); leftFoot = GameObject.Find("33_Foot_Left"); rightFoot = GameObject.Find("43_Foot_Right"); pc = model.transform.parent.gameObject.GetComponent<CharacterController>(); player = new Player(pc, model, hip, leftFoot, rightFoot); Vector3 posLeft = leftFoot.transform.position; Vector3 posRight = rightFoot.transform.position; Vector3 initialPcPosition = pc.transform.position; } /// <summary> /// Tears down. /// </summary> [TearDown] public void TearDown() { player = null; model = null; hip = null; leftFoot = null; rightFoot = null; pc = null; } /// <summary> /// Test for the constructor. /// </summary> [Test] public void TestNull() { Assert.IsNotNull(player); } /// <summary> /// Test for the UpdateCrouch method /// </summary> [Test] public void UpdateCrouchTestModel() { player.UpdateCrouch(); Assert.AreNotEqual(player.pc.transform.position.x, initialPcPosition.x); } /// <summary> /// Test for the UpdateCrouch method /// </summary> [Test] public void UpdateCrouchTestLeftFoot() { player.UpdateCrouch(); Assert.AreNotEqual(player.leftFoot.transform.position.z, posLeft.z); Assert.AreNotEqual(player.leftFoot.transform.position.x, posLeft.x); } /// <summary> /// Test for the UpdateCrouch method /// </summary> [Test] public void UpdateCrouchTestrightFoot() { player.UpdateCrouch(); Assert.AreNotEqual(player.rightFoot.transform.position.z, posRight.z); Assert.AreNotEqual(player.rightFoot.transform.position.x, posRight.x); } /// <summary> /// Test for the CapVector method /// </summary> [Test] public void capVectorTest1() { Vector3 vec1 = new Vector3(1, 2, 3); Vector3 expected = new Vector3(1, 2, 3); player.capVector(vec1, 3, 6); Assert.True(vec1.Equals(expected)); } /// <summary> /// Test for the UpdateMovement method /// </summary> [Test] public void UpdateMovementTest() { player.updateMovement(); Assert.AreNotEqual(player.pc.transform.position.z, initialPcPosition.z); Assert.AreNotEqual(player.pc.transform.position.x, initialPcPosition.x); } /// <summary> /// Test for the UpdateRotation method /// </summary> [Test] public void UpdateRotationTest() { player.updateRotation(); Assert.AreNotEqual(player.pc.transform.position.z, initialPcPosition.z); Assert.AreNotEqual(player.pc.transform.position.x, initialPcPosition.x); } } #endregion Methods
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; public class PlayerDetectCollision : DetectObject { [SerializeField] private float distance_to_be_arrested = 3f; [SerializeField] private float distance_to_owner = 6f; private bool can_attach = false; private bool can_enter = false; private bool can_leave = false; private GameObject object_to_attach = null; private GameObject house_entered = null; private PlayerHidden player_hidden = null; private bool is_inside = false; private GameOverHUDAnimations game_over_animations = null; private float interval_to_enter_house_again_sec = 3.0f; private float time_left_house = 0.0f; private void Start() { player_hidden = GetComponent<PlayerHidden>(); game_over_animations = FindObjectOfType<GameOverHUDAnimations>(); if (game_over_animations == null) { Debug.LogError("no GameOverHudAnimations reference"); } } protected override void HandleCollision(Collider2D collider) { Debug.Log(collider.tag); if (collider.tag == "InsideBuilding") { can_leave = true; } else if (collider.tag == "Animal") { can_attach = collider.GetComponent<AnimalDetectObject>().CanInteractMustache(); object_to_attach = collider.gameObject; } else if(collider.tag == "Building") { if (Time.realtimeSinceStartup - time_left_house > interval_to_enter_house_again_sec && !is_inside) { can_enter = !collider.GetComponent<BuildingDoor>().IsDoorLocked(); house_entered = collider.gameObject; } } if(collider.GetComponent<BBDetectCollision>() != null && !game_over_animations.IsGameOver()) { var BBMustacheDistance = Mathf.Abs(Vector2.Distance(collider.gameObject.transform.position, transform.position)); if (BBMustacheDistance < distance_to_be_arrested) { game_over_animations.GameOverFromBBCollision(); } } if(collider.GetComponent<Mustacheless>() != null && !game_over_animations.IsGameOver()) { var OwnerMustacheDistance = Mathf.Abs(Vector2.Distance(collider.gameObject.transform.position, transform.position)); if (OwnerMustacheDistance < distance_to_owner) { game_over_animations.GameOverFromFoundOwnerCollision(); } } } protected override void HandleStoppedColliding(Collider2D collider) { if (collider.tag == "InsideBuilding") { can_leave = false; } else if (collider.tag == "Animal") { can_attach = false; object_to_attach = null; } else if (collider.tag == "Building") { can_enter = false; if(!is_inside) house_entered = null; } } public void Attach(InputAction.CallbackContext context) { if(can_attach) { object_to_attach.GetComponent<DisplayMustache>().AttachMustache(); object_to_attach.GetComponent<DisplayMustache>().SetPlayer(gameObject); player_hidden.HideOn(object_to_attach); } else if(can_enter && !is_inside) { GetComponent<InsideHouseTrigger>().TriggerOpenHouse(house_entered); GetComponent<SpriteRenderer>().sortingLayerName = "InsideHouse"; transform.position = new Vector2(-23, -8); is_inside = true; } else if(is_inside && can_leave) { GetComponent<InsideHouseTrigger>().TriggerLeaveHouse(); GetComponent<SpriteRenderer>().sortingLayerName = "Player"; transform.position = house_entered.transform.position + new Vector3(0,-2,0); is_inside = false; time_left_house = Time.realtimeSinceStartup; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using Engine; namespace Test_Client { //The commands for interaction between the server and the client enum Command { Login, //Log into the server Logout, //Logout of the server Message, //Send a text message to all the chat clients List, //Get a list of users in the chat room from the server Command, //Game Command PrivateMessage, Pulse, NewLogin, Null //No command } public partial class Test_Client : Form { public Socket clientSocket; //The main client socket public string strServerName; //Name by which the user logs into the room public int user_index; private byte[] byteData = new byte[1024]; //Game Logger (Game Logs ##-##-####.txt) Test_Client_Logger logging; //Error parser Packet_Error error; public Test_Client() { InitializeComponent(); logging = new Test_Client_Logger(); error = new Packet_Error(logging, txtChatBox); timer1.Start(); } private void OnSend(IAsyncResult ar) { try { clientSocket.EndSend(ar); } catch { } } string[] char_Info = new string[] { "Character Slot : ", //0 "Character Name : ", //1 "Character Level : ", //2 "Character EXP : ", //3 "Character Gold : ", //4 "Character Vit : ", //5 "Character Str : ", //6 "Character Int : ", //7 "Character Wis : ", //8 "Character Dex : ", //9 "Character Char : " //10 }; private void OnReceive(IAsyncResult ar) { try { clientSocket.EndReceive(ar); Data msgReceived = new Data(byteData); //Accordingly process the message received switch (msgReceived.cmdCommand) { case Command.Login: lstChatters.Items.Add(msgReceived.strName); break; case Command.Logout: lstChatters.Items.Remove(msgReceived.strName); break; case Command.Message: break; case Command.Command: if (msgReceived.strMessage.Contains("@ERROR")) { string[] words = msgReceived.strMessage.Split('\t'); logging.Logging(string.Format("word 1 = {0} word 2 = {1}", words[0], words[1])); error.ERROR(Convert.ToInt32(words[1])); } else if (msgReceived.strMessage.Contains("@load_Char")) { logging.Logging(string.Format("From Server {0}", msgReceived.strMessage)); string[] words = msgReceived.strMessage.Split('=', ' '); int logThismany = words.Length; logging.Logging(string.Format("DEBUG : parma count : {0}", words.Length)); if (logThismany < 22) break; for(int i = 0; i < logThismany; i++) { #region DULL switch (i) { case 2: logging.Logging(string.Format("{0}{1}", char_Info[0], words[i])); break; case 4: logging.Logging(string.Format("{0}{1}", char_Info[1], words[i])); break; case 6: logging.Logging(string.Format("{0}{1}", char_Info[2], words[i])); break; case 8: logging.Logging(string.Format("{0}{1}", char_Info[3], words[i])); break; case 10: logging.Logging(string.Format("{0}{1}", char_Info[4], words[i])); break; case 12: logging.Logging(string.Format("{0}{1}", char_Info[5], words[i])); break; case 14: logging.Logging(string.Format("{0}{1}", char_Info[6], words[i])); break; case 16: logging.Logging(string.Format("{0}{1}", char_Info[7], words[i])); break; case 18: logging.Logging(string.Format("{0}{1}", char_Info[8], words[i])); break; case 20: logging.Logging(string.Format("{0}{1}", char_Info[9], words[i])); break; case 22: logging.Logging(string.Format("{0}{1}", char_Info[10], words[i])); break; case 24: logging.Logging(string.Format("{0}{1}", char_Info[0], words[i])); break; case 26: logging.Logging(string.Format("{0}{1}", char_Info[1], words[i])); break; case 28: logging.Logging(string.Format("{0}{1}", char_Info[2], words[i])); break; case 30: logging.Logging(string.Format("{0}{1}", char_Info[3], words[i])); break; case 32: logging.Logging(string.Format("{0}{1}", char_Info[4], words[i])); break; case 34: logging.Logging(string.Format("{0}{1}", char_Info[5], words[i])); break; case 36: logging.Logging(string.Format("{0}{1}", char_Info[6], words[i])); break; case 38: logging.Logging(string.Format("{0}{1}", char_Info[7], words[i])); break; case 40: logging.Logging(string.Format("{0}{1}", char_Info[8], words[i])); break; case 42: logging.Logging(string.Format("{0}{1}", char_Info[9], words[i])); break; case 44: logging.Logging(string.Format("{0}{1}", char_Info[10], words[i])); break; case 46: logging.Logging(string.Format("{0}{1}", char_Info[0], words[i])); break; case 48: logging.Logging(string.Format("{0}{1}", char_Info[1], words[i])); break; case 50: logging.Logging(string.Format("{0}{1}", char_Info[2], words[i])); break; case 52: logging.Logging(string.Format("{0}{1}", char_Info[3], words[i])); break; case 54: logging.Logging(string.Format("{0}{1}", char_Info[4], words[i])); break; case 56: logging.Logging(string.Format("{0}{1}", char_Info[5], words[i])); break; case 58: logging.Logging(string.Format("{0}{1}", char_Info[6], words[i])); break; case 60: logging.Logging(string.Format("{0}{1}", char_Info[7], words[i])); break; case 62: logging.Logging(string.Format("{0}{1}", char_Info[8], words[i])); break; case 64: logging.Logging(string.Format("{0}{1}", char_Info[9], words[i])); break; case 66: logging.Logging(string.Format("{0}{1}", char_Info[10], words[i])); break; case 68: logging.Logging(string.Format("{0}{1}", char_Info[0], words[i])); break; case 70: logging.Logging(string.Format("{0}{1}", char_Info[1], words[i])); break; case 72: logging.Logging(string.Format("{0}{1}", char_Info[2], words[i])); break; case 74: logging.Logging(string.Format("{0}{1}", char_Info[3], words[i])); break; case 76: logging.Logging(string.Format("{0}{1}", char_Info[4], words[i])); break; case 78: logging.Logging(string.Format("{0}{1}", char_Info[5], words[i])); break; case 80: logging.Logging(string.Format("{0}{1}", char_Info[6], words[i])); break; case 82: logging.Logging(string.Format("{0}{1}", char_Info[7], words[i])); break; case 84: logging.Logging(string.Format("{0}{1}", char_Info[8], words[i])); break; case 86: logging.Logging(string.Format("{0}{1}", char_Info[9], words[i])); break; case 88: logging.Logging(string.Format("{0}{1}", char_Info[10], words[i])); break; default: break; } #endregion } } else logging.Logging(string.Format("From Server {0}", msgReceived.strMessage)); break; case Command.List: lstChatters.Items.AddRange(msgReceived.strMessage.Split('*')); lstChatters.Items.RemoveAt(lstChatters.Items.Count - 1); txtChatBox.Text += strServerName + " connected\r\n"; break; } if (msgReceived.strMessage != null && msgReceived.cmdCommand != Command.List && msgReceived.cmdCommand != Command.Command) txtChatBox.Text += msgReceived.strMessage + "\r\n"; byteData = new byte[1024]; clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } catch (ObjectDisposedException) { } catch { } } private void Form1_Load(object sender, EventArgs e) { this.Text = "Test Client: " + strServerName; //The user has logged into the system so we now request the server to send //the names of all users who are in the chat room Data msgToSend = new Data (); msgToSend.cmdCommand = Command.List; msgToSend.strName = strServerName; msgToSend.strMessage = null; byteData = msgToSend.ToByte(); clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); byteData = new byte[1024]; //Start listening to the data asynchronously clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } private void txtMessage_TextChanged(object sender, EventArgs e) { if (txtMessage.Text.Length == 0) btnSend.Enabled = false; else btnSend.Enabled = true; } private void Test_Client_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Are you sure you want to leave the chat room?", "Test Client: " + strServerName, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No) { e.Cancel = true; return; } try { //Send a message to logout of the server Data msgToSend = new Data (); msgToSend.cmdCommand = Command.Logout; msgToSend.strName = strServerName; msgToSend.strMessage = null; byte[] b = msgToSend.ToByte (); clientSocket.Send(b, 0, b.Length, SocketFlags.None); clientSocket.Close(); } catch (ObjectDisposedException) { } catch { } } private void loginButton_Click(object sender, EventArgs e) { if ((usernameBox.Text.Length < 3) || (passwordBox.Text.Length < 3)) return; else { LoginData msgToSend = new LoginData(); msgToSend.strUsername = usernameBox.Text; msgToSend.strPassword = passwordBox.Text; msgToSend.cmdCommand = Command.NewLogin; byte[] byteData = msgToSend.ToByte(); clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); txtMessage.Text = null; } } private void button1_Click(object sender, EventArgs e) { } private void cAccountButton_Click(object sender, EventArgs e) { } private void btnSend_Click_1(object sender, EventArgs e) { if (txtMessage.Text.Contains("@")) { try { Data msgToSend = new Data(); msgToSend.strName = "TEST_CLIENT"; msgToSend.strMessage = txtMessage.Text; msgToSend.cmdCommand = Command.Command; logging.Logging(string.Format("To Server : {0}\r\nPacket Type : Command\r\nServer : {1}", msgToSend.strMessage, msgToSend.strName)); byte[] byteData = msgToSend.ToByte(); clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); txtMessage.Text = null; } catch { } } else if (txtMessage.Text.Contains("/")) { try { string[] temp = new string[65535]; Data msgToSend = new Data(); msgToSend.strName = "TEST_CLIENT"; if (txtMessage.Text.Contains(" ")) { txtMessage.Text.Replace('/', ' '); temp = txtMessage.Text.Split(' '); } msgToSend.strToUser = temp[0]; for (int i =1; i<temp.Length; i++) { msgToSend.strMessage += temp[i] + " "; } if (msgToSend.strMessage.Length <= 0) return; msgToSend.cmdCommand = Command.PrivateMessage; byte[] byteData = msgToSend.ToByte(); clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); txtMessage.Text = null; } catch { } } else { try { //Fill the info for the message to be send Data msgToSend = new Data(); msgToSend.strName = "TEST_CLIENT"; msgToSend.strMessage = txtMessage.Text; msgToSend.cmdCommand = Command.Message; logging.Logging(string.Format("To Server : {0}\r\nPacket Type : Message\r\nServer : {1}", msgToSend.strMessage, msgToSend.strName)); byte[] byteData = msgToSend.ToByte(); //Send it to the server clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null); txtMessage.Text = null; } catch { } } } private void txtMessage_KeyDown_1(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { btnSend_Click_1(sender, null); } } private void timer1_Tick(object sender, EventArgs e) { try { Data msgToSend = new Data(); msgToSend.cmdCommand = Command.Pulse; msgToSend.strName = "TEST_CLIENT"; msgToSend.strMessage = "TESTING"; byte[] message; message = msgToSend.ToByte(); clientSocket.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(OnSend), null); } catch { } } } //The data structure by which the server and the client interact with //each other class LoginData { public string strUsername; //Name by which the client logs into the room public string strPassword; //Message text public Command cmdCommand; public LoginData() { this.cmdCommand = Command.Null; this.strUsername = null; this.strPassword = null; } public LoginData(byte[] data) { this.cmdCommand = (Command)BitConverter.ToInt32(data, 0); int userNameLen = BitConverter.ToInt32(data, 4); int passwordLen = BitConverter.ToInt32(data, 8); if (userNameLen > 0) this.strUsername = Encoding.UTF8.GetString(data, 12, userNameLen); else this.strUsername = null; if (passwordLen > 0) this.strPassword = Encoding.UTF8.GetString(data, 8, passwordLen); else this.strPassword = null; } public byte[] ToByte() { List<byte> result = new List<byte>(); result.AddRange(BitConverter.GetBytes((int)cmdCommand)); if (strUsername != null) result.AddRange(BitConverter.GetBytes(strUsername.Length)); else result.AddRange(BitConverter.GetBytes(0)); if (strPassword != null) result.AddRange(BitConverter.GetBytes(strPassword.Length)); else result.AddRange(BitConverter.GetBytes(0)); if (strUsername != null) result.AddRange(Encoding.UTF8.GetBytes(strUsername)); if (strPassword != null) result.AddRange(Encoding.UTF8.GetBytes(strPassword)); return result.ToArray(); } } class Data { //Default constructor public Data() { this.cmdCommand = Command.Null; this.strMessage = null; this.strToUser = null; this.strName = null; } //Converts the bytes into an object of type Data public Data(byte[] data) { //The first four bytes are for the Command this.cmdCommand = (Command)BitConverter.ToInt32(data, 0); //The next four store the length of the name int nameLen = BitConverter.ToInt32(data, 4); //The next four store the length of the message int msgLen = BitConverter.ToInt32(data, 8); int toUserLen = BitConverter.ToInt32(data, 12); //This check makes sure that strName has been passed in the array of bytes if (nameLen > 0) this.strName = Encoding.UTF8.GetString(data, 16, nameLen); else this.strName = null; //This checks for a null message field if (msgLen > 0) this.strMessage = Encoding.UTF8.GetString(data, 16 + nameLen, msgLen); else this.strMessage = null; if (toUserLen > 0) this.strToUser = Encoding.UTF8.GetString(data, 16 + nameLen + toUserLen, msgLen); else this.strToUser = null; } //Converts the Data structure into an array of bytes public byte[] ToByte() { List<byte> result = new List<byte>(); //First four are for the Command result.AddRange(BitConverter.GetBytes((int)cmdCommand)); //Add the length of the name if (strName != null) result.AddRange(BitConverter.GetBytes(strName.Length)); else result.AddRange(BitConverter.GetBytes(0)); //Length of the message if (strMessage != null) result.AddRange(BitConverter.GetBytes(strMessage.Length)); else result.AddRange(BitConverter.GetBytes(0)); if (strToUser != null) result.AddRange(BitConverter.GetBytes(strToUser.Length)); else result.AddRange(BitConverter.GetBytes(0)); //Add the name if (strName != null) result.AddRange(Encoding.UTF8.GetBytes(strName)); //And, lastly we add the message text to our array of bytes if (strMessage != null) result.AddRange(Encoding.UTF8.GetBytes(strMessage)); if (strToUser != null) result.AddRange(Encoding.UTF8.GetBytes(strToUser)); return result.ToArray(); } public string strName; //Name by which the client logs into the room public string strMessage; //Message text public string strToUser; public Command cmdCommand; //Command type (login, logout, send message, etcetera) } }
using Microsoft.Extensions.Logging; namespace OmniSharp.Extensions.JsonRpc { public static class Events { public static EventId UnhandledException { get; } = new EventId(1337_100); public static EventId UnhandledRequest { get; } = new EventId(1337_101); public static EventId UnhandledNotification { get; } = new EventId(1337_102); } }
namespace Problems { using System; public class ProblemA { public static void Main() { var n = ulong.Parse(Console.ReadLine()); var m = ulong.Parse(Console.ReadLine()); var y = ulong.Parse(Console.ReadLine()); var targetsPoked = 0; var fiftyValue = n / 2D; while (true) { n -= m; if (n < 0) { break; } targetsPoked++; if (n == fiftyValue) { try { n /= y; } catch (Exception) { continue; } } if (m > n) { break; } } Console.WriteLine(n); Console.WriteLine(targetsPoked); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Configuration; using System.Globalization; using System.Data; using System.Data.OleDb; using System.IO; using Obout.Interface; using HSoft.SQL; using HSoft.ClientManager.Web; using SisoDb.Sql2012; using SisoDb.Configurations; public partial class Pages_CC_Emails : System.Web.UI.Page { private static String ssql = String.Empty; private static DataTable _dtemails = null; private static DataTable _dtclicks = null; protected void Page_Load(object sender, EventArgs e) { HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString); if (!IsPostBack) { Tools.devlogincheat(); if (Session["ghirarchy"] == null) { Session["ghirarchy"] = String.Format("{0},", Session["guser"]); } LastUpdate.Text = _sql.ExecuteScalar("SELECT lastmodified FROM _CCupdates WHERE tablename = 'Campaings' AND isdeleted = 0").ToString(); // CountContacts.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM ContactStrings WHERE MemberPath = 'Status'").ToString(); // CountActive.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM ContactStrings WHERE MemberPath = 'Status' AND LOWER(Value) ='active'").ToString(); // CountLeads.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM Lead_Flat WHERE isdeleted = 0 ").ToString(); // Linked.Text = _sql.ExecuteScalar("SELECT COUNT(*) FROM Lead_Flat WHERE ConstantContactID >0 AND isdeleted = 0 ").ToString(); } ssql = "SELECT StructureId Id, " + " (SELECT Value FROM EmailCampaignStrings WHERE StructureId = ecs.StructureId AND MemberPath = 'Name') Name, " + " (SELECT Value FROM EmailCampaignDates WHERE StructureId = ecs.StructureId AND MemberPath = 'ModifiedDate') Opened, " + " COALESCE((SELECT isTracked FROM EmailCampaignTracking WHERE EmailCampaignId = ecs.StructureId),0) IsTracked, " + " COALESCE((SELECT LeadText FROM EmailCampaignTracking WHERE EmailCampaignId = ecs.StructureId),'') LeadText" + " FROM EmailCampaignStructure ecs " + " ORDER BY (SELECT Value FROM EmailCampaignDates WHERE StructureId = ecs.StructureId AND MemberPath = 'ModifiedDate') DESC "; _dtemails = _sql.GetTable(ssql); foreach (DataRow dr in _dtemails.Rows) { HtmlTableRow _row = new HtmlTableRow(); HtmlTableCell _cell1 = new HtmlTableCell(); HtmlTableCell _cell2 = new HtmlTableCell(); HtmlTableCell _cell3 = new HtmlTableCell(); HtmlTableCell _cell4 = new HtmlTableCell(); HtmlTableCell _cell5 = new HtmlTableCell(); HtmlTableCell _cell6 = new HtmlTableCell(); HtmlTableCell _cell7 = new HtmlTableCell(); _cell4.Controls.Add(new LiteralControl(dr["Id"].ToString())); _cell1.Controls.Add(new LiteralControl(dr["Name"].ToString())); _cell7.Controls.Add(new LiteralControl(dr["LeadText"].ToString())); _cell2.Controls.Add(new LiteralControl(String.Format("{0:MM/dd/yyyy}", dr["Opened"]))); String _lastUpdate = String.Empty; try { _lastUpdate = _sql.ExecuteScalar2(String.Format("SELECT lastmodified FROM _CCupdates WHERE tablename = 'Campaign_{0}' AND isdeleted = 0", dr["Id"])).ToString(); } catch { } _cell3.Controls.Add(new LiteralControl(String.Format("{0:MM/dd/yyyy}", _lastUpdate))); if (dr["IsTracked"].ToString() == "1" ) { _cell5.Controls.Add(new LiteralControl("Yes")); String scount = _sql.ExecuteScalar(String.Format("SELECT COUNT(*) FROM [CampainActivity] WHERE [CampaignId] = '{0}' AND [isdeleted] = 0 ",dr["Id"])).ToString(); _cell6.Controls.Add(new LiteralControl(scount)); } { _cell5.Controls.Add(new LiteralControl("")); } _row.Cells.Add(_cell4); _row.Cells.Add(_cell1); _row.Cells.Add(_cell2); _row.Cells.Add(_cell3); _row.Cells.Add(_cell5); _row.Cells.Add(_cell6); _row.Cells.Add(_cell7); emails.Rows.Add(_row); } ssql = "SELECT lf.Name Name, ca.EmailAddress Email,lf.Phone, MAX(ca.OpenDate) OpenDate,ecs.Value List, cs.Value Name2" + " FROM CampainActivity ca " + " LEFT OUTER JOIN Lead_Flat lf ON ca.ContactId = lf.ConstantContactID " + " LEFT OUTER JOIN [ContactStrings] cs ON cs.StructureId = ca.ContactId AND cs.MemberPath = 'LastName' " + " LEFT JOIN EmailCampaignStrings ecs ON ecs.StructureId = ca.CampaignId AND ecs.MemberPath = 'Name' " + " GROUP BY lf.Name,ca.EmailAddress,lf.Phone,ecs.Value, cs.Value " + " ORDER BY MAX(ca.OpenDate) desc"; _dtclicks = _sql.GetTable(ssql); foreach (DataRow dr in _dtclicks.Rows) { HtmlTableRow _row = new HtmlTableRow(); HtmlTableCell _cell1 = new HtmlTableCell(); HtmlTableCell _cell2 = new HtmlTableCell(); HtmlTableCell _cell3 = new HtmlTableCell(); HtmlTableCell _cell4 = new HtmlTableCell(); HtmlTableCell _cell5 = new HtmlTableCell(); if (dr["Name"].ToString().Length > 0) { _cell1.Controls.Add(new LiteralControl(dr["Name"].ToString())); } else { _cell1.Controls.Add(new LiteralControl("* ")); _cell1.Controls.Add(new LiteralControl(dr["Name2"].ToString())); } _cell2.Controls.Add(new LiteralControl(dr["Email"].ToString())); _cell3.Controls.Add(new LiteralControl(dr["Phone"].ToString())); _cell4.Controls.Add(new LiteralControl(dr["OpenDate"].ToString())); _cell5.Controls.Add(new LiteralControl(dr["List"].ToString())); _row.Cells.Add(_cell1); _row.Cells.Add(_cell2); _row.Cells.Add(_cell3); _row.Cells.Add(_cell4); _row.Cells.Add(_cell5); clicks.Rows.Add(_row); } _sql.Close(); } protected void Btn_Command(object sender, CommandEventArgs e) { CC_Command(e.CommandName); } protected void CC_Command(string scmd) { switch (scmd) { case "UpdateCampaigns" : { HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString); Tools.SetDate(DateTime.Now,"Campaings"); Tools.update_Campains(); _sql.Close(); } break; case "Update": { Tools.update_Campain(true, Session["guser"].ToString()); } break; } Response.Redirect("/Pages/CC_Emails.aspx"); } }
namespace DbIntegrationTestsWithContainers { using System; using System.Data.SqlClient; using System.Threading.Tasks; using Polly; using TestContainers.Core.Containers; public sealed class SqlServerContainer : DatabaseContainer { private string databaseName = "master"; private string userName = "sa"; private string password = "Password123"; public override string DatabaseName => base.DatabaseName ?? databaseName; public override string UserName => base.UserName ?? userName; public override string Password => base.Password ?? password; public override string ConnectionString => $"Data Source={GetDockerHostIpAddress()};Initial Catalog={DatabaseName};User ID={UserName};Password={Password}"; protected override string TestQueryString => "SELECT 1"; protected override async Task WaitUntilContainerStarted() { await base.WaitUntilContainerStarted(); var connection = new SqlConnection(ConnectionString); var result = await Policy .TimeoutAsync(TimeSpan.FromMinutes(2)) .WrapAsync(Policy .Handle<SqlException>() .WaitAndRetryForeverAsync( iteration => TimeSpan.FromSeconds(10))) .ExecuteAndCaptureAsync(async () => { await connection.OpenAsync(); var cmd = new SqlCommand(TestQueryString, connection); await cmd.ExecuteScalarAsync(); }); if (result.Outcome == OutcomeType.Failure) { connection.Dispose(); throw new Exception(result.FinalException.Message); } } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class PaymentResponse { public PaymentStatus CurrentStatus; public String Message; public String TransactionId; public String ProfileId; public CheckoutRequest CheckoutRequest; public CheckoutData CheckoutData; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace serial { static class Menu { public static void mostrarMenu(Operacoes operacoes) { char op; do { Console.Clear(); Console.WriteLine("Cadastro de Alunos"); Console.WriteLine("==================\n"); Console.WriteLine( "1 - Inserir\n" + "2 - Alterar\n" + "3 - Excluir\n" + "4 - Pesquisar\n" + "5 - Listar\n" + "6 - Ordenar\n" + "7 - Salvar Dados\n" + "8 - Ler Dados\n" + "9 - Sair\n"); Console.Write("Opção: "); op = Console.ReadLine()[0]; switch (op) { case '1': operacoes.inserir(); break; case '2': //TODO Alterar break; case '3': //TODO Exculir break; case '4': //TODO Pesquisar break; case '5': //TODO Listar break; case '6': //TODO Ordenar break; case '7': //TODO Salvar Dados break; case '8': //TODO Ler Dados break; case '9': Console.WriteLine("Saindo...."); break; default: Console.WriteLine("Tente Novamente!"); break; } } while (op != '9'); } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_ComputeBuffer : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 3) { int num2; LuaObject.checkType(l, 2, out num2); int num3; LuaObject.checkType(l, 3, out num3); ComputeBuffer o = new ComputeBuffer(num2, num3); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (num == 4) { int num4; LuaObject.checkType(l, 2, out num4); int num5; LuaObject.checkType(l, 3, out num5); ComputeBufferType computeBufferType; LuaObject.checkEnum<ComputeBufferType>(l, 4, out computeBufferType); ComputeBuffer o = new ComputeBuffer(num4, num5, computeBufferType); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else { result = LuaObject.error(l, "New object failed."); } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Dispose(IntPtr l) { int result; try { ComputeBuffer computeBuffer = (ComputeBuffer)LuaObject.checkSelf(l); computeBuffer.Dispose(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Release(IntPtr l) { int result; try { ComputeBuffer computeBuffer = (ComputeBuffer)LuaObject.checkSelf(l); computeBuffer.Release(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SetData(IntPtr l) { int result; try { ComputeBuffer computeBuffer = (ComputeBuffer)LuaObject.checkSelf(l); Array data; LuaObject.checkType<Array>(l, 2, out data); computeBuffer.SetData(data); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int GetData(IntPtr l) { int result; try { ComputeBuffer computeBuffer = (ComputeBuffer)LuaObject.checkSelf(l); Array array; LuaObject.checkType<Array>(l, 2, out array); computeBuffer.GetData(array); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int CopyCount_s(IntPtr l) { int result; try { ComputeBuffer computeBuffer; LuaObject.checkType<ComputeBuffer>(l, 1, out computeBuffer); ComputeBuffer computeBuffer2; LuaObject.checkType<ComputeBuffer>(l, 2, out computeBuffer2); int num; LuaObject.checkType(l, 3, out num); ComputeBuffer.CopyCount(computeBuffer, computeBuffer2, num); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_count(IntPtr l) { int result; try { ComputeBuffer computeBuffer = (ComputeBuffer)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, computeBuffer.get_count()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_stride(IntPtr l) { int result; try { ComputeBuffer computeBuffer = (ComputeBuffer)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, computeBuffer.get_stride()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.ComputeBuffer"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.Dispose)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.Release)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.SetData)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.GetData)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.CopyCount_s)); LuaObject.addMember(l, "count", new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.get_count), null, true); LuaObject.addMember(l, "stride", new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.get_stride), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_ComputeBuffer.constructor), typeof(ComputeBuffer)); } }
using Doozy.Engine.UI; using System; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : SingletonBehaviour<GameManager> { public string TitleScene; public string MainGame; public UIView TimerView; public TMP_Text TimerText; public UIView WinContainer; public TMP_Text WinText; //public bool SkipTitle; public bool NeverLose; public bool IsPlayerControllerEnabled; public float TimeRemaining; public float TimeToReset; public delegate void ResetAction(); public static event ResetAction OnReset; public bool[] CheckpointList = new bool[7]; public int LoopCounter; private bool isPlaying; private float startTime; private bool alreadyDead; void Start() { DontDestroyOnLoad(this.gameObject); this.isPlaying = false; this.alreadyDead = true; SceneManager.sceneLoaded += OnSceneLoaded; } public void StartGame() { this.alreadyDead = false; this.LoopCounter = 0; this.IsPlayerControllerEnabled = true; this.TimeRemaining = this.TimeToReset; this.TimerView.Show(); } public void WinGame() { this.isPlaying = false; this.IsPlayerControllerEnabled = false; this.WinContainer.Show(); this.WinText.text = $"You escaped in {this.LoopCounter} loops!"; } public void ReturnToTitle() { this.WinContainer.Hide(); this.IsPlayerControllerEnabled = false; SceneManager.LoadScene(this.TitleScene); } public void QuitGame() { Application.Quit(); } public void ActivateCheckpoint(Checkpoints checkpoint) { this.CheckpointList[(int)checkpoint] = true; } public bool HasCheckpoint(Checkpoints checkpoint) => CheckpointList[(int) checkpoint]; private void ResetGameState() { this.LoopCounter = 0; this.startTime = Time.deltaTime; this.isPlaying = true; this.TimeRemaining = this.TimeToReset; this.IsPlayerControllerEnabled = true; } public void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode) { if (scene.name == "Main") { this.ResetGameState(); this.StartGame(); } } private void Update() { this.TimeRemaining -= Time.deltaTime; this.TimeRemaining = Mathf.Clamp(this.TimeRemaining, 0, this.TimeToReset); if(this.TimeRemaining > 0 && !this.alreadyDead) { float seconds = Mathf.FloorToInt(this.TimeRemaining % 60); float milliseconds = 100 - ((int)(Time.timeSinceLevelLoad * 100f) % 100); this.TimerText.text = String.Format("{0:00}:{1:00}", seconds, milliseconds); } else if (this.TimeRemaining <= 0 && !this.alreadyDead) { this.TimerText.text = "00:00"; this.KillRespawnPlayer(); } } public void KillRespawnPlayer() { if (!NeverLose) { LoopCounter++; IsPlayerControllerEnabled = false; alreadyDead = true; var pdl = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerDeathLoop>(); StartCoroutine(RespawnPlayer(pdl)); } } private IEnumerator RespawnPlayer(PlayerDeathLoop loop) { loop.KillPlayer(); OnReset(); loop.RespawnPlayer(); yield return new WaitForSeconds(2); IsPlayerControllerEnabled = true; alreadyDead = false; TimeRemaining = TimeToReset; } } public enum Checkpoints { None, GunRoomComplete, Room1Complete, Room2Complete, Room34Complete, Room5Complete, RoomFinalComplete }
using System; using System.Collections.Generic; using System.Text; using CSharpLearning.Sort; namespace CSharpLearning.Sort { public class QuickSorter { //快速排序 private static void Quick_sort(int[] s, int l, int r) { if (l < r) { //Swap(s[l], s[(l + r) / 2]); //将中间的这个数和第一个数交换 参见注1 int i = l, j = r, x = s[l]; while (i < j) { while(i < j && s[j] >= x) // 从右向左找第一个小于x的数 j--; if(i < j) s[i++] = s[j]; while(i < j && s[i] < x) // 从左向右找第一个大于等于x的数 i++; if(i < j) s[j--] = s[i]; } s[i] = x; Quick_sort(s, l, i - 1); // 递归调用 Quick_sort(s, i + 1, r); } } private static int PartitionLeftAsPivot(int[] s, int l, int r) { int i = l, j = r, x = s[l]; Console.WriteLine("pivot index {0} : value {1}", l, x); while (i < j) { while (i < j && s[j] >= x) // 从右向左找第一个小于x的数 j--; if (i < j) { s[i++] = s[j]; Console.WriteLine(" " + string.Join(" ", s)); } while (i < j && s[i] < x) // 从左向右找第一个大于等于x的数 i++; if (i < j) { s[j--] = s[i]; Console.WriteLine(" " + string.Join(" ", s)); } } s[i] = x; Console.WriteLine(" " + string.Join(" ", s)); return i; } private static int PartitionMiddleAsPivot(int[] s, int l, int r) { Helper.Swap(ref s[l], ref s[(l + r) / 2]); //将中间的这个数和第一个数交换 int i = l, j = r, x = s[l]; Console.WriteLine("pivot index {0} : value {1}", l, x); while (i < j) { while (i < j && s[j] >= x) // 从右向左找第一个小于x的数 j--; if (i < j) { s[i++] = s[j]; Console.WriteLine(" " + string.Join(" ", s)); } while (i < j && s[i] < x) // 从左向右找第一个大于等于x的数 i++; if (i < j) { s[j--] = s[i]; Console.WriteLine(" " + string.Join(" ", s)); } } s[i] = x; Console.WriteLine(" " + string.Join(" ", s)); return i; } private static void Qsort_LeftAsPivot(int[] input, int left, int right) { if (left < right) { int i = PartitionLeftAsPivot(input, left, right);//先成挖坑填数法调整 Qsort_LeftAsPivot(input, left, i - 1); // 递归调用 Qsort_LeftAsPivot(input, i + 1, right); } } private static void Qsort_MiddleAsPivot(int[] input, int left, int right) { if (left < right) { int i = PartitionMiddleAsPivot(input, left, right); Qsort_MiddleAsPivot(input, left, i - 1); Qsort_MiddleAsPivot(input, i + 1, right); } } private static void QuickSort_RightAsPivot(int[] input, int left, int right) { if (left < right) { int i = PartitionRightAsPivot(input, left, right); QuickSort_RightAsPivot(input, left, i - 1); QuickSort_RightAsPivot(input, i + 1, right); } } private static void quickSort(int[] number, int left, int right) { if(left < right) { int iPivot = number[(left+right)/2]; Console.WriteLine("pivot index {0} : value {1}", (left+right)/2, iPivot); int i = left - 1; int j = right + 1; while(true) { while (number[++i] < iPivot) ; // 向右找 //遇到iPivot也跳出,把iPivot交换到j while (number[--j] > iPivot) ; // 向左找 if(i >= j) break; Helper.Swap(ref number[i], ref number[j]); Console.WriteLine(" " + string.Join(" ",number)); } //pivot 参与交换,写不成 partition 函数 quickSort(number, left, i-1); // 對左邊進行遞迴 quickSort(number, j+1, right); // 對右邊進行遞迴 } } private static int PartitionRightAsPivot(int[] number, int left, int right) { int iPivot = number[right]; Console.WriteLine("pivot index {0} : value {1}", right, iPivot); int i = left-1; for (int j = left; j < right ; j++) { if (number[j] <= iPivot) { i++; if (i != j) { Helper.Swap(ref number[i], ref number[j]); Console.WriteLine(" " + string.Join(" ", number)); } } } Helper.Swap(ref number[i+1], ref number[right]); return i+1; } public static void Quick_sort(int[] array) { //Quick_sort(array, 0, array.Length - 1); //quickSort(array, 0, array.Length - 1); //Qsort_LeftAsPivot(array, 0, array.Length - 1); // Qsort_MiddleAsPivot(array, 0, array.Length - 1); QuickSort_RightAsPivot(array, 0, array.Length - 1); } public static void Run() { int[] a = { 11, 49, 53, 86, 22, 27, 98, 88, 91, 100 }; //int[] a = { 10,9,8,7,6,5,4,3,2,1}; //int[] a = { 1,2,3,4,5,6,7,8,9,10 }; //int[] a = new int[] {4, 2, 1, 6, 3, 6, 0, -5, 1, 1}; //int[] a = { 2, 9, 5, 1, 8, 3, 6, 4, 7, 0 }; Console.WriteLine(string.Join(" ", a)); Quick_sort(a); Console.WriteLine(string.Join(" ", a)); Console.ReadKey(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using TechTalk.SpecFlow; using ZiZhuJY.Helpers; namespace ZiZhuJY.Core.Tests { [Binding] public class ZodiacYearsSteps { private DateTime datetime; private ZodiacYears actualZodiacGot; [Given(@"the date is ""(.*)""")] public void GivenTheDateIs(string dateString) { datetime = DateTime.Parse(dateString); actualZodiacGot = ZodiacYear.GetZodiac(datetime); } [Then(@"the Zodiac is ""(.*)""")] public void ThenTheZodiacIs(string expectedZodiac) { Assert.AreEqual(EnumHelper.ParseEnum<ZodiacYears>(expectedZodiac), actualZodiacGot); } [Given(@"the Lunar Year is (.*)")] public void GivenTheLunarYearIs(int lunarYear) { actualZodiacGot = ZodiacYear.GetZodiac(lunarYear); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AvaliacaoFinalCSharp.Features.Country { public interface ICountryParser { Dictionary<string, string> Parse(string textFromSource); } }
using System; namespace ASCOM.microlux { public class RingBuffer { private readonly byte[] buffer; private int writeIndex = 0, readIndex = 0, size = 0; public RingBuffer(int capacity) { buffer = new byte[capacity]; } public int GetReadIndex() { return readIndex; } public bool Sync(byte[] marker) { var toCheck = size - (marker.Length * 2); for (var i = 0; i < toCheck; i++) { var start = readIndex + i; for (var j = 0; j < marker.Length; j++) { if (buffer[(start + (j << 1)) % buffer.Length] != marker[j]) { goto outer; } } Consume(i); return true; outer: { // do nothing, this is used as a marker to break inner loop then continue outer loop } } return false; } public void Consume(int length) { if (size >= length) { readIndex = (readIndex + length) % buffer.Length; size -= length; } } public void Write(byte[] data, int offset, int length) { if (writeIndex + length > buffer.Length) { var toWrite = buffer.Length - writeIndex; Write(data, 0, toWrite); Write(data, toWrite, length - toWrite); return; } if (size + length > buffer.Length) { Consume(length); } Array.Copy(data, offset, buffer, writeIndex, length); writeIndex = (writeIndex + length) % buffer.Length; size += length; } public byte[] Read(int length) { return Read(length, true); } public byte[] Read(int length, bool consume) { var data = new byte[length]; if (readIndex + length > buffer.Length) { var toRead = buffer.Length - readIndex; Array.Copy(buffer, readIndex, data, 0, toRead); Array.Copy(buffer, 0, data, toRead, length - toRead); } else { Array.Copy(buffer, readIndex, data, 0, length); } if (consume) Consume(length); return data; } public int Available() { return size; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; using System.Windows.Forms; using System.Drawing; namespace WallPaperChangerV2 { public class ScreenFetcher : List<ScreenInfo> { //Size of the monitor space private Size size; //Offset point to compensate for the primary screen not being top left private Point offset; public Size Size { get { return size; } set { size = value; } } public Point Offset { get { return offset; } set { offset = value; } } /// <summary> /// Default Constructor /// </summary> public ScreenFetcher() { getScreens(); } /// <summary> /// Refreshes data stored in this class with current data from the Screens class. /// </summary> public void RefreshScreens() { this.Clear(); getScreens(); } /// <summary> /// Gets all the screens for the system and saves it to the screens list. /// </summary> private void getScreens() { // 'Magic' that clears the Screen Static class so it can refresh with current information typeof( Screen ).GetField( "screens", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic ).SetValue( null, null ); Screen[] systemScreens = Screen.AllScreens; offset = new Point( 0, 0 ); //Determine 0,0 and Height/Width of screen area. foreach ( Screen screen in systemScreens ) { if ( screen.Bounds.Left < Offset.X ) { offset.X = screen.Bounds.Left; } if ( screen.Bounds.Top < Offset.Y ) { offset.Y = screen.Bounds.Top; } if ( screen.Bounds.Right > size.Width ) { size.Width = screen.Bounds.Right; } if ( screen.Bounds.Bottom > size.Height ) { size.Height = screen.Bounds.Bottom; } } //Adjust size to include offset size.Width = size.Width - offset.X; size.Height = size.Height - offset.Y; //Adds the screen foreach ( Screen screen in systemScreens ) { Point bitmapLocation = new Point( screen.Bounds.Location.X - Offset.X, screen.Bounds.Location.Y - Offset.Y ); ScreenInfo currentScreen = new ScreenInfo( screen.Bounds.Size, screen.Bounds.Location, bitmapLocation ); this.Add( currentScreen ); } } } }
using LuizalabsWishesManager.Services; using LuizalabsWishesManager.Shared; using NUnit.Framework; using RestSharp; namespace Tests { public class ProductTest { private IProductService _service; [SetUp] public void Setup(IProductService service) { _service = service; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using myDLL; namespace 主程序202104 { public partial class 数据处理excel : Form { [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); string inipath = AppDomain.CurrentDomain.BaseDirectory + "config.ini"; /// <summary> /// 写入INI文件 /// </summary> /// <param name="Section">项目名称(如 [TypeName] )</param> /// <param name="Key">键</param> /// <param name="Value">值</param> public void IniWriteValue(string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, this.inipath); } /// <summary> /// 读出INI文件 /// </summary> /// <param name="Section">项目名称(如 [TypeName] )</param> /// <param name="Key">键</param> public string IniReadValue(string Section, string Key) { StringBuilder temp = new StringBuilder(500); int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath); return temp.ToString(); } /// <summary> /// 验证文件是否存在 /// </summary> /// <returns>布尔值</returns> public bool ExistINIFile() { return File.Exists(inipath); } public 数据处理excel() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); dialog.Description = "请选择所在文件夹"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (string.IsNullOrEmpty(dialog.SelectedPath)) { MessageBox.Show(this, "文件夹路径不能为空", "提示"); return; } } textBox1.Text = dialog.SelectedPath; } private void button1_Click(object sender, EventArgs e) { System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); dialog.Description = "请选择所在文件夹"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string[] files = Directory.GetFiles(dialog.SelectedPath + @"\", "*.xlsx"); foreach (string file in files) { ListViewItem lv1 = listView1.Items.Add(listView1.Items.Count.ToString()); //使用Listview展示数据 lv1.SubItems.Add(file); lv1.SubItems.Add("未开始"); } } } bool xuanze = false; private void button7_Click(object sender, EventArgs e) { if (xuanze == false) { for (int i = 0; i < listView1.Items.Count; i++) { listView1.Items[i].Checked = true; } xuanze = true; } else { for (int i = 0; i < listView1.Items.Count; i++) { listView1.Items[i].Checked = false; } xuanze = false; } } /// <summary> /// 获取时间戳毫秒 /// </summary> /// <returns></returns> public string GetTimeStamp() { TimeSpan tss = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); long a = Convert.ToInt64(tss.TotalMilliseconds); return a.ToString(); } private void button6_Click(object sender, EventArgs e) { if (textBox1.Text != "") { System.Diagnostics.Process.Start(textBox1.Text); } } ArrayList lists = new ArrayList(); public void run() { for (int i = 0; i < listView1.CheckedItems.Count; i++) { string filename = listView1.CheckedItems[i].SubItems[1].Text; if (!lists.Contains(filename)) { lists.Add(filename); listView1.CheckedItems[i].SubItems[2].Text = "正在读取..."; try { DataTable dt = method.ExcelToDataTable(filename, true); MessageBox.Show(dt.Rows.Count.ToString()); if (checkBox1.Checked == true) { string txtname = textBox1.Text + "\\" +textBox2.Text+i+ ".txt"; FileStream fs1 = new FileStream(txtname, FileMode.Append, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fs1); for (int j = 2; j < dt.Rows.Count; j++) { string value = ""; if (filename.Contains("高级")) { value = dt.Rows[j][21].ToString().Replace(";", "\r\n").Trim(); } else { value = dt.Rows[j][14].ToString().Replace(";", "\r\n").Trim(); } if (value != "" && value != "-") { sw.WriteLine(value); } } sw.Close(); fs1.Close(); sw.Dispose(); listView1.CheckedItems[i].SubItems[2].Text = "已完成"; } if (checkBox2.Checked == true) { string txtname = textBox1.Text + "\\"+ textBox2.Text+i + ".txt"; FileStream fs1 = new FileStream(txtname, FileMode.Append, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fs1); for (int j = 2; j < dt.Rows.Count; j++) { string value = ""; if (filename.Contains("高级")) { value = dt.Rows[j][24].ToString().Replace(";", "\r\n").Trim(); } else { value = dt.Rows[j][19].ToString().Replace(";", "\r\n").Trim(); } if (value != "" && value !="-") { sw.WriteLine(value); } } sw.Close(); fs1.Close(); sw.Dispose(); listView1.CheckedItems[i].SubItems[2].Text = "已完成"; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } private void button3_Click(object sender, EventArgs e) { IniWriteValue("values", "path", textBox1.Text.Trim()); for (int i = 0; i < 10; i++) { Thread thread = new Thread(new ThreadStart(run)); thread.Start(); Control.CheckForIllegalCrossThreadCalls = false; } } private void 数据处理excel_FormClosing(object sender, FormClosingEventArgs e) { DialogResult dr = MessageBox.Show("确定要关闭吗?", "关闭", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dr == DialogResult.OK) { // Environment.Exit(0); System.Diagnostics.Process.GetCurrentProcess().Kill(); } else { e.Cancel = true;//点取消的代码 } } private void 数据处理excel_Load(object sender, EventArgs e) { if (ExistINIFile()) { textBox1.Text = IniReadValue("values", "path"); } } private void button5_Click(object sender, EventArgs e) { listView1.Items.Clear(); } } }
using System.Collections.Generic; namespace Plus.Communication.Packets.Outgoing.Users { public class IgnoredUsersComposer : MessageComposer { public IReadOnlyCollection<string> IgnoredUsers { get; } public IgnoredUsersComposer(IReadOnlyCollection<string> ignoredUsers) : base(ServerPacketHeader.IgnoredUsersMessageComposer) { IgnoredUsers = ignoredUsers; } public override void Compose(ServerPacket packet) { packet.WriteInteger(IgnoredUsers.Count); foreach (string username in IgnoredUsers) { packet.WriteString(username); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.Clustering { public class ClusterCollection { public ClusterCollection() { this.Clusters = new List<Cluster>(); } public ClusterCollection(IList<Cluster> clusters) { this.Clusters = clusters; } public IList<Cluster> Clusters { get; private set; } public int Count { get { return this.Clusters.Count; } } } }
using System; using Microsoft.Extensions.DependencyInjection; using HacktoberfestProject.Web.Data; using HacktoberfestProject.Web.Models.Entities; namespace HacktoberfestProject.Tests.Data { public class TableContextTests { private readonly ITableContext _context; private TrackerEntryEntity _entityToRemove; private readonly TrackerEntryEntity _trackerEntryEntity; public TableContextTests(ITableContext context) { _context = context; _trackerEntryEntity = new TrackerEntryEntity { Username = Constants.USERNAME, Url = Constants.URL, Status = null }; } public void TestInsert() { _ = _context.InsertOrMergeEntityAsync(_trackerEntryEntity).Result; } public void TestRetrieve() { _entityToRemove = _context.RetrieveEnitityAsync(_trackerEntryEntity).Result; } public void TestDelete() { _context.DeleteEntity(_entityToRemove); } public static void RunTableStorageTests(IServiceCollection services) { IServiceProvider sp = services.BuildServiceProvider(); var ctt = new TableContextTests(sp.GetService<ITableContext>()); ctt.TestInsert(); ctt.TestRetrieve(); ctt.TestDelete(); } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nim { class GameEngine { private const int MAX_ROWS = 3; private int[] _board; private bool isTurn; private State currentState; private State _endState = new State(new int[] { 0, 0, 0 }); private List<State> gameHistory = new List<State>(); private UI ui = new UI(); public GameEngine() { isTurn = StartingTurn(); _board = new int[MAX_ROWS] { 3, 5, 7 }; currentState = new State(_board); } public void PlayComputerVsPlayer() { bool gameGoing = true; while (gameGoing) { BoardView.PrintBoard(currentState.RowValues); if (currentState.RowValues[0] > 0 || currentState.RowValues[1] > 0 || currentState.RowValues[2] > 0) { if (!AI.StateTree.ContainsKey(currentState)) { AI.StateTree.Add(currentState, GeneratePossibleMoves(currentState)); } SwitchTurn(); if (!isTurn) { PossibleMove playersMove = new PossibleMove(ui.PromptRow(currentState), ui.PromptRemoval(currentState)); currentState = playersMove.RemovePieces(currentState.RowValues); } else { var possibleMoves = GeneratePossibleMoves(currentState); currentState = AI.PerformMove(currentState); gameHistory.Add(currentState); } } else { CalculateSumScores(); AI.CalculateAverage(gameHistory); ui.DisplayGameOver(isTurn); gameGoing = !gameGoing; } } } public void PlayComputerVsComputer() { bool gameGoing = true; while (gameGoing) { BoardView.PrintBoard(currentState.RowValues); if (currentState.RowValues[0] > 0 || currentState.RowValues[1] > 0 || currentState.RowValues[2] > 0) { AI.StateTree.Add(currentState, GeneratePossibleMoves(currentState)); SwitchTurn(); gameHistory.Add(currentState); currentState = AI.PerformMove(currentState); } else { CalculateSumScores(); AI.CalculateAverage(gameHistory); ui.DisplayGameOver(isTurn); gameGoing = !gameGoing; } } } public void PlayerVsPlayer() { bool gameGoing = true; while (gameGoing) { BoardView.PrintBoard(currentState.RowValues); if (currentState.RowValues[0] > 0 || currentState.RowValues[1] > 0 || currentState.RowValues[2] > 0) { SwitchTurn(); PossibleMove move = new PossibleMove(ui.PromptRow(currentState), ui.PromptRemoval(currentState)); currentState = move.RemovePieces(currentState.RowValues); } else { ui.DisplayGameOver(isTurn); gameGoing = !gameGoing; } } } private void CalculateSumScores() { gameHistory.Add(_endState); bool stateIsPositive = false; int negCounter = 0; int negDenominator = gameHistory.Count / 2; int posDenominator = ((gameHistory.Count - negDenominator) - 1); int posCounter = 0; for (int j = gameHistory.Count; j > 1; j--) { foreach (var item in AI.StateTree[gameHistory[j]]) { if (stateIsPositive) { item.Key.SumScore = new Tuple<int, int>(--negCounter, negDenominator); } else { item.Key.SumScore = new Tuple<int, int>(++posCounter, posDenominator); } item.Key.NumberOccured++; } } } public Dictionary<PossibleMove, double> GeneratePossibleMoves(State currentState) { Dictionary<PossibleMove, double> statesPosMoves = new Dictionary<PossibleMove, double>(); int removalLimit = 3; for (int i = 1; i <= MAX_ROWS; i++) { if (i == 2) { removalLimit = 5; } else if (i == 3) { removalLimit = 7; } for (int j = 1; j < removalLimit; j++) { PossibleMove posMove = new PossibleMove(i, j); if (!statesPosMoves.ContainsKey(posMove)) { statesPosMoves.Add(posMove, 0); } } } return statesPosMoves; } public bool StartingTurn() { Random rand = new Random(); return rand.Next(2) == 0; } public bool SwitchTurn() { ui.DisplayPlayerTurn(isTurn); isTurn = !isTurn; return isTurn; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WallCommentMicroService.Models { public class Post { public Guid Id { get; set; } public DateTime DateCreated { get; set; } public string Text { get; set; } public decimal Rating { get; set; } public int Views { get; set; } public byte[] Attachment { get; set; } public string Location { get; set; } public List<Guid> Labels { get; set; } public bool Active { get; set; } public string UserId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using System.IO; namespace Task2 { class Json { public static void Serialization(IGambling[] games) { var fn = Path.Combine(Environment.CurrentDirectory, "objects.json"); var init_array = new JsonSerializerSettings() { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Auto }; string json = JsonConvert.SerializeObject(games, init_array); File.WriteAllText(fn, json); var fnstr = File.ReadAllText(fn); var list = JsonConvert.DeserializeObject<IGambling[]>(fnstr, init_array); Console.WriteLine("Games to play:"); foreach (var l in list) Console.WriteLine($"{l.Name}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ItemEdit.Models { public class SysConfig { public string DefaultPath { get; set; } } }
using innovation4austria.dataaccess; using log4net; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace innovation4austria.logic { public class AusstattungVerwaltung { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Lädt alle Ausstattungen aus der Datenbank /// </summary> /// <returns>Liste aller Ausstattungen oder null bei Fehler</returns> public static List<Ausstattung> LadeAlle() { log.Debug("LadeAlle()"); List<Ausstattung> ausstattungListe = null; using (var context = new InnovationContext()) { try { ausstattungListe = context.AlleAusstattungen.ToList(); } catch (Exception ex) { log.Error("Exception bei LadeAlle aufgetreten", ex); if (ex.InnerException != null) { log.Error(ex.InnerException); } #if DEBUG Debugger.Break(); #endif } return ausstattungListe; } } /// <summary> /// Speichert Ausstattungen (inklusive Anzahl) zu einem Raum in der Datenbank /// </summary> /// <param name="raumId">die Id des Raumes</param> /// <param name="ausstattungsListe">das Dictionary, das die ID der Ausstattung und die Anzahl der Ausstattungen beinhaltet</param> /// <returns>true wenn erfolgreich, sonst false</returns> public static bool AusstattungenZuRaumSpeichern(int raumId, Dictionary<int, int> ausstattungsListe) { log.Debug("AusstattungenZuRaumSpeichern()"); bool erfolgreich = false; if (raumId <= 0) { throw new ArgumentException("raumId muss eine gültige Id sein > 0"); } using (var context = new InnovationContext()) { try { IEnumerable<Raumausstattung> raumAusstattungen = context.AlleRaumausstattungen.Where(x => x.raum_id == raumId); //wenn der Raum bereits Ausstattungen zugewiesen hat if (raumAusstattungen != null) { log.Info($"Der Raum {raumId} hat bereits {raumAusstattungen.Count()} Raumausstattungen"); List<int> ausstattungIds = raumAusstattungen.Select(x => x.ausstattung_id).ToList(); //filtere das übergebene Ausstattungsdictionary nach AusstattungIds, die es bereits in dem Raum gibt und die Anzahl > 0 ist IEnumerable<KeyValuePair<int, int>> bereitsVorhandeneAusstattungen = ausstattungsListe.Where(x => ausstattungIds.Contains(x.Key) && x.Value != 0); //filtere das übergebene Ausstattungsdictionary nach AusstattungIds, die es bereits in dem Raum gibt und deren Anzahl 0 ist IEnumerable<KeyValuePair<int, int>> entfernteAusstattungen = ausstattungsListe.Where(x => ausstattungIds.Contains(x.Key) && x.Value == 0); //filtere das übergebene Ausstattungsdictionary nach AusstattungIds, die es noch nicht in dem Raum gibt und die Anzahl > 0 ist IEnumerable<KeyValuePair<int, int>> neueAusstattungen = ausstattungsListe.Where(x => !ausstattungIds.Contains(x.Key) && x.Value != 0); foreach (var ausstattung in bereitsVorhandeneAusstattungen) { log.Info($"Raumausstattung mit ID {ausstattung.Key} - Anzahl bekommt Wert {ausstattung.Value}"); Raumausstattung gefundeneAusstattung = raumAusstattungen.FirstOrDefault(x => x.ausstattung_id == ausstattung.Key); gefundeneAusstattung.anzahl = ausstattung.Value; } foreach (var ausstattung in entfernteAusstattungen) { Raumausstattung gefundeneAusstattung = raumAusstattungen.FirstOrDefault(x => x.ausstattung_id == ausstattung.Key); context.AlleRaumausstattungen.Remove(gefundeneAusstattung); } foreach (var ausstattung in neueAusstattungen) { log.Info($"Es wird ein neuer Datensatz Raumausstattung erzeugt: AusstattungsIds {ausstattung.Key} - Anzahl {ausstattung.Value}"); Raumausstattung neueRaumausstattung = new Raumausstattung(); neueRaumausstattung.anzahl = ausstattung.Value; neueRaumausstattung.ausstattung_id = ausstattung.Key; neueRaumausstattung.raum_id = raumId; context.AlleRaumausstattungen.Add(neueRaumausstattung); } } else { log.Info($"Der Raum {raumId} hat noch keine Raumausstattungen"); foreach (var ausstattung in ausstattungsListe.Where(x => x.Value != 0)) { Raumausstattung neueRaumausstattung = new Raumausstattung(); neueRaumausstattung.anzahl = ausstattung.Value; neueRaumausstattung.ausstattung_id = ausstattung.Key; neueRaumausstattung.raum_id = raumId; context.AlleRaumausstattungen.Add(neueRaumausstattung); } } context.SaveChanges(); erfolgreich = true; } catch (Exception ex) { log.Error("Exception bei AusstattungenZuRaumSpeichern aufgetreten", ex); if (ex.InnerException != null) { log.Error(ex.InnerException); } #if DEBUG Debugger.Break(); #endif } } return erfolgreich; } } }
namespace OmniGui { public class Pen { public Pen(Brush brush, double thickness) { Brush = brush; Thickness = thickness; } public Brush Brush { get; set; } public double Thickness { get; set; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.Services.Sitemap { public enum SitemapChangeFrequency { Always, Hourly, Daily, Weekly, Monthly, Yearly, Never } }
using Domain.Common.Rules; using Sample.Domain; using Sample.Domain.Rules; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace Sample.WebApi.Rules { public class RuleFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var type = actionContext.ControllerContext.Controller.GetType(); type = type.BaseType.GetGenericArguments().First(); var ruleFilterType = typeof(RuleFilter<>).MakeGenericType(type); dynamic ruleFilter = Activator.CreateInstance(ruleFilterType); var item = actionContext.ActionArguments.First().Value; dynamic controller = actionContext.ControllerContext.Controller; var domain = controller.Domain; ruleFilterType.GetMethod("Before").Invoke(ruleFilter, new[]{ domain, item}); } } }
using Jieshai.Cache.CacheManagers; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Jieshai.Cache { public class CacheMapper : ObjectMapper { public CacheMapper(CacheContainer cacheContainer) : base() { this.CacheContainer = cacheContainer; } public CacheContainer CacheContainer { set; get; } protected override bool Map(object source, Type resultType, out object result) { Type sourceType = source.GetType(); if (this.KeyToCache(source, resultType, out result)) { return true; } else if (this.CacheToKey(source, resultType, out result)) { return true; } else if (this.ModelToCache(source, resultType, out result)) { return true; } return base.Map(source, resultType, out result); } private bool KeyToCache(object source, Type resultType, out object result) { result = null; if ((source is string || source is int) && !ReflectionHelper.IsIList(resultType)) { if (this.CacheContainer.Contains(resultType)) { object key = source; result = this.CacheContainer.Get(key, resultType); return true; } } else if (source is string && ReflectionHelper.IsIList(resultType)) { Type resultItemType = ReflectionHelper.GetCollectionItemType(resultType); if (this.CacheContainer.Contains(resultItemType)) { ICacheManager manager = this.CacheContainer.GetManager(resultItemType); string formatedKey = source as string; string[] keys = formatedKey.Split(','); result = Activator.CreateInstance(resultType); IList resultList = result as IList; foreach (string key in keys) { resultList.Add(manager.Get(key)); } return true; } } return false; } private bool CacheToKey(object source, Type resultType, out object result) { result = null; Type sourceType = source.GetType(); if (!ReflectionHelper.IsIList(sourceType) && (resultType == typeof(string) || resultType == typeof(int))) { if (resultType == typeof(int) && source is IIdProvider) { result = (source as IIdProvider).Id; return true; } else if (resultType == typeof(string) && source is IGuidProvider) { result = (source as IGuidProvider).Guid; return true; } else if (resultType == typeof(string) && source is ICodeProvider) { result = (source as ICodeProvider).Code; return true; } return false; } else if (ReflectionHelper.IsIList<IIdProvider>(sourceType) && resultType == typeof(string)) { List<object> keyList = new List<object>(); IList list = source as IList; foreach (object obj in list) { object key = key = (source as IIdProvider).Id; keyList.Add(key); } result = string.Join(",", keyList); return true; } return false; } private bool ModelToCache(object source, Type resultType, out object result) { result = null; Type sourceType = source.GetType(); if ((ReflectionHelper.Is<IIdProvider>(sourceType) || ReflectionHelper.Is<ICodeProvider>(sourceType) || ReflectionHelper.Is<IGuidProvider>(sourceType)) && !this.CacheContainer.Contains(sourceType) && this.CacheContainer.Contains(resultType)) { if (source is IIdProvider) { IIdProvider idProviderSource = source as IIdProvider; result = this.CacheContainer.Get(idProviderSource.Id, resultType); return true; } else if (source is IGuidProvider) { IGuidProvider guidProviderSource = source as IGuidProvider; result = this.CacheContainer.Get(guidProviderSource.Guid, resultType); return true; } else if (source is ICodeProvider) { ICodeProvider codeProviderSource = source as ICodeProvider; result = this.CacheContainer.Get(codeProviderSource.Code, resultType); return true; } } return false; } } public class TCacheMapper<TargetType, SourceType> : CacheMapper { public TCacheMapper(CacheContainer cacheContainer) : base(cacheContainer) { } public virtual TargetType Map(SourceType model) { if (model == null) { return default(TargetType); } ConstructorInfo cotr = ReflectionHelper.GetConstructor(typeof(TargetType)); ParameterInfo[] cotrParams = cotr.GetParameters(); if (cotrParams.Length > 1) { throw new Exception("无法加载多个参数列表的对象!"); } else if (cotrParams.Length == 1) { object infoArgs = this.Map(model, cotrParams[0].ParameterType); TargetType obj = this.Map<TargetType>(infoArgs); return obj; } else { TargetType obj = this.Map<TargetType>(model); return obj; } } public virtual void Map(TargetType target, SourceType source) { this.Map(target, source); } } }
namespace Triton.Game.Mapping { using System; public enum localRenderMask { None, Texture, Edges } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ButtonResume : MonoBehaviour { private void Awake() { Button button = GetComponent<Button>(); if(button) button.onClick.AddListener(OnClickAction); } /// <summary> /// [Delegate] Resume game from pause. /// </summary> public void OnClickAction() { GameAppManager gameAppManager = FindObjectOfType<GameAppManager>(); if(gameAppManager) gameAppManager.UnPauseGame(); } }
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace SkillsGardenApi.Utils { public static class ConfigurationExtension { public static T GetClassValueChecked<T>(this IConfiguration Configuration, string Key, T Default, ILogger Logger) where T : class { T Value = Configuration.GetValue<T>(Key); if (Value == null) { Logger.LogError($"Configuration key {Key} not found. Check your configuration!"); return Default; } return Value; } public static T GetValueChecked<T>(this IConfiguration Configuration, string Key, T Default, ILogger Logger) where T : struct { T? Value = Configuration.GetValue<T?>(Key); if (!Value.HasValue) { Logger.LogError($"Configuration key {Key} not found. Check your configuration!"); return Default; } return Value.Value; } } }
namespace Dotnet.Script.NuGetMetadataResolver { using System; using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; /// <summary> /// A class that is capable of running a command. /// </summary> public class CommandRunner : ICommandRunner { private readonly ILogger logger; private readonly StringBuilder lastStandardErrorOutput = new StringBuilder(); private readonly StringBuilder lastProcessOutput = new StringBuilder(); /// <summary> /// Initializes a new instance of the <see cref="CommandRunner"/> class. /// </summary> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> used to create an <see cref="ILogger"/> instance.</param> public CommandRunner(ILoggerFactory loggerFactory) { logger = loggerFactory.CreateLogger<CommandRunner>(); } /// <inheritdoc /> public void Execute(string commandPath, string arguments) { lastStandardErrorOutput.Clear(); logger.LogInformation($"Executing {commandPath} {arguments}"); var startInformation = CreateProcessStartInfo(commandPath, arguments); var process = CreateProcess(startInformation); RunAndWait(process); logger.LogInformation(lastProcessOutput.ToString()); if (process.ExitCode != 0) { logger.LogError(lastStandardErrorOutput.ToString()); throw new InvalidOperationException($"The command {commandPath} {arguments} failed to execute"); } } private static ProcessStartInfo CreateProcessStartInfo(string commandPath, string arguments) { var startInformation = new ProcessStartInfo(commandPath); startInformation.CreateNoWindow = true; startInformation.Arguments = arguments; startInformation.RedirectStandardOutput = true; startInformation.RedirectStandardError = true; startInformation.UseShellExecute = false; return startInformation; } private Process CreateProcess(ProcessStartInfo startInformation) { var process = new Process(); process.StartInfo = startInformation; process.ErrorDataReceived += (s, a) => { if (!string.IsNullOrWhiteSpace(a.Data)) { lastStandardErrorOutput.AppendLine(a.Data); } }; process.OutputDataReceived += (s, a) => { lastProcessOutput.AppendLine(a.Data); }; return process; } private static void RunAndWait(Process process) { process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); } } }
namespace TutteeFrame2.Model { public class Account { private string iD; private string teacherID; private string password; public string ID { get => iD; set => iD = value; } public string TeacherID { get => teacherID; set => teacherID = value; } public string Password { get => password; set => password = value; } public Account() { } public Account(string _id, string _teacherId, string _password) { iD = _id; teacherID = _teacherId; password = _password; } public Account(string _teacherId, string _password) { iD = ""; teacherID = _teacherId; password = _password; } } }
using System.Collections.Generic; namespace KnowledgeTester.Models { public class AdminPanelModel { public string Category_NewName { get; set; } public string Subcategory_NewName { get; set; } public string Subcategory_Cat { get; set; } public IEnumerable<CategoryModel> Categories { get; set; } } }
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using YCSOrderSystem.Models; namespace YCSOrderSystem.Controllers { public class SupplierController : Controller { YCSDatabaseEntities db = new YCSDatabaseEntities(); // GET: Supplier public ActionResult Index() { if(User.Identity.IsAuthenticated) { String UserRole = SUserRole(); if(UserRole != "Customer") { ViewBag.displayMenu = "yes"; var supps = db.Suppliers.ToList(); return View(supps); } } return RedirectToAction("Index", "Users"); } public String SUserRole() { if (User.Identity.IsAuthenticated) { var user = User.Identity; ApplicationDbContext context = new ApplicationDbContext(); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var s = UserManager.GetRoles(user.GetUserId()); if (s[0].ToString() == "Admin") { return "Admin"; } else if (s[0].ToString() == "Manager") { return "Manager"; } else if (s[0].ToString() == "Employee") { return "Employee"; } else { return "Customer"; } } return "Customer"; } public ActionResult Create() { if(User.Identity.IsAuthenticated) { if(SUserRole() != "Customer") { ViewBag.displayMenu = "yes"; return View(); } } return RedirectToAction("Index", "Users"); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "SuppName, Address, Contact, Email")]Supplier supplier) { if (SUserRole() != "Customer" && SUserRole() != null) { ViewBag.displayMenu = "Yes"; } try { if(ModelState.IsValid) { db.Suppliers.Add(supplier); db.SaveChanges(); return RedirectToAction("Index"); } } catch(DataException ex) { ModelState.AddModelError("", "Unable To Save Changes, Try Again"); string emessage = ex.InnerException.Message.ToString(); string eemessage = ex.InnerException.InnerException.Message.ToString(); } return View(supplier); } public ActionResult Details(int? id) { if (SUserRole() != "Customer" && SUserRole() != null) { ViewBag.displayMenu = "Yes"; } if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Supplier supp = db.Suppliers.Find(id); if(supp == null) { return HttpNotFound(); } return View(supp); } [HttpGet] public ActionResult Delete(int? id, bool? saveChangesError=false) { if (SUserRole() != "Customer" && SUserRole() != null) { ViewBag.displayMenu = "Yes"; } if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if(saveChangesError.GetValueOrDefault()) { ViewBag.ErrorMessage = "Delete Failed, Try Again"; } Supplier supp = db.Suppliers.Find(id); if(supp == null) { return HttpNotFound(); } return View(supp); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id) { if (SUserRole() != "Customer" && SUserRole() != null) { ViewBag.displayMenu = "Yes"; } try { Supplier supp = db.Suppliers.Find(id); db.Suppliers.Remove(supp); db.SaveChanges(); } catch(DataException) { return RedirectToAction("Delete", new { id = id, saveChangesError = true }); } return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebEditor { public class ApplicationManager { private static ApplicationManager _instance; public static ApplicationManager Instance { get { if(_instance == null) { _instance = new ApplicationManager(); } return _instance; } } private string _prevSelectedPage = ""; private bool _isEdited = false; private ApplicationManager() { } public void Initialize() { } public void OnPageChanged(MainViewModel model, string selectedPage) { if (_prevSelectedPage.Equals(selectedPage)) return; if (_isEdited) { // Show unsaved changes prompt } string filepath = "References/" + selectedPage + ".json"; model.ActiveModel = PageViewModel.FromJson(filepath); _prevSelectedPage = selectedPage; } public void OnContentChanged() { _isEdited = true; } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace WebDataDemo.Data.Migrations; public partial class StoredProcs : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql( @" EXEC ('CREATE PROCEDURE ListAuthors AS SELECT Id, Name FROM Authors ')"); migrationBuilder.Sql( @" EXEC ('CREATE PROCEDURE ListAuthorsWithCourses @AuthorId int AS SELECT a.Id, a.Name, ca.RoyaltyPercentage, ca.CourseId, ca.AuthorId, c.Title FROM Authors a LEFT JOIN CourseAuthor ca ON a.Id = ca.AuthorId LEFT JOIN Courses c ON c.Id = ca.CourseId WHERE a.Id = @AuthorId ')"); migrationBuilder.Sql( @" EXEC ('CREATE PROCEDURE ListAuthorsWithCoursesMulti @AuthorId int AS SELECT a.Id, a.Name FROM Authors a WHERE Id = @AuthorId; SELECT ca.RoyaltyPercentage, ca.CourseId, ca.AuthorId, c.Title FROM CourseAuthor ca INNER JOIN Courses c ON c.Id = ca.CourseId WHERE ca.AuthorId = @AuthorId')"); migrationBuilder.Sql( @" EXEC ('CREATE PROCEDURE InsertAuthor @name varchar(100) AS INSERT Authors (name) VALUES (@name);SELECT CAST(scope_identity() AS int);')"); migrationBuilder.Sql( @" EXEC ('CREATE PROCEDURE DeleteAuthor @AuthorId int AS DELETE Authors WHERE Id = @AuthorId;')"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.Sql( @" EXEC ('DROP PROCEDURE ListAuthors'); EXEC ('DROP PROCEDURE ListAuthorsWithCourses') EXEC ('DROP PROCEDURE ListAuthorsWithCoursesMulti') EXEC ('DROP PROCEDURE InsertAuthor') EXEC ('DROP PROCEDURE DeleteAuthors') "); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OfficeAPI { interface IButtonClick { void MessageBox(string message); } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Security.Cryptography; using System.Xml; using System.Data; using System.Text; using Framework.Utils; using Framework.Db; namespace Framework.Metadata { //------------------------------------------------------------------------------ /// <summary> /// Class to hold information about application entity usage. /// </summary> public class CxEntityUsageMetadata : CxEntityMetadata { //---------------------------------------------------------------------------- public const string LOCALIZATION_OBJECT_TYPE_CODE = "Metadata.EntityUsage"; public const string PROPERTY_GRID_ORDER = "grid_visible_order"; public const string PROPERTY_EDIT_ORDER = "edit_order"; public const string PROPERTY_FILTER_ORDER = "filter_order"; public const string PROPERTY_QUERY_ORDER = "query_order"; public const string PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST = "child_entity_usage_order_in_list"; public const string PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW = "child_entity_usage_order_in_view"; //---------------------------------------------------------------------------- private CxEntityUsagesMetadata m_EntityUsages; // Global collection of entity usages protected Dictionary<string, CxChildEntityUsageMetadata> m_ChildEntityUsages = new Dictionary<string, CxChildEntityUsageMetadata>(); // Dictionary of child entity usages protected IList<CxChildEntityUsageMetadata> m_ChildEntityUsagesList = new List<CxChildEntityUsageMetadata>(); // Ordered list child entity usages protected IList<string> m_OrderedAttributeNames; // List of attribute names with overriden order protected IList<CxEntityUsageToEditMetadata> m_EntityUsagesToEdit = new List<CxEntityUsageToEditMetadata>(); // List of entity usages to edit instead of this one protected IList<string> m_OrderedCommandNames; // Ordered list of command names. protected bool m_IsOrderedCommandNamesDefined; protected List<CxCommandMetadata> m_OrderedCommandList; // Ordered list of commands. protected CxGenericDataTable m_EmptyDataTable; // Empty data table. // Lock objects to get cached entity data. protected Hashtable m_EntityDataCacheLockObjectMap = new Hashtable(); // Descendant entity usage cache. protected IList<CxEntityUsageMetadata> m_DirectDescendantEntityUsages; protected List<CxEntityUsageMetadata> m_DescendantEntityUsages; // Empty entity instance, for internal purposes protected object m_EntityInstance; // Cached list of attributes protected List<CxAttributeMetadata> m_Attributes; // Cached flag private readonly object m_AttributeLock = new object(); private CxEntityUsageMetadata m_InheritedEntityUsage; private bool m_IsInheritedEntityUsageCached; private CxEntityMetadata m_Entity; private bool m_IsEntityCached; private readonly Dictionary<NxChildEntityUsageOrderType, CxChildEntityUsageOrder> m_WinChildEntityUsageOrder = new Dictionary<NxChildEntityUsageOrderType, CxChildEntityUsageOrder>(); protected UniqueList<string> m_NewChildEntityUsageNames; //---------------------------------------------------------------------------- /// <summary> /// A list of property names that are not inheritable. /// </summary> public override List<string> NonInheritableProperties { get { if (m_NonInheritableProperties == null) { m_NonInheritableProperties = new List<string>(base.NonInheritableProperties); m_NonInheritableProperties.Add("is_queryable"); } return m_NonInheritableProperties; } } //---------------------------------------------------------------------------- /// <summary> /// Indicates whether an explicit command order is defined. /// </summary> public bool IsOrderedCommandNamesDefined { get { return m_IsOrderedCommandNamesDefined; } } //---------------------------------------------------------------------------- /// <summary> /// Returns the child entity usage order of the requested type. /// </summary> /// <param name="orderType">the type of the order</param> public CxChildEntityUsageOrder GetChildEntityUsageOrder(NxChildEntityUsageOrderType orderType) { CxChildEntityUsageOrder result; if (m_WinChildEntityUsageOrder.ContainsKey(orderType)) result = m_WinChildEntityUsageOrder[orderType]; else { result = m_WinChildEntityUsageOrder[orderType] = new CxChildEntityUsageOrder(this, orderType); } return result; } //---------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="holder">a metadata holder the usage belongs to</param> /// <param name="element">XML element that holds metadata</param> /// <param name="entityUsages">a collection of entity usages the usage should be added to</param> public CxEntityUsageMetadata( CxMetadataHolder holder, XmlElement element, CxEntityUsagesMetadata entityUsages) : base(holder, element) { m_EntityUsages = entityUsages; AddNodeToProperties(element, "where_clause"); AddNodeToProperties(element, "join_condition"); // Load child entity usages XmlElement childrenEntitiesElement = (XmlElement) element.SelectSingleNode("child_entity_usages"); if (childrenEntitiesElement != null) { LoadChildEntityUsages(childrenEntitiesElement, false); } // Load description of entity usages to edit XmlElement entitiesToEditElement = (XmlElement) element.SelectSingleNode("entity_usages_to_edit"); if (entitiesToEditElement != null) { string importFromId = CxXml.GetAttr(entitiesToEditElement, "import_from"); if (CxUtils.NotEmpty(importFromId)) { CxEntityUsageMetadata importFromEntityUsage = Holder.EntityUsages[importFromId]; foreach (CxEntityUsageToEditMetadata edit in importFromEntityUsage.EntityUsagesToEdit) { m_EntityUsagesToEdit.Add(edit); } } else { XmlNodeList nodes = entitiesToEditElement.SelectNodes("entity_usage_to_edit"); if (nodes != null) { foreach (XmlElement editElement in nodes) { CxEntityUsageToEditMetadata edit = new CxEntityUsageToEditMetadata(Holder, editElement); m_EntityUsagesToEdit.Add(edit); } } } } CreateChildEntityUsageOrder(); } //---------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> public CxEntityUsageMetadata( CxMetadataHolder holder, CxEntityUsageMetadata baseEntityUsage) : base(holder) { CopyPropertiesFrom(baseEntityUsage); CreateChildEntityUsageOrder(); } //---------------------------------------------------------------------------- /// <summary> /// Loads children entity usages from the given XML element. /// </summary> /// <param name="childrenEntitiesElement"></param> protected void LoadChildEntityUsages(XmlElement childrenEntitiesElement, bool doLoadOverrides) { string importFromId = CxXml.GetAttr(childrenEntitiesElement, "import_from"); if (CxUtils.NotEmpty(importFromId)) { CxEntityUsageMetadata importFromEntityUsage = m_EntityUsages[importFromId]; foreach (CxChildEntityUsageMetadata child in importFromEntityUsage.ChildEntityUsagesList) { if (!ChildEntityUsages.ContainsKey(child.Id)) { AddChild(child); } } } else { XmlNodeList nodes = childrenEntitiesElement.SelectNodes("child_entity_usage"); if (nodes != null) { foreach (XmlElement childElement in nodes) { string childId = CxXml.GetAttr(childElement, "id").ToUpper(); if (!ChildEntityUsages.ContainsKey(childId)) { CxChildEntityUsageMetadata child = new CxChildEntityUsageMetadata(Holder, childElement, this); AddChild(child); } else if (doLoadOverrides) { CxChildEntityUsageMetadata child = ChildEntityUsages[childId]; child.LoadOverride(childElement); } } } } } //---------------------------------------------------------------------------- /// <summary> /// Creates attribute order objects. /// </summary> protected void CreateChildEntityUsageOrder() { } //---------------------------------------------------------------------------- /// <summary> /// Returns the XML tag name applicable for the current metadata object. /// </summary> public override string GetTagName() { return "entity_usage"; } //---------------------------------------------------------------------------- /// <summary> /// Seeks for entity usages that contain the given entity usage in their "child_entity_usages" reference. /// </summary> /// <returns>a list of entity usages found</returns> public IList<CxEntityUsageMetadata> FindParentEntityUsages() { List<CxEntityUsageMetadata> parentEntityUsages = new List<CxEntityUsageMetadata>(); foreach (CxEntityUsageMetadata entityUsage in Entity.Holder.EntityUsages.Items) { foreach (CxChildEntityUsageMetadata childEntityUsageMetadata in entityUsage.ChildEntityUsagesList) { if (childEntityUsageMetadata.EntityUsage == this && !parentEntityUsages.Contains(entityUsage)) parentEntityUsages.Add(entityUsage); } } return parentEntityUsages; } //---------------------------------------------------------------------------- /// <summary> /// Renders the metadata object to its XML representation. /// </summary> /// <param name="document">the document to render into</param> /// <param name="custom">indicates whether just customization should be rendered</param> /// <param name="tagName">the tag name to be used while rendering</param> /// <returns>the rendered object</returns> public override CxXmlRenderedObject RenderToXml(XmlDocument document, bool custom, string tagName) { Dictionary<string, string> propertiesToRender = new Dictionary<string, string>(); List<string> propertiesToRemove = new List<string>(); bool isOneOrderSaved = false; CxAttributeOrder orderGrid = GetAttributeOrder(NxAttributeContext.GridVisible); if (orderGrid.IsCustom) { propertiesToRender[PROPERTY_GRID_ORDER] = CxUtils.Nvl(CxText.ComposeCommaSeparatedString(orderGrid.OrderIds), " "); isOneOrderSaved = true; } else if (!string.IsNullOrEmpty(this[PROPERTY_GRID_ORDER])) { propertiesToRemove.Add(PROPERTY_GRID_ORDER); } CxAttributeOrder orderEdit = GetAttributeOrder(NxAttributeContext.Edit); if (orderEdit.IsCustom) { propertiesToRender[PROPERTY_EDIT_ORDER] = CxUtils.Nvl(CxText.ComposeCommaSeparatedString(orderEdit.OrderIds), " "); isOneOrderSaved = true; } else if (!string.IsNullOrEmpty(this[PROPERTY_EDIT_ORDER])) { propertiesToRemove.Add(PROPERTY_EDIT_ORDER); } CxAttributeOrder orderFilter = GetAttributeOrder(NxAttributeContext.Filter); if (orderFilter.IsCustom) { propertiesToRender[PROPERTY_FILTER_ORDER] = CxUtils.Nvl(CxText.ComposeCommaSeparatedString(orderFilter.OrderIds), " "); isOneOrderSaved = true; } else if (!string.IsNullOrEmpty(this[PROPERTY_FILTER_ORDER])) { propertiesToRemove.Add(PROPERTY_FILTER_ORDER); } CxAttributeOrder orderQuery = GetAttributeOrder(NxAttributeContext.Queryable); if (orderQuery.IsCustom) { propertiesToRender[PROPERTY_QUERY_ORDER] = CxUtils.Nvl(CxText.ComposeCommaSeparatedString(orderQuery.OrderIds), " "); isOneOrderSaved = true; } else if (!string.IsNullOrEmpty(this[PROPERTY_QUERY_ORDER])) { propertiesToRemove.Add(PROPERTY_QUERY_ORDER); } if (isOneOrderSaved) { // This property should be set BEFORE the object properties are rendered. KnownAttributesString = CxText.ComposeCommaSeparatedString(ExtractIds(Attributes)); //propertiesToRender["known_attributes"] = CxText.ComposeCommaSeparatedString(ExtractIds(Attributes)); } bool isCustomChildEntityUsageOrderSaved = false; // 1. Main form CxChildEntityUsageOrder childEntityUsageOrder_InList = GetChildEntityUsageOrder(NxChildEntityUsageOrderType.InList); if (childEntityUsageOrder_InList.IsCustom) { propertiesToRender[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST] = CxText.ComposeCommaSeparatedString(childEntityUsageOrder_InList.OrderIds); isCustomChildEntityUsageOrderSaved = true; } else if (!string.IsNullOrEmpty(this[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST])) { propertiesToRemove.Add(PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST); } // 2. Edit form CxChildEntityUsageOrder childEntityUsageOrder_InView = GetChildEntityUsageOrder(NxChildEntityUsageOrderType.InView); if (childEntityUsageOrder_InView.IsCustom) { propertiesToRender[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW] = CxText.ComposeCommaSeparatedString(childEntityUsageOrder_InView.OrderIds); isCustomChildEntityUsageOrderSaved = true; } else if (!string.IsNullOrEmpty(this[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW])) { propertiesToRemove.Add(PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW); } if (isCustomChildEntityUsageOrderSaved) { propertiesToRender["known_child_entity_usages"] = CxText.ComposeCommaSeparatedString(ExtractIds(ChildEntityUsagesList)); } // Here we call the base method writing down all the current object properties // so they should be in the proper state at this moment in order to write them down. CxXmlRenderedObject result = base.RenderToXml(document, custom, tagName); foreach (string propertyName in propertiesToRemove) { XmlAttribute attribute = result.Element.Attributes[propertyName]; if (attribute != null) result.Element.Attributes.Remove(attribute); } foreach (KeyValuePair<string, string> pair in propertiesToRender) { XmlAttribute attribute = document.CreateAttribute(pair.Key); attribute.Value = pair.Value; result.Element.Attributes.Append(attribute); result.IsEmpty = false; } XmlElement attributeUsagesElement = document.CreateElement("attribute_usages"); bool isAttributeUsagesNonEmpty = false; foreach (string attributeId in ExtractIds(Attributes)) { CxAttributeMetadata attributeMetadata = GetAttribute(attributeId); CxXmlRenderedObject renderedAttribute = attributeMetadata.RenderToXml(document, custom, "attribute_usage"); if (!renderedAttribute.IsEmpty) { attributeUsagesElement.AppendChild(renderedAttribute.Element); isAttributeUsagesNonEmpty = true; } } if (isAttributeUsagesNonEmpty) { result.Element.AppendChild(attributeUsagesElement); result.IsEmpty = false; } return result; } //------------------------------------------------------------------------- public string GridOrderCustom { get { return this["grid_visible_order_custom"]; } set { this["grid_visible_order_custom"] = value; } } //------------------------------------------------------------------------- public string EditOrderCustom { get { return this["edit_order_custom"]; } set { this["edit_order_custom"] = value; } } //------------------------------------------------------------------------- public string FilterOrderCustom { get { return this["filter_order_custom"]; } set { this["filter_order_custom"] = value; } } //------------------------------------------------------------------------- public string QueryOrderCustom { get { return this["query_order_custom"]; } set { this["query_order_custom"] = value; } } //------------------------------------------------------------------------- /// <summary> /// Loads custom metadata object from the given XML element. /// </summary> /// <param name="element">the element to load from</param> public override void LoadCustomMetadata(XmlElement element) { base.LoadCustomMetadata(element); string gridOrder = this["grid_visible_order"]; if (!string.IsNullOrEmpty(gridOrder)) { CxAttributeOrder orderGrid = GetAttributeOrder(NxAttributeContext.GridVisible); if (!CxList.CompareOrdered(orderGrid.OrderIds, CxText.DecomposeWithWhiteSpaceAndComma(gridOrder))) orderGrid.SetCustomOrder(gridOrder); this["grid_visible_order"] = GetInitialProperty("grid_visible_order"); } string editOrder = this["edit_order"]; if (!string.IsNullOrEmpty(editOrder)) { CxAttributeOrder orderEdit = GetAttributeOrder(NxAttributeContext.Edit); if (!CxList.CompareOrdered(orderEdit.OrderIds, CxText.DecomposeWithWhiteSpaceAndComma(editOrder))) orderEdit.SetCustomOrder(editOrder); this["edit_order"] = GetInitialProperty("edit_order"); } string filterOrder = this["filter_order"]; if (!string.IsNullOrEmpty(filterOrder)) { CxAttributeOrder orderFilter = GetAttributeOrder(NxAttributeContext.Filter); if (!CxList.CompareOrdered(orderFilter.OrderIds, CxText.DecomposeWithWhiteSpaceAndComma(filterOrder))) orderFilter.SetCustomOrder(filterOrder); this["filter_order"] = GetInitialProperty("filter_order"); } string queryOrder = this["query_order"]; if (!string.IsNullOrEmpty(queryOrder)) { CxAttributeOrder orderQuery = GetAttributeOrder(NxAttributeContext.Queryable); if (!CxList.CompareOrdered(orderQuery.OrderIds, CxText.DecomposeWithWhiteSpaceAndComma(queryOrder))) orderQuery.SetCustomOrder(queryOrder); this["query_order"] = GetInitialProperty("query_order"); } // 1. Main form string childEntityUsageOrder_InList = this[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST]; if (!string.IsNullOrEmpty(childEntityUsageOrder_InList)) { CxChildEntityUsageOrder orderChildEntityUsage = GetChildEntityUsageOrder(NxChildEntityUsageOrderType.InList); if (!CxList.CompareOrdered(orderChildEntityUsage.OrderIds, CxText.DecomposeWithWhiteSpaceAndComma(childEntityUsageOrder_InList))) orderChildEntityUsage.SetCustomOrder(childEntityUsageOrder_InList); this[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST] = GetInitialProperty(PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_LIST); } // 2. Edit form string childEntityUsageOrder_InView = this[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW]; if (!string.IsNullOrEmpty(childEntityUsageOrder_InView)) { CxChildEntityUsageOrder orderChildEntityUsage = GetChildEntityUsageOrder(NxChildEntityUsageOrderType.InView); if (!CxList.CompareOrdered(orderChildEntityUsage.OrderIds, CxText.DecomposeWithWhiteSpaceAndComma(childEntityUsageOrder_InView))) orderChildEntityUsage.SetCustomOrder(childEntityUsageOrder_InView); this[PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW] = GetInitialProperty(PROPERTY_CHILD_ENTITY_USAGE_ORDER_IN_VIEW); } } //---------------------------------------------------------------------------- /// <summary> /// Loads metadata object override. /// </summary> /// <param name="element">XML element to load overridden properties from</param> override public void LoadOverride(XmlElement element) { base.LoadOverride(element); XmlElement childrenEntitiesElement = (XmlElement) element.SelectSingleNode("child_entity_usages"); if (childrenEntitiesElement != null) { LoadChildEntityUsages(childrenEntitiesElement, true); } } //---------------------------------------------------------------------------- /// <summary> /// Adds command to the list. /// </summary> /// <param name="command">command to add</param> override public void AddCommand(CxCommandMetadata command) { base.AddCommand(command); // Copy command properties from base entity or inherited entity usage. CxCommandMetadata parentCommand; if (InheritedEntityUsage != null) { parentCommand = InheritedEntityUsage.GetCommand(command.Id); if (parentCommand != null) { command.CopyPropertiesFrom(parentCommand); } } parentCommand = Entity.GetCommand(command.Id); if (parentCommand != null) { command.CopyPropertiesFrom(parentCommand); } } //---------------------------------------------------------------------------- /// <summary> /// "Registers" child entity usage. /// </summary> /// <param name="child">child entity usage to add</param> protected void AddChild(CxChildEntityUsageMetadata child) { ChildEntityUsages.Add(child.Id, child); m_ChildEntityUsagesList.Add(child); } //---------------------------------------------------------------------------- /// <summary> /// Dictionary of child entity usages. /// </summary> public Dictionary<string, CxChildEntityUsageMetadata> ChildEntityUsages { get { return m_ChildEntityUsages; } } //---------------------------------------------------------------------------- /// <summary> /// Ordered list child entity usages. /// </summary> public IList<CxChildEntityUsageMetadata> ChildEntityUsagesList { get { return m_ChildEntityUsagesList; } } //---------------------------------------------------------------------------- /// <summary> /// Returns child entity usage by ID. If not found raises exception. /// </summary> /// <param name="childId">ID of child entity usage</param> /// <returns>child entity usage by ID</returns> public CxChildEntityUsageMetadata GetChildEntityUsage(string childId) { string upperChildId = CxText.ToUpper(childId); CxChildEntityUsageMetadata child = null; if (ChildEntityUsages.ContainsKey(upperChildId)) child = ChildEntityUsages[upperChildId]; if (child != null) { return child; } else { throw new ExMetadataException(string.Format( "Entity usage <{0}> does not have child entity usage <{1}>", Id, childId)); } } //---------------------------------------------------------------------------- /// <summary> /// List of entity usages to edit instead of this one. /// </summary> public IList<CxEntityUsageToEditMetadata> EntityUsagesToEdit { get { return m_EntityUsagesToEdit; } } //---------------------------------------------------------------------------- /// <summary> /// ID of entity this usage based on. /// </summary> public string EntityId { get { return this["entity_id"].ToUpper(); } } //---------------------------------------------------------------------------- /// <summary> /// Entity this usage based on. /// </summary> public CxEntityMetadata Entity { get { if (!m_IsEntityCached) { m_Entity = Holder.Entities[EntityId]; m_IsEntityCached = true; } return m_Entity; } } //---------------------------------------------------------------------------- /// <summary> /// ID of entity usage this usage based on. /// </summary> public string InheritedEntityUsageId { get { return this["inherited_entity_usage_id"].ToUpper(); } } //---------------------------------------------------------------------------- /// <summary> /// Entity usage this usage based on. /// </summary> public CxEntityUsageMetadata InheritedEntityUsage { get { if (!m_IsInheritedEntityUsageCached) { if (CxUtils.NotEmpty(InheritedEntityUsageId) && InheritedEntityUsageId != Id) { CxEntityUsageMetadata entityUsage = EntityUsages.Find(InheritedEntityUsageId); if (entityUsage == null) { throw new ExMetadataException( String.Format( "Inherited entity usage with ID=\"{0}\" could not be found. " + "Probably it is not defined or defined after the dependent entity usage with ID=\"{1}\".", InheritedEntityUsageId, Id)); } m_InheritedEntityUsage = entityUsage; } m_IsInheritedEntityUsageCached = true; } return m_InheritedEntityUsage; } } //---------------------------------------------------------------------------- /// <summary> /// ID of menu item to use security rights from. /// </summary> public string SecurityMenuItemId { get { return this["security_menu_item_id"]; } } //---------------------------------------------------------------------------- /// <summary> /// ID of base entity usage for this one. /// </summary> public string BaseEntityUsageId { get { return this["base_entity_usage_id"]; } } //---------------------------------------------------------------------------- /// <summary> /// Base entity usage for this one. /// </summary> public CxEntityUsageMetadata BaseEntityUsage { get { return (CxUtils.NotEmpty(BaseEntityUsageId) ? Holder.EntityUsages[BaseEntityUsageId] : null); } } //------------------------------------------------------------------------- /// <summary> /// True if entity should be used in Bookmarks and Recent Items lists on behalf of another entity metadata. /// Notice, the reference cannot go deeper than just one hop. No complex circular references possible. /// </summary> public string BookmarksAndRecentItemsEntityMetadataId { get { return this["bookmarks_and_recent_items_entity_metadata_id"]; } } //------------------------------------------------------------------------- public CxEntityUsageMetadata BookmarksAndRecentItemsEntityMetadata { get { if (!string.IsNullOrEmpty(BookmarksAndRecentItemsEntityMetadataId)) { var entityMetadata = Holder.EntityUsages.Find(BookmarksAndRecentItemsEntityMetadataId); if (entityMetadata != null) return entityMetadata; } return this; } } //---------------------------------------------------------------------------- /// <summary> /// ID of entity usage this one should use main menu properties of. /// </summary> public string MainMenuEntityUsageId { get { return this["main_menu_entity_usage_id"]; } } //---------------------------------------------------------------------------- /// <summary> /// true if this entity usage may be added to the hot item list. /// </summary> public bool Hottable { get { string s = this["hottable"].ToLower(); return (CxUtils.NotEmpty(s) ? (s == "true") : BaseEntityUsage != null ? BaseEntityUsage.Hottable : false); } } //---------------------------------------------------------------------------- /// <summary> /// Join condition to link entity usage to parent. /// </summary> public string JoinCondition { get { return this["join_condition"]; } } //---------------------------------------------------------------------------- /// <summary> /// Additional where clause. /// </summary> public string WhereClause { get { return this["where_clause"]; } } //---------------------------------------------------------------------------- /// <summary> /// true if grid should has grouping by default. /// </summary> public bool GridGrouping { get { return (this["grid_grouping"].ToLower() != "false"); } } //---------------------------------------------------------------------------- /// <summary> /// true if grid sorting should be enabled. /// </summary> public bool GridSorting { get { return (this["grid_sorting"].ToLower() != "false"); } } //---------------------------------------------------------------------------- /// <summary> /// true if master entity should be refreshed on detail change. /// </summary> public bool RefreshMaster { get { return (this["refresh_master"].ToLower() == "true"); } } //---------------------------------------------------------------------------- /// <summary> /// true if detail entities should be refreshed on detail change. /// </summary> public bool RefreshDetail { get { return (this["refresh_detail"].ToLower() == "true"); } } //---------------------------------------------------------------------------- /// <summary> /// True if all current list of entities should be refreshed on /// record change (insert, update or delete). /// </summary> public bool RefreshList { get { return (this["refresh_list"].ToLower() == "true"); } } //---------------------------------------------------------------------------- /// <summary> /// True if the whole list of master entities should be refreshed on /// record change (insert, update or delete). /// </summary> public bool RefreshMasterList { get { return (this["refresh_master_list"].ToLower() == "true"); } } //---------------------------------------------------------------------------- /// <summary> /// true if grid shoudl be refreshed after delete. /// </summary> public bool RefreshAfterDelete { get { return (this["refresh_after_delete"].ToLower() == "true"); } } //---------------------------------------------------------------------------- /// <summary> /// True if SQL select clause already contains parent-child join condition, /// and join_condition attribute is not needed for parent-child grid relation. /// </summary> public bool IsJoinConditionInSelectClause { get { return (this["join_condition_in_select"].ToLower() == "true"); } } //---------------------------------------------------------------------------- /// <summary> /// Returns attribute with the given name. /// </summary> /// <param name="name">attribute name</param> /// <returns>attribute with the given name</returns> override public CxAttributeMetadata GetAttribute(string name) { // Try to get attribute defined directly in this entity usage. CxAttributeMetadata attribute = base.GetAttribute(name); // Try to get attribute defined in the inherited entity usage. if (attribute == null && InheritedEntityUsage != null) { attribute = InheritedEntityUsage.GetAttribute(name); } // Try to get attribute defined in the base entity. if (attribute == null) { attribute = Entity.GetAttribute(name); } return attribute; } //---------------------------------------------------------------------------- /// <summary> /// Ordered list of attributes. /// </summary> override public IList<CxAttributeMetadata> Attributes { get { lock (m_AttributeLock) { if (m_Attributes == null) { m_Attributes = new List<CxAttributeMetadata>(); if (CxList.IsEmpty2(m_OrderedAttributeNames)) { if (InheritedEntityUsage != null) { m_Attributes.AddRange(InheritedEntityUsage.Attributes); } else { m_Attributes.AddRange(Entity.Attributes); } foreach (CxAttributeMetadata attributeUsage in base.Attributes) { CxAttributeMetadata entityAttribute; if (InheritedEntityUsage != null) { entityAttribute = InheritedEntityUsage.GetAttribute(attributeUsage.Id); } else { entityAttribute = Entity.GetAttribute(attributeUsage.Id); } if (entityAttribute != null) { int index = ExtractIds(Attributes).IndexOf(entityAttribute.Id); if (index < 0) throw new ExException("index is expected to be greater then -1"); m_Attributes[index] = attributeUsage; } else { m_Attributes.Add(attributeUsage); } } } else { foreach (string name in m_OrderedAttributeNames) { CxAttributeMetadata attribute = GetAttribute(name); if (attribute != null) m_Attributes.Add(attribute); } } } return new List<CxAttributeMetadata>(m_Attributes); } } } //---------------------------------------------------------------------------- private IList<CxAttributeMetadata> m_HyperlinkComposeXmlAttributes; //------------------------------------------------------------------------- /// <summary> /// Returns the list of hyperlink "xml compose" attributes, cached. /// </summary> public IList<CxAttributeMetadata> GetHyperlinkComposeXmlAttributes() { if (m_HyperlinkComposeXmlAttributes == null) { m_HyperlinkComposeXmlAttributes = new List<CxAttributeMetadata>(); foreach (CxAttributeMetadata attributeMetadata in Attributes) { if (attributeMetadata.HyperLinkComposeXml) { m_HyperlinkComposeXmlAttributes.Add(attributeMetadata); } } } return m_HyperlinkComposeXmlAttributes; } //---------------------------------------------------------------------------- /// <summary> /// Returns command with the given name. /// </summary> /// <param name="commandId">command name</param> /// <returns>command with the given name</returns> override public CxCommandMetadata GetCommand(string commandId) { CxCommandMetadata command = base.GetCommand(commandId); if (command == null && InheritedEntityUsage != null) { command = InheritedEntityUsage.GetCommand(commandId); } if (command == null) { command = Entity.GetCommand(commandId); } return command; } //---------------------------------------------------------------------------- /// <summary> /// Ordered list of commands. /// </summary> override public IList<CxCommandMetadata> Commands { get { if (m_OrderedCommandList == null) { m_OrderedCommandList = new List<CxCommandMetadata>(); if (CxList.IsEmpty2(m_OrderedCommandNames)) { if (InheritedEntityUsage != null) { m_OrderedCommandList.AddRange(InheritedEntityUsage.Commands); } else { m_OrderedCommandList.AddRange(Entity.Commands); } foreach (CxCommandMetadata command in base.Commands) { CxCommandMetadata entityCommand; if (InheritedEntityUsage != null) { entityCommand = InheritedEntityUsage.GetCommand(command.Id); } else { entityCommand = Entity.GetCommand(command.Id); } if (entityCommand != null) { int index = m_OrderedCommandList.IndexOf(entityCommand); m_OrderedCommandList[index] = command; } else { m_OrderedCommandList.Add(command); } } } else { foreach (string name in m_OrderedCommandNames) { CxCommandMetadata command = GetCommand(name); if (command != null) { m_OrderedCommandList.Add(command); } } } } return m_OrderedCommandList; } } //---------------------------------------------------------------------------- /// <summary> /// Sets overriden order of attributes. /// </summary> /// <param name="orderedAttributes">comma-separated list of attribute names</param> /// <param name="overwrite">determines if the ordered attributes /// should be overwritten even if it already exists</param> public void SetAttributeOrder(string orderedAttributes, bool overwrite) { if (overwrite || CxList.IsEmpty2(m_OrderedAttributeNames)) { m_OrderedAttributeNames = CxText.DecomposeWithWhiteSpaceAndComma(orderedAttributes.ToUpper()); } } //---------------------------------------------------------------------------- /// <summary> /// Sets overriden order of commands. /// </summary> /// <param name="orderedCommands">comma-separated list of command names</param> /// <param name="overwrite">determines if the command order /// should be overwritten even if it already exists</param> public void SetCommandOrder(string orderedCommands, bool overwrite) { if (overwrite) { m_OrderedCommandNames = CxText.DecomposeWithWhiteSpaceAndComma(orderedCommands.ToUpper()); m_IsOrderedCommandNamesDefined = true; } else if (CxList.IsEmpty2(m_OrderedCommandNames)) { m_OrderedCommandNames = new string[0]; m_IsOrderedCommandNamesDefined = false; } } //---------------------------------------------------------------------------- /// <summary> /// Returns true if the command should be visible from the current entity usage's point of view. /// </summary> /// <param name="commandMetadata">a command to evaluate</param> /// <returns>true if visible</returns> public bool GetIsCommandVisible(CxCommandMetadata commandMetadata) { return GetIsCommandVisible(commandMetadata, null); } //---------------------------------------------------------------------------- /// <summary> /// Returns true if the command should be visible from the current entity usage's point of view. /// </summary> /// <param name="commandMetadata">a command to evaluate</param> /// <returns>true if visible</returns> public bool GetIsCommandVisible(CxCommandMetadata commandMetadata, IxEntity parentEntity) { if (!Commands.Contains(commandMetadata)) return false; if (IsOrderedCommandNamesDefined && !m_OrderedCommandNames.Contains(commandMetadata.Id)) return false; if (!commandMetadata.Visible) return false; if (!EntityInstance.GetIsCommandVisible(commandMetadata, parentEntity)) return false; return true; } //---------------------------------------------------------------------------- /// <summary> /// Returns full SQL SELECT statement with WHERE condition. /// </summary> public string GetSelectStatement() { return CxDbUtils.AddToWhere(SqlSelect, WhereClause); } //---------------------------------------------------------------------------- /// <summary> /// Compose SQL statement for ReadData method. /// </summary> /// <param name="where">additional where clause</param> public string ComposeReadDataSql(string where = "") { if (CxUtils.IsEmpty(SqlSelect)) { throw new ExMetadataException("SQL SELECT statement not defined for " + Id + " entity usage"); } string sql = GetSelectStatement(); sql = CxDbUtils.AddToWhere(sql, where); sql = CxDbUtils.AddToWhere(sql, GetCustomWhereClause()); sql = CxDbUtils.AddToWhere(sql, GetAccessWhereClause()); return sql; } //---------------------------------------------------------------------------- /// <summary> /// Prepares value provider before passing to command. /// </summary> /// <param name="provider">base value provider</param> /// <returns>value provider to pass to SQL command</returns> public IxValueProvider PrepareValueProvider(IxValueProvider provider) { IxValueProvider res; if (Holder != null) { res = Holder.PrepareValueProvider(provider); } else { res = new CxValueProviderCollection(); ((CxValueProviderCollection)res).AddIfNotEmpty(provider); } foreach (var atr in Attributes) { res.ValueTypes.Add(atr.Id.ToUpper(), atr.Type); } return res; } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="cacheMode">entity cache mode</param> /// <param name="customPreProcessHandler">a custom pre-processing handler to be applied to the /// data obtained</param> public void ReadData( CxDbConnection connection, DataTable dt, string where = "", IxValueProvider provider = null, NxEntityDataCache cacheMode = NxEntityDataCache.Default, DxCustomPreProcessDataSource customPreProcessHandler = null) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } string sql = ComposeReadDataSql(where); sql = ComposeRecordLimitSqlText(connection, sql); GetQueryResult(connection, dt, sql, provider, cacheMode, customPreProcessHandler); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="orderClause">order by clause in format {field1} asc | desc, {field2} asc | desc</param> /// <param name="recordCountLimit">record count limit</param> public void ReadData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, string orderClause, int recordCountLimit) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } string sql = ComposeReadDataSql(where); sql = ComposeRecordLimitSqlText(connection, sql, recordCountLimit); if (CxUtils.NotEmpty(orderClause)) { sql += "\r\nORDER BY " + orderClause; } GetQueryResult(connection, dt, sql, provider, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="orderClause">order by clause in format {field1} asc | desc, {field2} asc | desc</param> public void ReadData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, string orderClause) { ReadData(connection, dt, where, provider, orderClause, -1, -1); } //---------------------------------------------------------------------------- /// <summary> /// Performs the query to be performed before any SELECT statement. /// </summary> /// <param name="connection">database connection</param> protected void DoSqlSelectRunBefore( CxDbConnection connection) { string statement = SqlSelectRunBefore; if (!string.IsNullOrEmpty(statement)) { IxValueProvider provider = Holder.ApplicationValueProvider; connection.ExecuteCommand(statement, provider); } } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="orderClause">order by clause in format {field1} asc | desc, {field2} asc | desc</param> /// <param name="startRowIndex">start record index to get data</param> /// <param name="rowCount">amount of records to get</param> public void ReadData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, string orderClause, int startRowIndex, int rowCount) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } string sql = ComposeReadDataSql(where); if (startRowIndex == -1) { if (rowCount == -1) sql = ComposeRecordLimitSqlText(connection, sql); else sql = ComposeRecordLimitSqlText(connection, sql, rowCount); } else { if (rowCount == -1) throw new ExArgumentException("recordsAmount", rowCount.ToString()); sql = ComposePagedSqlText( connection, sql, startRowIndex, rowCount, orderClause); } if (!String.IsNullOrEmpty(orderClause)) { sql += "\r\nORDER BY " + orderClause; } GetQueryResult(connection, dt, sql, provider, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Returns the overall amount of data rows (not taking into account the record /// frame probably used). /// </summary> /// <param name="connection">database connection</param> /// <param name="where">where clause</param> /// <param name="valueProvider">value provider for parameters</param> /// <returns>amount of datarows available</returns> public int ReadDataRowAmount( CxDbConnection connection, string where, IxValueProvider valueProvider) { if (!GetIsAccessGranted()) { return -1; } string sql = ComposeReadDataSql(where); sql = connection.ScriptGenerator.GetCountSqlScriptForSelect(sql); object resultObj = connection.ExecuteScalar(sql, valueProvider); if (!CxUtils.IsNull(resultObj)) return Convert.ToInt32(resultObj); else throw new ExException("Unexpected query result: NULL result for the <select count> query"); } //---------------------------------------------------------------------------- /// <summary> /// Returns the overall amount of data rows taking into account /// the existing parent-child relationship /// (not taking into account the record frame probably used). /// </summary> /// <param name="connection">database connection</param> /// <param name="where">where clause</param> /// <param name="valueProvider">value provider for parameters</param> /// <returns>amount of datarows available</returns> public int ReadChildDataRowAmount( CxDbConnection connection, string where, IxValueProvider valueProvider) { if (!GetIsAccessGranted()) { return -1; } string sql = GetChildDataQuery(connection, where); sql = connection.ScriptGenerator.GetCountSqlScriptForSelect(sql); object resultObj = connection.ExecuteScalar(sql, valueProvider); if (!CxUtils.IsNull(resultObj)) return Convert.ToInt32(resultObj); else throw new ExException("Unexpected query result: NULL result for the <select count> query"); } //---------------------------------------------------------------------------- /// <summary> /// Reads an array of entities of the given entity usage. /// </summary> /// <param name="connection">a database connection</param> /// <param name="where">where clause (filter condition)</param> /// <param name="valueProvider">a provider for parameter values</param> /// <param name="startRowIndex">start index offset</param> /// <param name="rowCount">amount of records to get</param> /// <param name="sortings">sort descriptors collection</param> /// <returns>an array of entities</returns> public IxEntity[] ReadEntities( CxDbConnection connection, string where, IxValueProvider valueProvider, int startRowIndex = -1, int rowCount = -1, CxSortDescriptorList sortings = null) { return EntityInstance.ReadEntities( connection, where, valueProvider, startRowIndex, rowCount, sortings); } //---------------------------------------------------------------------------- /// <summary> /// Reads an entity of the given entity usage and with the given entity PK. /// </summary> /// <param name="connection">a database connection</param> /// <param name="where">where clause (filter condition)</param> /// <param name="valueProvider">a provider for parameter values, including PK</param> /// <returns>the entity read</returns> public IxEntity ReadEntity( CxDbConnection connection, string where, IxValueProvider valueProvider) { return EntityInstance.ReadEntity( connection, where, valueProvider); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="paramValues">values of parameters in where clause (if any)</param> public void ReadData(CxDbConnection connection, DataTable dt, string where, object[] paramValues) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } string sql = ComposeReadDataSql(where); IxValueProvider provider = CxDbUtils.GetValueProvider(sql, paramValues); ReadData(connection, dt, where, provider); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="customPreProcessHandler">a custom pre-processing handler to be applied to the /// data obtained</param> public void ReadData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, DxCustomPreProcessDataSource customPreProcessHandler) { ReadData(connection, dt, where, provider, NxEntityDataCache.Default, customPreProcessHandler); } //---------------------------------------------------------------------------- /// <summary> /// Compose SQL statement for ReadDataRow method. /// </summary> /// <param name="where">additional where clause</param> protected string ComposeReadDataRowSql(string where) { string sql = SqlSelectSingleRow; if (CxUtils.IsEmpty(sql)) { throw new ExMetadataException("SQL SELECT statement not defined for " + Id + " entity usage"); } sql = CxDbUtils.AddToWhere(sql, where); sql = CxDbUtils.AddToWhere(sql, GetAccessWhereClause()); return sql; } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="where">primary key condition</param> /// <param name="primaryKeyValues">values of primary key fields</param> public DataRow ReadDataRow( CxDbConnection connection, string where, object[] primaryKeyValues) { if (!GetIsAccessGranted()) { return null; } IxValueProvider valueProvider = PrepareValueProvider( CreatePrimaryKeyValueProvider(primaryKeyValues)); return ReadDataRow(connection, where, valueProvider); } //---------------------------------------------------------------------------- /// <summary> /// Creates a value provider containing primary key values /// taken from the given collection. /// </summary> /// <param name="primaryKeyValues">the ordered collection of primary key values</param> /// <returns>value provider created</returns> public IxValueProvider CreatePrimaryKeyValueProvider( object[] primaryKeyValues) { CxHashtable result = new CxHashtable(); CxAttributeMetadata[] primaryKeyAttributes = PrimaryKeyAttributes; for (int i = 0; i < primaryKeyAttributes.Length; i++) { CxAttributeMetadata attributeMetadata = PrimaryKeyAttributes[i]; result[attributeMetadata.Id] = primaryKeyValues[i]; } return result; } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="where">primary key condition</param> /// <param name="provider">parameter values provider to get primary key values</param> /// <param name="cacheMode">entity cache mode</param> public DataRow ReadDataRow( CxDbConnection connection, string where, IxValueProvider provider, NxEntityDataCache cacheMode) { if (!GetIsAccessGranted()) { return null; } string sql = ComposeReadDataRowSql(where); CxGenericDataTable dt = new CxGenericDataTable(); GetQueryResult(connection, dt, sql, provider, cacheMode); if (dt.Rows.Count == 1) { return dt.Rows[0]; } else if (dt.Rows.Count == 0) { return null; } else { string[] pkNames = CxDbParamParser.GetList(where, false); object[] pkValues = new object[pkNames.Length]; for (int i = 0; i < pkNames.Length; i++) { pkValues[i] = provider[pkNames[i]]; } throw new ExTooManyRowsException(PluralCaption, pkNames, pkValues, dt.Rows.Count); } } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="where">primary key condition</param> /// <param name="provider">parameter values provider to get primary key values</param> public DataRow ReadDataRow( CxDbConnection connection, string where, IxValueProvider provider) { return ReadDataRow(connection, where, provider, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Reads root-level self-referencing hierarchical entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="orderByClause">order by clause</param> /// <param name="cacheMode">entity cache mode</param> public void ReadRootLevelData(CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, string orderByClause, NxEntityDataCache cacheMode) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } if (CxUtils.IsEmpty(SqlSelect)) { throw new ExMetadataException("SQL SELECT statement not defined for " + Id + " entity usage"); } string sql = GetSelectStatement(); sql = CxDbUtils.AddToWhere(sql, RootCondition); sql = CxDbUtils.AddToWhere(sql, where); sql = CxDbUtils.AddToWhere(sql, GetCustomWhereClause()); sql = CxDbUtils.AddToWhere(sql, GetAccessWhereClause()); sql = ComposeRecordLimitSqlText(connection, sql); if (!String.IsNullOrEmpty(orderByClause)) { sql += "\r\nORDER BY " + orderByClause; } GetQueryResult(connection, dt, sql, provider, cacheMode); } //---------------------------------------------------------------------------- /// <summary> /// Reads root-level self-referencing hierarchical entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="cacheMode">entity cache mode</param> public void ReadRootLevelData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, NxEntityDataCache cacheMode) { ReadRootLevelData(connection, dt, where, provider, null, cacheMode); } //---------------------------------------------------------------------------- /// <summary> /// Reads root-level self-referencing hierarchical entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> public void ReadRootLevelData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider) { ReadRootLevelData(connection, dt, where, provider, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Reads root-level self-referencing hierarchical entity data from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="where">additional where clause</param> /// <param name="provider">parameter values provider</param> /// <param name="orderByClause">order by clause</param> public void ReadRootLevelData( CxDbConnection connection, DataTable dt, string where, IxValueProvider provider, string orderByClause) { ReadRootLevelData(connection, dt, where, provider, orderByClause, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Reads next level of self-reference hierarchilcal entity data. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="provider">parameter values provider</param> /// <param name="cacheMode">entity cache mode</param> public void ReadNextLevelData( CxDbConnection connection, DataTable dt, IxValueProvider provider, NxEntityDataCache cacheMode) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } if (CxUtils.IsEmpty(SqlSelect)) { throw new ExMetadataException("SQL SELECT statement not defined for " + Id + " entity usage"); } if (CxUtils.IsEmpty(LevelCondition)) { throw new ExMetadataException("'level_condition' statement not defined for " + Id + " entity usage"); } string sql = GetSelectStatement(); sql = CxDbUtils.AddToWhere(sql, LevelCondition); sql = CxDbUtils.AddToWhere(sql, GetCustomWhereClause()); sql = CxDbUtils.AddToWhere(sql, GetAccessWhereClause()); sql = ComposeRecordLimitSqlText(connection, sql); GetQueryResult(connection, dt, sql, provider, cacheMode); } //---------------------------------------------------------------------------- /// <summary> /// Reads next level of self-reference hierarchilcal entity data. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of entities</param> /// <param name="provider">parameter values provider</param> public void ReadNextLevelData( CxDbConnection connection, DataTable dt, IxValueProvider provider) { ReadNextLevelData(connection, dt, provider, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Gets a query to obtain childish data. /// </summary> /// <param name="connection">a connection to be used</param> /// <param name="where">where clause to be used</param> /// <returns>a query</returns> public string GetChildDataQuery( CxDbConnection connection, string where) { string sql = GetSelectStatement(); sql = CxDbUtils.AddToWhere(sql, where); sql = CxDbUtils.AddToWhere(sql, JoinCondition); sql = CxDbUtils.AddToWhere(sql, GetCustomWhereClause()); sql = CxDbUtils.AddToWhere(sql, GetAccessWhereClause()); sql = ComposeRecordLimitSqlText(connection, sql); return sql; } //---------------------------------------------------------------------------- /// <summary> /// Gets data provider for the query to obtain childish data. /// </summary> /// <param name="paramProvider">parameter provider</param> /// <param name="where">where clause</param> /// <param name="paramValues"></param> /// <returns>a value provider</returns> public CxValueProviderCollection GetChildDataProvider( IxValueProvider paramProvider, string where, params object[] paramValues) { CxValueProviderCollection provider = new CxValueProviderCollection(); provider.AddIfNotEmpty(paramProvider); provider.AddIfNotEmpty(CxDbUtils.GetValueProvider(where, paramValues)); return provider; } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data as child one from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of child entities</param> /// <param name="paramProvider">provider of the parent/child parameter values</param> /// <param name="where">additional where clause</param> /// <param name="paramValues">values of parameters in where clause (if any)</param> /// <param name="cacheMode">entity cache mode</param> public void ReadChildData( CxDbConnection connection, DataTable dt, IxValueProvider paramProvider, string where, NxEntityDataCache cacheMode, params object[] paramValues) { ReadChildData(connection, dt, paramProvider, where, cacheMode, -1, -1, paramValues); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data as child one from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of child entities</param> /// <param name="paramProvider">provider of the parent/child parameter values</param> /// <param name="where">additional where clause</param> /// <param name="rowCount">amount of rows to get</param> /// <param name="paramValues">values of parameters in where clause (if any)</param> /// <param name="cacheMode">entity cache mode</param> /// <param name="startRowIndex">start index offset to get rows from</param> public void ReadChildData( CxDbConnection connection, DataTable dt, IxValueProvider paramProvider, string where, NxEntityDataCache cacheMode, int startRowIndex, int rowCount, params object[] paramValues) { if (!GetIsAccessGranted()) { GetEmptyDataTable(dt); return; } if (CxUtils.IsEmpty(SqlSelect)) { throw new ExMetadataException("SQL SELECT statement not defined for " + Id + " entity usage"); } if (CxUtils.IsEmpty(JoinCondition) && !IsJoinConditionInSelectClause) { throw new ExMetadataException("Parent/child join condition not defined for " + Id + " entity usage"); } CxValueProviderCollection provider = GetChildDataProvider(paramProvider, where, paramValues); string sql = GetChildDataQuery(connection, where); if (startRowIndex >= 0 && rowCount >= 0) sql = ComposePagedSqlText(connection, sql, startRowIndex, rowCount, OrderByClause); GetQueryResult(connection, dt, sql, provider, cacheMode); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data as child one from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of child entities</param> /// <param name="where">additional where clause</param> /// <param name="paramProvider">provider of all values</param> public void ReadChildData( CxDbConnection connection, DataTable dt, string where, IxValueProvider paramProvider) { ReadChildData(connection, dt, paramProvider, where, NxEntityDataCache.Default); } //---------------------------------------------------------------------------- /// <summary> /// Reads entity data as child one from the database. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="dt">data table with list of child entities</param> /// <param name="paramProvider">provider of the parent/child parameter values</param> public void ReadChildData(CxDbConnection connection, DataTable dt, IxValueProvider paramProvider) { ReadChildData(connection, dt, "", paramProvider); } //---------------------------------------------------------------------------- /// <summary> /// Returns entity usage metadata for the child with the specified ID. /// </summary> /// <param name="childId">ID of the child entity usage</param> /// <returns>entity usage metadata for the child with the specified ID</returns> public CxEntityUsageMetadata GetChildMetadata(string childId) { CxEntityUsageMetadata childEntityUsage = null; if (CxUtils.NotEmpty(childId)) { childEntityUsage = ChildEntityUsages[childId.ToUpper()].EntityUsage; } if (childEntityUsage != null) return childEntityUsage; else throw new ExMetadataException(string.Format("Child entity usage with ID=<{0}> not defined for entity usage with ID=<{1}>", childId, Id)); } //---------------------------------------------------------------------------- /// <summary> /// Returns child entity usage by the id of the target entity usage. /// </summary> /// <param name="entityUsageId">string id</param> /// <returns>child entity usage metadata object</returns> public CxChildEntityUsageMetadata GetChildEntityUsageOrInheritedByEntityUsageId(string entityUsageId) { CxEntityUsageMetadata entityUsage = Holder.EntityUsages[entityUsageId]; foreach (CxChildEntityUsageMetadata childEntityUsageMetadata in ChildEntityUsages.Values) { if (childEntityUsageMetadata.EntityUsage == entityUsage || childEntityUsageMetadata.EntityUsage.IsInheritedFrom(entityUsage)) return childEntityUsageMetadata; } return null; } //---------------------------------------------------------------------------- /// <summary> /// Generates attributes for this entity usage using information from database schema. /// </summary> /// <param name="connection">database connection to use</param> /// <param name="attributeUsage">true to generate attribute usage instead of attribute</param> /// <returns>generated attributes text</returns> public string GenerateAttributes(CxDbConnection connection, bool attributeUsage) { string sql = "select distinct c.colid, o.name as object_name, c.name as column_name,\r\n" + " t.name as type_name, c.prec as length, c.scale, c.isnullable as nullable,\r\n" + " (select 1\r\n" + " from sysobjects pk,\r\n" + " sysindexes i,\r\n" + " sysindexkeys k\r\n" + " where pk.parent_obj = c.id\r\n" + " and pk.xtype = 'PK'\r\n" + " and i.name = pk.name\r\n" + " and k.id = i.id\r\n" + " and k.indid = i.indid\r\n" + " and k.colid = c.colid\r\n" + " ) as primary_key\r\n" + " from syscolumns c,\r\n" + " sysobjects o,\r\n" + " systypes t\r\n" + " where c.id = o.id\r\n" + " and c.xtype = t.xusertype\r\n" + " and t.name not in ('sysname', 'Category')\r\n" + " and o.name = '" + DbObject + "'\r\n" + " order by c.colid"; DataTable dt = connection.GetQueryResult(sql); StringBuilder sb = new StringBuilder(); sb.Append(attributeUsage ? " <entity_usage id=\"" + Id + "\">\r\n" : " <entity id=\"" + Entity.Id + "\" id=\"" + Id + "\">\r\n"); sb.Append(attributeUsage ? " <attribute_usages>\r\n" : " <attributes>\r\n"); string padding = attributeUsage ? " " : " "; foreach (DataRow dr in dt.Rows) { string name = (string) dr["column_name"]; sb.Append(" <" + (attributeUsage ? "attribute_usage" : "attribute") + " id=\"" + name + "\"\r\n"); string type = ((string) dr["type_name"]).ToLower(); type = (type == "varchar" || type == "nvarchar" || type == "char" || type == "nchar" || type == "udt_longstring" || type == "udt_text" || type == "udt_string" ? CxAttributeMetadata.TYPE_STRING : type == "text" || type == "ntext" ? CxAttributeMetadata.TYPE_LONGSTRING : type == "datetime" || type == "smalldatetime" ? CxAttributeMetadata.TYPE_DATE : type == "bigint" || type == "int" || type == "udt_objid" || type == "smallint" || type == "tinyint" ? CxAttributeMetadata.TYPE_INT : type == "decimal" || type == "numeric" || type == "udt_currency" || type == "udt_curr_rate" || type == "money" || type == "smallmoney" || type == "float" || type == "real" ? CxAttributeMetadata.TYPE_FLOAT : type == "bit" ? CxAttributeMetadata.TYPE_BOOLEAN : "??? " + type + " ???"); bool visible = true; if (!CxUtils.IsNull(dr["primary_key"]) && Convert.ToInt32(dr["primary_key"]) == 1) { sb.Append(padding + "primary_key=\"true\"\r\n"); if (type == CxAttributeMetadata.TYPE_INT) { sb.Append(padding + "visible=\"false\"\r\n"); sb.Append(padding + "editable=\"false\"\r\n"); sb.Append(padding + "default=\"=@sequence\"\r\n"); visible = false; } } if (visible) { sb.Append(padding + "caption=\"" + name + "\"\r\n"); } sb.Append(padding + "type=\"" + type + "\"\r\n"); if (dr["length"] != DBNull.Value) { int length = Convert.ToInt32(dr["length"]); sb.Append(padding + "max_length=\"" + length + "\"\r\n"); } if (!CxUtils.IsNull(dr["scale"]) && Convert.ToInt32(dr["scale"]) != 0) { sb.Append(padding + "scale=\"" + dr["scale"] + "\"\r\n"); } if ((int) dr["nullable"] == 0) { sb.Append(padding + "nullable=\"false\"\r\n"); } /*string control = (type == CxAttributeMetadata.TYPE_BOOLEAN ? CxAttributeMetadata.WIN_CONTROL_CHECKBOX : type == CxAttributeMetadata.TYPE_DATE ? CxAttributeMetadata.WIN_CONTROL_DATE : type == CxAttributeMetadata.TYPE_INT || type == CxAttributeMetadata.TYPE_FLOAT ? CxAttributeMetadata.WIN_CONTROL_SPIN : CxAttributeMetadata.WIN_CONTROL_TEXT); sb.Append(" control=\"" + control + "\"\r\n");*/ /*int width = Math.Min(Math.Max(length * 10, 30), 200); sb.Append(" grid_width=\"" + width + "\"\r\n");*/ sb.Append(" />\r\n"); } sb.Append(attributeUsage ? " </attribute_usages>\r\n" : " </attributes>\r\n"); sb.Append(attributeUsage ? " </entity_usage>\r\n" : " </entity>\r\n"); sb.Append(" <!-- -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- -->\r\n"); return sb.ToString(); } //---------------------------------------------------------------------------- /// <summary> /// Generates attributes for this entity usage using information from database schema. /// </summary> /// <param name="connection">database connection to use</param> /// <returns>generated attributes text</returns> public string GenerateAttributes(CxDbConnection connection) { return GenerateAttributes(connection, false); } //---------------------------------------------------------------------------- /// <summary> /// List of custom attributes. /// </summary> public IList<CxAttributeMetadata> CustomAttributes { get { List<CxAttributeMetadata> list = new List<CxAttributeMetadata>(); foreach (CxAttributeMetadata attribute in Attributes) { if (attribute.Custom) { list.Add(attribute); } } return list; } } //------------------------------------------------------------------------- /// <summary> /// List of attributes with controls defined in design-time. /// </summary> public IList<CxAttributeMetadata> ManualAttributes { get { List<CxAttributeMetadata> list = new List<CxAttributeMetadata>(); foreach (CxAttributeMetadata attribute in Attributes) { if (attribute.Manual) { list.Add(attribute); } } return list; } } //------------------------------------------------------------------------- /// <summary> /// Returns object that desctibes what to edit depending on the column name. /// </summary> /// <param name="columnName">name of the column to find description for</param> /// <param name="exact">if true return only explicitly specified definition</param> /// <returns>object that desctibes what to edit depending on the column name</returns> public CxEntityUsageToEditMetadata GetEntityUsageToEdit(string columnName, bool exact) { foreach (CxEntityUsageToEditMetadata edit in m_EntityUsagesToEdit) { if (edit.Complies(columnName, exact)) { return edit; } } return null; } //------------------------------------------------------------------------- /// <summary> /// The id of the attribute to store the states of each sub-tab into. /// For WinForms only. /// </summary> public string WinSubTabStateAttributeId { get { return this["win_sub_tab_state_attribute_id"]; } } //------------------------------------------------------------------------- /// <summary> /// The attribute to store the state of each sub-tab into. /// For WinForms only. /// </summary> public CxAttributeMetadata WinSubTabStateAttribute { get { return GetAttribute(WinSubTabStateAttributeId); } } //------------------------------------------------------------------------- /// <summary> /// Returns true if this entity usage is default for the entity. /// </summary> public bool IsDefault { get { return CxBool.Parse(this["is_default"], false); } } //------------------------------------------------------------------------- /// <summary> /// Returns true if the entity usage can be involved into querying thru Query Builder UI. /// </summary> public bool IsQueryable { get { return CxBool.Parse(this["is_queryable"], false); } } //------------------------------------------------------------------------- /// <summary> /// Returns default entity usage metadata object for the given entity. /// </summary> override public CxEntityUsageMetadata DefaultEntityUsage { get { // Returns null since the property is applicable for entity metadata only. return null; } } //------------------------------------------------------------------------- /// <summary> /// Replaces text placeholders with actual property values. /// Placeholders are in format: %property_name%. /// </summary> /// <param name="text">text to replace</param> /// <returns>text with placeholders replaced to values</returns> public string ReplacePlaceholders(string text) { if (CxUtils.NotEmpty(text)) { CxEntityUsagePlaceholderManager placeholderManager = new CxEntityUsagePlaceholderManager(this); text = placeholderManager.ReplacePlaceholders(text); text = CxText.RemovePlaceholders(text, '%'); } return text; } //------------------------------------------------------------------------- /// <summary> /// Returns entity usage ID to use for entity commands. /// </summary> public string CommandEntityUsageId { get { return this["command_entity_usage_id"]; } } //------------------------------------------------------------------------- /// <summary> /// Returns entity usage object to use for entity commands. /// </summary> public CxEntityUsageMetadata CommandEntityUsage { get { if (CxUtils.NotEmpty(CommandEntityUsageId)) { return Holder.EntityUsages[CommandEntityUsageId]; } return this; } } //------------------------------------------------------------------------- /// <summary> /// Returns an id of the entity usage the visibility of the current /// entity usage depends on. /// </summary> public string VisibilityReferenceEntityUsageId { get { return this["visibility_ref_entity_usage_id"]; } set { this["visibility_ref_entity_usage_id"] = value; } } //------------------------------------------------------------------------- /// <summary> /// Returns an entity usage the visibility of the current /// entity usage depends on. /// </summary> public CxEntityUsageMetadata VisibilityReferenceEntityUsage { get { return Holder.EntityUsages.Find(VisibilityReferenceEntityUsageId); } } //------------------------------------------------------------------------- /// <summary> /// Returns true if the entity usage is visible. /// </summary> protected override bool GetIsVisible() { CxEntityUsageMetadata entityUsage = VisibilityReferenceEntityUsage; if (entityUsage != null && entityUsage != this) { return entityUsage.Visible; } return base.GetIsVisible(); } //------------------------------------------------------------------------- /// <summary> /// Returns empty data table with columns filled by attribute metadata. /// </summary> public CxGenericDataTable GetEmptyDataTable() { if (m_EmptyDataTable == null) { CxGenericDataTable dt = new CxGenericDataTable(); EmptyDataSource(dt); m_EmptyDataTable = dt; } return m_EmptyDataTable; } //------------------------------------------------------------------------- /// <summary> /// Fills data table with columns by attribute metadata. /// </summary> public void GetEmptyDataTable(DataTable dt) { dt.Clear(); dt.Columns.Clear(); dt.Rows.Clear(); dt.Columns.AddRange(GetDataColumnsFromAttributes()); } //------------------------------------------------------------------------- /// <summary> /// Fills the given data source with columns by attribute metadata. /// </summary> public void EmptyDataSource(IxGenericDataSource dataSource) { dataSource.ClearDataAndSchema(); dataSource.PopulateColumns(GetDataColumnsFromAttributes()); } //------------------------------------------------------------------------- /// <summary> /// Returns an array of data columns created by the entity's attributes. /// </summary> /// <returns>an array of data columns</returns> public DataColumn[] GetDataColumnsFromAttributes() { DataColumn[] columns = new DataColumn[Attributes.Count]; for (int i = 0; i < Attributes.Count; i++) { CxAttributeMetadata attr = Attributes[i]; DataColumn dc = new DataColumn(attr.Id, attr.GetPropertyType()); if (dc.DataType == typeof(string) && attr.Type == CxAttributeMetadata.TYPE_LONGSTRING) dc.MaxLength = int.MaxValue; columns[i] = dc; } return columns; } //------------------------------------------------------------------------- /// <summary> /// Returns true if access to the entity usage is granted. /// </summary> public bool GetIsAccessGranted() { if (Holder != null && Holder.Security != null) { return Holder.Security.GetRight(this); } return true; } //------------------------------------------------------------------------- /// <summary> /// Returns access rule WHERE clause (horizontal security). /// </summary> protected string GetAccessWhereClause() { string whereClause = ""; if (Holder != null) { // Apply horizontal security rule defined in the object permissions. if (Holder.Security != null) { whereClause = CxDbUtils.ComposeWhereClause(whereClause, Holder.Security.GetWhereClause(this)); } // Apply workspace condition. string workspaceClause = GetWorkspaceWhereClause(); if (CxUtils.NotEmpty(workspaceClause)) { whereClause = CxDbUtils.ComposeWhereClause(whereClause, workspaceClause); } } return whereClause; } //------------------------------------------------------------------------- /// <summary> /// Returns workspace filter WHERE clause or null if clause is not needed. /// </summary> /// <returns>workspace filter WHERE clause or null if clause is not needed</returns> protected string GetWorkspaceWhereClause() { string clause = null; if (Holder.UserPermissionProvider != null && IsWorkspaceDependent) { if (IsFilteredByCurrentWorkspace) { // Filter by current selected workspace. clause = "WorkspaceId in (0, :Application$CurrentWorkspaceId)"; } else if (IsFilteredByAvailableWorkspaces) { // Filter by workspaces available for the current user. if (Holder.ApplicationValueProvider != null) { string valueListStr = "0"; DataTable dt = (DataTable) Holder.ApplicationValueProvider["Application$WorkspaceAvailableForUserTable"]; if (dt != null) { foreach (DataRow dr in dt.Rows) { if (CxUtils.NotEmpty(dr["WorkspaceId"])) { valueListStr += "," + dr["WorkspaceId"]; } } } clause = "WorkspaceId in (" + valueListStr + ")"; } } string customClause = GetCustomWorkspaceWhereClause(clause); if (CxUtils.NotEmpty(customClause)) { clause = customClause; } } return clause; } //------------------------------------------------------------------------- /// <summary> /// Returns custom WHERE clause (can be provided by the entity). /// </summary> protected string GetCustomWhereClause() { if (EntityInstance != null) { return EntityInstance.GetCustomWhereClause(); } return null; } //------------------------------------------------------------------------- /// <summary> /// Returns custom workspace filter WHERE clause /// or null if custom workspace clause is not needed. /// </summary> /// <param name="defaultWorkspaceClause">default workspace WHERE clause</param> /// <returns>custom clause or null if no custom clause should be applied</returns> protected string GetCustomWorkspaceWhereClause(string defaultWorkspaceClause) { if (EntityInstance != null) { return EntityInstance.GetCustomWorkspaceWhereClause(defaultWorkspaceClause); } return null; } //------------------------------------------------------------------------- /// <summary> /// Returns list of DB file attributes. /// </summary> public IList<CxAttributeMetadata> DbFileAttributes { get { List<CxAttributeMetadata> list = new List<CxAttributeMetadata>(); foreach (CxAttributeMetadata attr in Attributes) { if (attr.IsDbFile) { list.Add(attr); } } return list; } } //------------------------------------------------------------------------- /// <summary> /// Returns first found DB file attribute. /// </summary> public CxAttributeMetadata GetFirstDbFileAttribute() { foreach (CxAttributeMetadata attr in Attributes) { if (attr.IsDbFile) { return attr; } } return null; } //------------------------------------------------------------------------- /// <summary> /// Adds child entity usages to the given list. /// </summary> /// <param name="list">list to add child entity usages to</param> protected void AddChildEntityUsagesToList(IList<CxEntityUsageMetadata> list) { foreach (CxChildEntityUsageMetadata childMetadata in ChildEntityUsagesList) { if (childMetadata.EntityUsage != null && list.IndexOf(childMetadata.EntityUsage) < 0) { list.Add(childMetadata.EntityUsage); childMetadata.EntityUsage.AddChildEntityUsagesToList(list); } } } //------------------------------------------------------------------------- /// <summary> /// Returns complete list of all child entity usages (iterates throw all levels). /// </summary> /// <returns>list of CxEntityUsage objects</returns> public IList<CxEntityUsageMetadata> GetChildEntityUsagesRecurrent() { List<CxEntityUsageMetadata> list = new List<CxEntityUsageMetadata>(); AddChildEntityUsagesToList(list); return list; } //------------------------------------------------------------------------- /// <summary> /// Returns default command for the entity usage. /// </summary> public CxCommandMetadata GetDefaultCommand() { foreach (CxCommandMetadata command in Commands) { if (command.IsDefault) { return command; } } return null; } //------------------------------------------------------------------------- /// <summary> /// Adds record limitation clause to the original SQL text. /// </summary> /// <param name="connection"></param> /// <param name="sqlText"></param> /// <param name="recordCountLimit"></param> /// <returns></returns> protected string ComposeRecordLimitSqlText( CxDbConnection connection, string sqlText, int recordCountLimit) { return recordCountLimit > 0 ? connection.ScriptGenerator.GetTopRecordsSqlText(sqlText, recordCountLimit) : sqlText; } //------------------------------------------------------------------------- /// <summary> /// Adds record limitation clause to the original SQL text. /// </summary> /// <param name="connection"></param> /// <param name="sqlText"></param> /// <returns></returns> protected string ComposeRecordLimitSqlText( CxDbConnection connection, string sqlText) { return IsRecordCountLimited ? ComposeRecordLimitSqlText(connection, sqlText, RecordCountLimit) : sqlText; } //------------------------------------------------------------------------- /// <summary> /// Composes an SQL statement basing on the given statement and the /// given record frame to get. /// </summary> /// <param name="connection">database connection</param> /// <param name="sqlText">SQL text to use</param> /// <param name="startRowIndex">starting index of records to get by the statement</param> /// <param name="rowsAmount">amount of records to get by the statement</param> /// <param name="orderByClause">sorting conditions</param> /// <returns>composed statement</returns> protected string ComposePagedSqlText( CxDbConnection connection, string sqlText, int startRowIndex, int rowsAmount, string orderByClause) { return connection.ScriptGenerator.GetPagedScriptForSelect( sqlText, startRowIndex, rowsAmount, ComposeOrderClauseForPagedSql(connection, orderByClause)); } //------------------------------------------------------------------------- /// <summary> /// Composes the complete order by clause for paged queries. /// </summary> /// <param name="connection">database connection</param> /// <param name="orderByClause">original order by clause</param> /// <returns>composed clause</returns> protected string ComposeOrderClauseForPagedSql( CxDbConnection connection, string orderByClause) { // Validation if (connection == null) throw new ExNullArgumentException("connection"); List<string> statements = new List<string>(); CxSortDescriptorList sortDescriptors = new CxSortDescriptorList(); if (!string.IsNullOrEmpty(orderByClause)) statements.Add(orderByClause); foreach (CxAttributeMetadata attributeMetadata in PrimaryKeyAttributes) { sortDescriptors.Add(new CxSortDescriptor(attributeMetadata.Id, ListSortDirection.Ascending)); } statements.Add(connection.ScriptGenerator.GetOrderByClause(sortDescriptors)); return string.Join(",", statements.ToArray()); } //------------------------------------------------------------------------- /// <summary> /// Returns cache key used to cache data returned by SQL statements. /// </summary> /// <param name="sql"></param> /// <param name="provider"></param> /// <returns></returns> protected string GetSqlSelectCacheKey( string sql, IxValueProvider provider) { string fullKey = CxUtils.Nvl(sql, "NO_SQL") + "\r\nPARAMS:\r\n"; IList<string> paramNames = CxDbParamParser.GetList(sql, true); foreach (string paramName in paramNames) { string paramValue = provider != null ? CxUtils.ToString(provider[paramName]) : ""; fullKey += paramName + "=" + paramValue + "\r\n"; } string hashKey = Convert.ToBase64String( new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(fullKey))); hashKey = EntityId + "." + hashKey; return hashKey; } //------------------------------------------------------------------------- /// <summary> /// Executes select statement and returns query result. /// </summary> /// <param name="connection">a connection context to get query result through</param> /// <param name="dt">a data table to load data to</param> /// <param name="sql">a SQL statement to be used to get data</param> /// <param name="valueProvider">a value provider to be used to provide the SQL query with values</param> /// <param name="cacheMode">entity cache mode</param> public void GetQueryResult( CxDbConnection connection, DataTable dt, string sql, IxValueProvider valueProvider, NxEntityDataCache cacheMode) { GetQueryResult(connection, dt, sql, valueProvider, cacheMode, null); } //------------------------------------------------------------------------- /// <summary> /// Executes select statement and returns query result. /// </summary> /// <param name="connection">a connection context to get query result through</param> /// <param name="dt">a data table to load data to</param> /// <param name="sql">a SQL statement to be used to get data</param> /// <param name="valueProvider">a value provider to be used to provide the SQL query with values</param> /// <param name="cacheMode">entity cache mode</param> /// <param name="customPreProcessingHandler">a custom pre-processing handler to be applied to /// the data obtained</param> public void GetQueryResult( CxDbConnection connection, DataTable dt, string sql, IxValueProvider valueProvider, NxEntityDataCache cacheMode, DxCustomPreProcessDataSource customPreProcessingHandler) { IxValueProvider preparedProvider = PrepareValueProvider(valueProvider); bool isCacheEnabled = cacheMode != NxEntityDataCache.NoCache && IsCached && Holder.IsEntityDataCacheEnabled; if (isCacheEnabled) { string cacheKey = GetSqlSelectCacheKey(sql, preparedProvider); object lockObject; lock (this) { lockObject = m_EntityDataCacheLockObjectMap[cacheKey]; if (lockObject == null) { lockObject = new object(); m_EntityDataCacheLockObjectMap[cacheKey] = lockObject; } } DataTable cachedTable; lock (lockObject) { cachedTable = (DataTable) Holder.GetEntityDataCacheObject(cacheKey); if (cachedTable == null) { cachedTable = new DataTable(); DoSqlSelectRunBefore(connection); connection.GetQueryResult(cachedTable, sql, preparedProvider); Holder.SetEntityDataCacheObject(cacheKey, cachedTable); } } CxData.CopyDataTable(cachedTable, dt); } else { DoSqlSelectRunBefore(connection); connection.GetQueryResult(dt, sql, preparedProvider); } PreProcessDataSourceEntirely(dt as IxGenericDataSource, customPreProcessingHandler); } //------------------------------------------------------------------------- /// <summary> /// Invoked immediately after data table is read by the entity usage metadata. /// </summary> /// <param name="dataSource">data source containing entity or entity list</param> /// <param name="customPreProcessingHandler">a custom pre-processing handler to be applied to /// the data obtained</param> public void PreProcessDataSourceEntirely( IxGenericDataSource dataSource, DxCustomPreProcessDataSource customPreProcessingHandler) { if (dataSource != null && EntityInstance != null) { // Data source EntityInstance.PreProcessDataSource(dataSource, customPreProcessingHandler); // Data columns for (int i = 0; i < dataSource.Columns.Count; i++) { PreProcessDataColumn(dataSource.Columns[i]); } // Data rows for (int i = 0; i < dataSource.Count; i++) { EntityInstance.PreProcessDataRow(dataSource[i]); } } } //------------------------------------------------------------------------- /// <summary> /// Preprocesses the given data-column accordingly to the entity's attributes. /// </summary> /// <param name="column">a data column to be pre-processed</param> public void PreProcessDataColumn(DataColumn column) { if (column.DataType == typeof(string)) { CxAttributeMetadata attribute = GetAttribute(column.ColumnName); if (attribute != null) { if (column.DataType == typeof(string) && attribute.Type == CxAttributeMetadata.TYPE_LONGSTRING) column.MaxLength = int.MaxValue; } } } //------------------------------------------------------------------------- /// <summary> /// True if hierarchical entity usage should be always expanded in the grid. /// </summary> public bool IsAlwaysExpanded { get { return this["always_expanded"] == "true"; } } //------------------------------------------------------------------------- /// <summary> /// Retruns list of entity usages which use this entity usage as inherited entity usage. /// </summary> public IList<CxEntityUsageMetadata> DirectDescendantEntityUsages { get { if (m_DirectDescendantEntityUsages == null) { m_DirectDescendantEntityUsages = GetDirectlyInheritedEntityUsages(); } return m_DirectDescendantEntityUsages; } } //------------------------------------------------------------------------- /// <summary> /// Returns list of all descendant entity usages. /// </summary> protected void GetDescendantEntityUsagesList( CxEntityUsageMetadata entityUsage, IList<CxEntityUsageMetadata> list, Hashtable checkedMap) { foreach (CxEntityUsageMetadata descendant in entityUsage.DirectDescendantEntityUsages) { if (!checkedMap.ContainsKey(descendant)) { list.Add(descendant); checkedMap[descendant] = true; GetDescendantEntityUsagesList(descendant, list, checkedMap); } } } //------------------------------------------------------------------------- /// <summary> /// Returns list of entity usages which use this entity usage as inherited entity usage. /// </summary> public IList<CxEntityUsageMetadata> DescendantEntityUsages { get { if (m_DescendantEntityUsages == null) { m_DescendantEntityUsages = new List<CxEntityUsageMetadata>(); Hashtable checkedMap = new Hashtable(); GetDescendantEntityUsagesList(this, m_DescendantEntityUsages, checkedMap); } return m_DescendantEntityUsages; } } //------------------------------------------------------------------------- /// <summary> /// Returns global collection of entity usages. /// </summary> public CxEntityUsagesMetadata EntityUsages { get { return Holder != null && Holder.EntityUsages != null ? Holder.EntityUsages : m_EntityUsages; } set { m_EntityUsages = value; } } //------------------------------------------------------------------------- /// <summary> /// Returns object type code for localization. /// </summary> override public string LocalizationObjectTypeCode { get { return LOCALIZATION_OBJECT_TYPE_CODE; } } //---------------------------------------------------------------------------- /// <summary> /// Returns list of metadata objects properties was inherited from. /// </summary> override public IList<CxMetadataObject> InheritanceList { get { List<CxMetadataObject> list = new List<CxMetadataObject>(); if (InheritedEntityUsage != null) { list.Add(InheritedEntityUsage); } list.Add(Entity); return list; } } //---------------------------------------------------------------------------- /// <summary> /// Returns true if this entity usage is inherited from the given entity usage. /// </summary> public bool IsInheritedFrom(CxEntityUsageMetadata entityUsage) { CxEntityUsageMetadata ancestor = this; while (ancestor != null) { if (ancestor == entityUsage) { return true; } ancestor = ancestor.InheritedEntityUsage; } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns true if this entity usage is inherited from the given entity usage. /// </summary> /// <param name="entityUsageId">entity usage id to be evaluated</param> /// <returns>true if this entity usage is inherited from the given entity usage</returns> public bool IsInheritedFrom(string entityUsageId) { CxEntityUsageMetadata entityUsage = Holder.EntityUsages[entityUsageId]; return IsInheritedFrom(entityUsage); } //---------------------------------------------------------------------------- /// <summary> /// Returns true if given entity usage metadata is inherited from this /// entity usage or vise versa. /// </summary> public bool IsAncestorOrDescendant(CxEntityUsageMetadata entityUsage) { if (entityUsage != null) { return IsInheritedFrom(entityUsage) || entityUsage.IsInheritedFrom(this); } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns true if given entity usage contains all this entity usage attributes. /// </summary> public bool IsCompatibleByAttributes(CxEntityUsageMetadata entityUsage) { if (entityUsage != null && entityUsage.EntityId == EntityId) { if (entityUsage.Id == Id) { return true; } foreach (CxAttributeMetadata attr in Attributes) { if (entityUsage.GetAttribute(attr.Id) == null) { return false; } } return true; } return false; } //---------------------------------------------------------------------------- /// <summary> /// Returns list of entity usages inherited from this entity. /// </summary> override public IList<CxEntityUsageMetadata> GetInheritedEntityUsages() { List<CxEntityUsageMetadata> list = new List<CxEntityUsageMetadata>(); foreach (CxEntityUsageMetadata entityUsage in Holder.EntityUsages.Items) { if (entityUsage.InheritedEntityUsage == this) { list.Add(entityUsage); list.AddRange(entityUsage.GetInheritedEntityUsages()); } } return list; } //---------------------------------------------------------------------------- /// <summary> /// Returns list of entity usages which are referenced by attribute properties. /// </summary> /// <returns>list of CxEntityMetadata objects or null</returns> override public IList<CxEntityMetadata> GetReferencedEntities() { UniqueList<CxEntityMetadata> result = new UniqueList<CxEntityMetadata>(); result.Add(Entity); if (FileLibraryCategoryEntityUsage != null && FileLibraryCategoryEntityUsage != this) result.Add(FileLibraryCategoryEntityUsage); foreach (CxAttributeMetadata attribute in Attributes) result.AddRange(attribute.GetReferencedEntities()); foreach (CxCommandMetadata command in Commands) result.AddRange(command.GetReferencedEntities()); foreach (CxEntityUsageMetadata entityUsage in GetDirectlyInheritedEntityUsages()) { result.Add(entityUsage); result.AddRange(entityUsage.GetReferencedEntities()); } return result; } //---------------------------------------------------------------------------- /// <summary> /// Creates instance of the entity class (defined as entity_class_id). /// </summary> /// <returns>created instance</returns> public object CreateEntityInstance() { return CxType.CreateInstance( EntityClass, new Type[] { typeof(CxEntityUsageMetadata) }, new object[] { this }); } //------------------------------------------------------------------------- /// <summary> /// Empty entity instance for internal purposes. /// </summary> protected IxEntity EntityInstance { get { if (m_EntityInstance == null) { m_EntityInstance = CreateEntityInstance(); } return m_EntityInstance as IxEntity; } } //------------------------------------------------------------------------- public override CxAttributeMetadata[] GetPrimaryKeyAttributes(int dbObjectIndex) { CxAttributeMetadata[] result = EntityInstance.GetPrimaryKeyAttributes(dbObjectIndex); return result; } //------------------------------------------------------------------------- /// <summary> /// Compares value providers by primary key values. /// </summary> /// <param name="p1">provider #1</param> /// <param name="p2">provider #2</param> /// <returns>true if equals</returns> public bool CompareByPK(IxValueProvider p1, IxValueProvider p2) { if (p1 != null && p2 != null) { CxAttributeMetadata[] pkAttrs = PrimaryKeyAttributes; if (pkAttrs != null && pkAttrs.Length > 0) { foreach (CxAttributeMetadata pkAttr in pkAttrs) { if (!CxUtils.Compare(p1[pkAttr.Id], p2[pkAttr.Id])) { return false; } } return true; } } return false; } //------------------------------------------------------------------------- /// <summary> /// Returns a list of attributes that may contain the entity usage id /// the entity instance depends on. /// </summary> /// <returns></returns> public CxAttributeMetadata[] GetEntityInstanceDependentAttributesToCalculateAutoRefreshBy() { List<CxAttributeMetadata> result = new List<CxAttributeMetadata>(); foreach (CxAttributeMetadata attributeMetadata in Attributes) { if (attributeMetadata.Type == CxAttributeMetadata.TYPE_LINK && attributeMetadata.HyperLinkAutoRefresh) { if (GetValueDefinedAttribute(attributeMetadata) != null) { if (CxUtils.NotEmpty(attributeMetadata.HyperLinkEntityUsageAttrId)) result.Add(GetAttribute(attributeMetadata.HyperLinkEntityUsageAttrId)); } } } return result.ToArray(); } //------------------------------------------------------------------------- /// <summary> /// True if entity usage has at least one referencing column with /// auto refresh flag set to true. /// </summary> public bool HasAutoRefreshableAttributes( CxEntityUsageMetadata changedEntityUsageMetadata) { bool result = false; foreach (CxAttributeMetadata attributeMetadata in Attributes) { if (attributeMetadata.Type == CxAttributeMetadata.TYPE_LINK && attributeMetadata.HyperLinkAutoRefresh) { if (GetValueDefinedAttribute(attributeMetadata) != null) { if (attributeMetadata.HyperLinkEntityUsageId == changedEntityUsageMetadata.Id) { result = true; } } } if (!result) { result = attributeMetadata.ReferenceAutoRefresh && ((IList) attributeMetadata.ReferenceEntityUsages).Contains(changedEntityUsageMetadata); } if (result) break; } return result; } //------------------------------------------------------------------------- /// <summary> /// Returns true if refresh of the current entity depends on the given /// entity usage. I.e. current entity should be refreshed when the given /// entity usage is changed. /// </summary> /// <param name="entityUsage">entity usage to check dependency on</param> /// <returns>true if refresh of the current entity depends on the given entity usage</returns> public bool IsRefreshDependentOn(CxEntityUsageMetadata entityUsage) { if (entityUsage != null) { if (IsAncestorOrDescendant(entityUsage)) { return true; } IList<string> entityUsageIds = CxText.DecomposeWithSeparator(RefreshDependsOnEntityUsages, ","); foreach (string entityUsageId in entityUsageIds) { CxEntityUsageMetadata dependency = Holder.EntityUsages.Find(entityUsageId); if (dependency != null && entityUsage.IsInheritedFrom(dependency)) { return true; } } } return false; } //------------------------------------------------------------------------- /// <summary> /// Defines an attribute with the given id and initial values on the level of /// the current entity metadata. Overriden. /// </summary> /// <param name="attributeId">id of the attribute to be added</param> /// <param name="initialValues">initial values of the attribute to be added</param> /// <returns>defined attribute metadata</returns> public override CxAttributeMetadata DefineEntityAttribute( string attributeId, IDictionary<string, string> initialValues) { return DefineEntityAttribute(attributeId, initialValues, "attribute_usage"); } //------------------------------------------------------------------------- /// <summary> /// Returns a list of direct descendants of the current entity usage. /// </summary> /// <returns>a list of direct descendants</returns> public override IList<CxEntityUsageMetadata> GetDirectlyInheritedEntityUsages() { List<CxEntityUsageMetadata> list = new List<CxEntityUsageMetadata>(); foreach (CxEntityUsageMetadata entityUsage in Holder.EntityUsages.Items) { if (entityUsage.InheritedEntityUsage == this) list.Add(entityUsage); } return list; } //------------------------------------------------------------------------- /// <summary> /// Returns a list of child entity usage ids built on the ground of the given childs. /// </summary> /// <param name="childs">childs to be used to build the result</param> /// <returns>list of child entity usage ids</returns> public IList<string> GetIdsFromChildEntityUsage(IEnumerable<CxChildEntityUsageMetadata> childs) { UniqueList<string> result = new UniqueList<string>(); foreach (CxChildEntityUsageMetadata child in childs) { result.Add(child.Id); } return result; } //------------------------------------------------------------------------- /// <summary> /// Returns a list of child entity usages built on the ground of the given attribute ids. /// </summary> /// <param name="childEntityUsageIds">child entity usage ids to be used to build the result</param> /// <returns>list of attributes</returns> public IList<CxChildEntityUsageMetadata> GetChildEntityUsagesFromIds(IEnumerable<string> childEntityUsageIds) { // Validate if (childEntityUsageIds == null) throw new ExNullArgumentException("childEntityUsageIds"); UniqueList<CxChildEntityUsageMetadata> result = new UniqueList<CxChildEntityUsageMetadata>(); foreach (string childEntityUsageId in childEntityUsageIds) { CxChildEntityUsageMetadata childEntityUsage = GetChildEntityUsage(childEntityUsageId); #if DEBUG //if (attribute == null) // throw new ExException( // string.Format("Cannot find attribute by its id: <{0}.{1}>", Id, attributeId), new ExNullReferenceException("attribute")); #endif result.Add(childEntityUsage); } return result; } //------------------------------------------------------------------------- /// <summary> /// Returns child entity usage names for new added child entity usages that are not /// included into the child entity usage order. /// </summary> protected internal UniqueList<string> NewChildEntityUsageNames { get { if (m_NewChildEntityUsageNames == null) { m_NewChildEntityUsageNames = new UniqueList<string>(StringComparer.OrdinalIgnoreCase); if (CxUtils.NotEmpty(this["known_child_entity_usages"])) { IList<string> list = CxText.DecomposeWithWhiteSpaceAndComma(this["known_child_entity_usages"]); UniqueList<string> oldChildEntityUsageList = new UniqueList<string>(StringComparer.OrdinalIgnoreCase); oldChildEntityUsageList.AddRange(CxList.ToList<string>(list)); foreach (CxChildEntityUsageMetadata child in ChildEntityUsagesList) { if (!oldChildEntityUsageList.Contains(child.Id)) { m_NewChildEntityUsageNames.Add(child.Id); } } } } return m_NewChildEntityUsageNames; } } //------------------------------------------------------------------------- /// <summary> /// True if Entity should be saved /// </summary> public bool IsAlwaysSaveOnEdit { get { return this["always_save_on_edit"] == "true"; } } //------------------------------------------------------------------------- } }
namespace Westbot { class AcceptState { public const bool Accept = false; public const bool Error = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Selected : MonoBehaviour { Renderer rend; // TODO pretty sure this can be optimized a tad easier private void Awake() { rend = GetComponent<Renderer>(); rend.material.color = Color.blue; } private void Update() { } public void Deselect() { rend.material.color = Color.blue; } public void Select() { rend.material.color = Color.cyan; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainMenuLogic : MonoBehaviour { [SerializeField] Button StartButton; // Setting the first button to be highlighted for PS4 controller selection through UI Elements private void Start() { if (StartButton) { StartButton.Select(); } } // Functioins below are one for each button individually public void onStartClicked() { Debug.Log("Start Clicked"); SceneManager.LoadScene("GameScene"); } public void onOptionsClicked() { Debug.Log("Options CLicked"); UiManager.instance.SetUIState(UIState.OptionsMenu); } public void onQuitClicked() { Debug.Log("Quit Clicked"); Application.Quit(); } }
using System; using System.Collections; using System.Collections.Generic; namespace OCP { /** * Factory class creating instances of \OCP\ITags * * A tag can be e.g. 'Family', 'Work', 'Chore', 'Special Occation' or * anything else that is either parsed from a vobject or that the user chooses * to add. * Tag names are not case-sensitive, but will be saved with the case they * are entered in. If a user already has a tag 'family' for a type, and * tries to add a tag named 'Family' it will be silently ignored. * @since 6.0.0 */ public interface ITagManager { /** * Create a new \OCP\ITags instance and load tags from db for the current user. * * @see \OCP\ITags * @param string type The type identifier e.g. 'contact' or 'event'. * @param array defaultTags An array of default tags to be used if none are stored. * @param boolean includeShared Whether to include tags for items shared with this user by others. * @param string userId user for which to retrieve the tags, defaults to the currently * logged in user * @return \OCP\ITags * @since 6.0.0 - parameter includeShared and userId were added in 8.0.0 */ ITags load(string type, IList<ITags> defaultTags, bool includeShared = false, string userId = null); } }
using WUIClient.Gizmos; using WUIShared.Objects; namespace WUIClient.Tools { public class ScaleTool : Tool { private ScaleGizmo gizmo; private GameObject selected; public ScaleTool() { gizmo = new ScaleGizmo(); } protected override void OnSelect() { } protected override void OnUpdate() { if (WMouse.LeftMouseClick()) { GameObject obj = WMouse.GetGameObjectUnderneathMouse(Game1.instance.world, false); if (obj != null) { selected = obj; if (gizmo.Parent == null) Game1.gizmoWorld.AddChild(gizmo); gizmo.UseOnBounds(selected.transform.Bounds); } } if (WMouse.RightMouseClick()) { selected = null; gizmo.Remove(); } if (selected != null) { selected.transform.Size = gizmo.GetSize(); selected.transform.Position = gizmo.GetPosition(); gizmo.UseOnBounds(selected.transform.Bounds); } } protected override void OnDeselect() { selected = null; gizmo.Remove(); } } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System; using System.Collections.Generic; using System.Runtime.Serialization; using Framework.Db; using Framework.Metadata; namespace Framework.Remote { [DataContract] public sealed class CxClientEntityMetadata : IxErrorContainer { [DataMember] public readonly string EntityId; [DataMember] public readonly string Id; [DataMember] public readonly string SingleCaption; [DataMember] public readonly string PluralCaption; [DataMember] public readonly string FrameClassId; [DataMember] public readonly string ClientClassId; [DataMember] public readonly bool SlFilterOnStart; [DataMember] public readonly bool IsAlwaysSaveOnEdit; [DataMember] public readonly Dictionary<string, CxClientAttributeMetadata> Attributes = new Dictionary<string, CxClientAttributeMetadata>(); [DataMember] public readonly List<string> EditableAttributes = new List<string>(); [DataMember] public readonly List<string> GridOrderedAttributes = new List<string>(); [DataMember] public readonly CxClientEntityMetadata[] ChildEntities; [DataMember] public readonly CxClientCommandMetadata[] Commands; [DataMember] public readonly string EditControllerClassId; [DataMember] public readonly string EditFrameId; [DataMember] public List<string> JoinParamsNames { get; private set; } [DataMember] public List<string> WhereParamsNames { get; private set; } [DataMember] public List<string> FilterableIds { get; private set; } [DataMember] public CxExceptionDetails Error { get; internal set; } [DataMember] public bool ApplyDefaultFilter { get; internal set; } /// <summary> /// It is used to switch off find feature on the entity list. (true by default) /// </summary> [DataMember] public bool IsFilterEnabled { get; internal set; } [DataMember] public Dictionary<string, object> ApplicationValues = new Dictionary<string, object>(); [DataMember] public string ImageId { get; set; } [DataMember] public bool SaveAndStayCommand { get; set; } [DataMember] public bool IsPagingEnabled { get; set; } [DataMember] public bool RefreshParentAfterSave { get; set; } [DataMember] public new List<CxClientParentEntity> ParentEntities { get; set; } [DataMember] public bool MultipleGridEdit { get; set; } //---------------------------------------------------------------------------- public CxClientEntityMetadata() { } //---------------------------------------------------------------------------- internal CxClientEntityMetadata( CxSlMetadataHolder holder, CxEntityUsageMetadata entityUsage) { if (holder == null) throw new ArgumentNullException("holder"); if (entityUsage == null) throw new ArgumentNullException("entityUsage"); EntityId = entityUsage.EntityId; Id = entityUsage.Id; SingleCaption = entityUsage.SingleCaption; PluralCaption = entityUsage.PluralCaption; FrameClassId = entityUsage.FrameClassId; SlFilterOnStart = entityUsage.SlFilterOnStart; IsAlwaysSaveOnEdit = entityUsage.IsAlwaysSaveOnEdit; bool saveAndStayCommand; SaveAndStayCommand = bool.TryParse(entityUsage["sl_save_and_stay"], out saveAndStayCommand); foreach (CxAttributeMetadata attrMetadata in entityUsage.Attributes) { CxClientAttributeMetadata clientAttributeMetadata = new CxClientAttributeMetadata(attrMetadata, entityUsage); Attributes.Add(clientAttributeMetadata.Id, clientAttributeMetadata); } foreach (CxAttributeMetadata editableAttrMetadata in entityUsage.GetAttributeOrder(NxAttributeContext.Edit).OrderAttributes) { if (Attributes.ContainsKey(editableAttrMetadata.Id)) EditableAttributes.Add(editableAttrMetadata.Id); } foreach (CxAttributeMetadata gridOrderedMetadata in entityUsage.GetAttributeOrder(NxAttributeContext.GridVisible).OrderAttributes) { if (Attributes.ContainsKey(gridOrderedMetadata.Id)) GridOrderedAttributes.Add(gridOrderedMetadata.Id); } ChildEntities = entityUsage.ChildEntityUsages.Values.ToArray(childEntityUsageMetadata => new CxClientEntityMetadata(holder, childEntityUsageMetadata.EntityUsage)); Commands = entityUsage.Commands.ToArray(commandMetadata => new CxClientCommandMetadata(commandMetadata, entityUsage)); ClientClassId = entityUsage["sl_client_class_id"]; EditControllerClassId = entityUsage["sl_edit_controller_class_id"]; EditFrameId = entityUsage.SlEditFrameId; JoinParamsNames = new List<string>(); JoinParamsNames.AddRange(CxDbParamParser.GetList(entityUsage.JoinCondition, true)); WhereParamsNames = new List<string>(); WhereParamsNames.AddRange(CxDbParamParser.GetList(entityUsage.WhereClause, true)); FilterableIds = new List<string>(); IsPagingEnabled = entityUsage.IsPagingEnabled; foreach (CxAttributeMetadata filterable in entityUsage.FilterableAttributes) { if (Attributes.ContainsKey(filterable.Id)) FilterableIds.Add(filterable.Id); } ApplyDefaultFilter = string.IsNullOrEmpty(entityUsage["sl_apply_default_filter"]) ? false : Convert.ToBoolean(entityUsage["sl_apply_default_filter"]); IsFilterEnabled = entityUsage.IsFilterEnabled; ImageId = entityUsage.ImageId; bool refreshParent; bool.TryParse(entityUsage["sl_refresh_parent_after_save"], out refreshParent); RefreshParentAfterSave = refreshParent; ParentEntities = new List<CxClientParentEntity>(); foreach (CxParentEntityMetadata parentEntity in entityUsage.Entity.ParentEntities) { ParentEntities.Add( new CxClientParentEntity( parentEntity.Entity.Id, parentEntity.EntityUsageId, CxDbParamParser.GetList(parentEntity.WhereClause, true))); } bool multipleGridEdit; MultipleGridEdit = bool.TryParse(entityUsage["sl_multiple_grid_edit"], out multipleGridEdit); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using System.Collections.ObjectModel; namespace BaiTapTuan2 { // Learn more about making custom code visible in the Xamarin.Forms previewer // by visiting https://aka.ms/xamarinforms-previewer [DesignTimeVisible(false)] [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainPage : ContentPage { ObservableCollection<hoa> Hoas = new ObservableCollection<hoa>(); public MainPage() { InitializeComponent(); Hoas.Add(new hoa { TenHoa = "Đón Xuân", Gia = 50000, Hinh = "cuc_1.jpg", Mota = "Hoa cúc các màu: Trắng, vàng, cam " }); Hoas.Add(new hoa { TenHoa = "Hồn nhiên", Gia = 60000, Hinh = "cuc_2.jpg", Mota = "Hoa cúc vàng, cam, lá mảng " }); Hoas.Add(new hoa { TenHoa = "Tím thủy chung", Gia = 45000, Hinh = "cuc_3.jpg", Mota = "Hoa cúc tím" }); lsvHoa.ItemsSource = Hoas; } } }
using System.ComponentModel.DataAnnotations; namespace Psub.DataService.DTO { public class RelayDataDTO { public int Id { get; set; } [Display(Name = "Назначение")] public string Name { get; set; } [Display(Name = "Вывод (pin)")] public int PinName { get; set; } [Display(Name = "вкл/откл")] public bool Value { get; set; } public ControlObjectDTO ControlObject { get; set; } [Display(Name = "Параметр обнавлен")] public string LastUpdate { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Creature : MonoBehaviour { public GameObject foodPrefab; public float sensoryRadius = 100f; public float eatRadius = 1f; public float attackRadius = 3f; public float foodEnergy = 30f; public float attackEnergyHit = 30f; public float maxSpeed = 8f; public GameObject closestCreature; public GameObject closestFood; public float score = 0f; public float timeout = 120f; // genetics public Chromosome chromosome; // inputs public float creatureX; public float creatureZ; public float foodX; public float foodZ; public float energy = 120f; public float creatureEnergy; public float random; // outputs public float moveX; public float moveZ; public float mouth; public float attack; private Brain brain; private bool isInitialized = false; // Use this for initialization public void Initialize (Chromosome c) { chromosome = c; brain = new Brain (this); isInitialized = true; attack = 0.5f; StartCoroutine (Timeout ()); } private IEnumerator Timeout() { yield return new WaitForSeconds (timeout); energy = -1f; } // Update is called once per frame void Update () { if (!isInitialized) return; UpdateState (); brain.Think (); Act (); } void Act() { //normalize vector to preserve direction Vector3 a = new Vector3 (moveX, 0f, moveZ).normalized; Move(a.x, a.z); //if (Random.Range (0f, 1f) < mouth) Eat(); //if (Random.Range (0f, 1f) < attack) Attack (); } void UpdateState() { // update energy/life energy -= Time.deltaTime; score += Time.deltaTime; // dies if (energy <= 0f) { Instantiate (foodPrefab, transform.position, Quaternion.identity); FindObjectOfType<SimulationController> ().RegisterDeath (chromosome, score); Destroy (gameObject); } // update closest objects closestCreature = null; closestFood = null; float closestCreatureDistance = sensoryRadius + 1; float closestFoodDistance = sensoryRadius + 1; Collider[] cols = Physics.OverlapSphere (transform.position, sensoryRadius); foreach (Collider c in cols) { if (c.tag == "creature" && c.gameObject != gameObject) { float d = Vector3.Distance (transform.position, c.transform.position); if (d < closestCreatureDistance) { closestCreature = c.gameObject; closestCreatureDistance = d; } } if (c.tag == "food") { float d = Vector3.Distance (transform.position, c.transform.position); if (d < closestFoodDistance) { closestFood = c.gameObject; closestFoodDistance = d; } } } if (closestCreature == null) { creatureX = sensoryRadius + 1; creatureZ = sensoryRadius + 1; } else { creatureX = closestCreature.transform.position.x - transform.position.x; creatureZ = closestCreature.transform.position.z - transform.position.z; } if (closestFood == null) { foodX = sensoryRadius + 1; foodZ = sensoryRadius + 1; } else { foodX = closestFood.transform.position.x - transform.position.x; foodZ = closestFood.transform.position.z - transform.position.z; } } void Eat() { if (closestFood != null && Vector3.Distance(transform.position, closestFood.transform.position) < eatRadius) { Destroy (closestFood); energy += attackEnergyHit; } } void Attack() { if (closestCreature != null && Vector3.Distance(transform.position, closestCreature.transform.position) < attackRadius) { closestCreature.GetComponent<Creature>().energy -= attackEnergyHit * Time.deltaTime; } } void Move(float x, float z) { //vector scaled by deltaTime to work at same speed for all cpu speeds transform.position += new Vector3 ((x*Time.deltaTime), 0f, (z*Time.deltaTime)); } public float GetWeight(int i) { return chromosome.weights[i]; } }
using CarInventory.Data.Entities; using CarInventory.Exceptions; using CarInventory.Models; using System; namespace CarInventory.Data.Repositories { /// <summary> /// The user repository. /// </summary> public interface IUserRepository : IGenericRepository<RefUser, UserSearchCriteria> { /// <summary> /// Gets user by login. /// </summary> /// /// <param name="login">The user login.</param> /// <returns>The found User entity.</returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="login"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="login"/> is empty. /// </exception> /// <exception cref="EntityNotFoundException"> /// If user with given login is not found. /// </exception> RefUser GetByLogin(string login); } }
using System.Threading; using System.Threading.Tasks; using MediatR; namespace DemoDotNet.Taxas.Core { /// <summary> /// Executor da requisição de taxas de juros com valor fixo /// </summary> public class TaxaJurosValorFixoHandler : IRequestHandler<TaxaJurosConsulta, decimal> { // Como o resultado é fixo, podemos cachear a task de retorno private readonly Task<decimal> _taxaJurosValorFixo = Task.FromResult(0.01m); public Task<decimal> Handle(TaxaJurosConsulta request, CancellationToken cancellationToken) { return _taxaJurosValorFixo; } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_BoneWeight : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { BoneWeight boneWeight = default(BoneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int op_Equality(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); BoneWeight boneWeight2; LuaObject.checkValueType<BoneWeight>(l, 2, out boneWeight2); bool b = boneWeight == boneWeight2; LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int op_Inequality(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); BoneWeight boneWeight2; LuaObject.checkValueType<BoneWeight>(l, 2, out boneWeight2); bool b = boneWeight != boneWeight2; LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_weight0(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_weight0()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_weight0(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); float weight; LuaObject.checkType(l, 2, out weight); boneWeight.set_weight0(weight); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_weight1(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_weight1()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_weight1(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); float weight; LuaObject.checkType(l, 2, out weight); boneWeight.set_weight1(weight); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_weight2(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_weight2()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_weight2(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); float weight; LuaObject.checkType(l, 2, out weight); boneWeight.set_weight2(weight); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_weight3(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_weight3()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_weight3(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); float weight; LuaObject.checkType(l, 2, out weight); boneWeight.set_weight3(weight); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_boneIndex0(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_boneIndex0()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_boneIndex0(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); int boneIndex; LuaObject.checkType(l, 2, out boneIndex); boneWeight.set_boneIndex0(boneIndex); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_boneIndex1(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_boneIndex1()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_boneIndex1(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); int boneIndex; LuaObject.checkType(l, 2, out boneIndex); boneWeight.set_boneIndex1(boneIndex); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_boneIndex2(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_boneIndex2()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_boneIndex2(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); int boneIndex; LuaObject.checkType(l, 2, out boneIndex); boneWeight.set_boneIndex2(boneIndex); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_boneIndex3(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); LuaObject.pushValue(l, true); LuaObject.pushValue(l, boneWeight.get_boneIndex3()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_boneIndex3(IntPtr l) { int result; try { BoneWeight boneWeight; LuaObject.checkValueType<BoneWeight>(l, 1, out boneWeight); int boneIndex; LuaObject.checkType(l, 2, out boneIndex); boneWeight.set_boneIndex3(boneIndex); LuaObject.setBack(l, boneWeight); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.BoneWeight"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_BoneWeight.op_Equality)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_BoneWeight.op_Inequality)); LuaObject.addMember(l, "weight0", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_weight0), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_weight0), true); LuaObject.addMember(l, "weight1", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_weight1), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_weight1), true); LuaObject.addMember(l, "weight2", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_weight2), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_weight2), true); LuaObject.addMember(l, "weight3", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_weight3), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_weight3), true); LuaObject.addMember(l, "boneIndex0", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_boneIndex0), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_boneIndex0), true); LuaObject.addMember(l, "boneIndex1", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_boneIndex1), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_boneIndex1), true); LuaObject.addMember(l, "boneIndex2", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_boneIndex2), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_boneIndex2), true); LuaObject.addMember(l, "boneIndex3", new LuaCSFunction(Lua_UnityEngine_BoneWeight.get_boneIndex3), new LuaCSFunction(Lua_UnityEngine_BoneWeight.set_boneIndex3), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_BoneWeight.constructor), typeof(BoneWeight), typeof(ValueType)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OldLadyTrigger : MonoBehaviour { [SerializeField] private Animator oldLady; [SerializeField] private Animator boxKey; void OnTriggerEnter2D(Collider2D col) { if(col.CompareTag("Key")){ oldLady.gameObject.SetActive(true); boxKey.SetBool("boxFade",true); } boxKey.gameObject.AddComponent<LobbyBox>(); StartCoroutine(disableBox()); } IEnumerator disableBox() { yield return new WaitForSeconds(2); boxKey.gameObject.SetActive(false); } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace LearningEnglishMobile.Core.Models.User { public class UserInfo { [JsonProperty("sub")] public string UserId { get; set; } [JsonProperty("preferred_username")] public string PreferredUsername { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("last_name")] public string LastName { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("email_verified")] public bool EmailVerified { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Dentist.Enums; using Dentist.Models.Tags; namespace Dentist.Models { public class Person : IValidatableObject, IModelWithIsDelete { public Person() : base() { Address = new Address(); } public int Id { get; set; } public virtual List<File> Files { get; set; } public Title Title { get; set; } [Required] [StringLength(100)] public string FirstName { get; set; } [Required] [StringLength(100)] public string LastName { get; set; } [StringLength(100)] public string Email { get; set; } public DateTime? DateOfBirth { get; set; } [StringLength(100)] public string Phone { get; set; } public PersonRole PersonRole { get; protected set; } public int AddressId { get; set; } public virtual Address Address { get; set; } public bool IsDeleted { get; set; } public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var result = new List<ValidationResult>(); if (Files != null && Files.Count > 0) { Files.ForEach(f => { if (f.Content.Length > (1000*1000)) { result.Add(new ValidationResult("File cannot be bigger than 1 Mb")); } }); } return result; } } }
using UnityEngine; public class ButtonPause : MonoBehaviour { [SerializeField] GameObject panelPause; [SerializeField] GameObject panelOptions; public bool isActive { get; private set;} public void SetPause() { isActive = !isActive; panelPause.SetActive(isActive); if(isActive) { Time.timeScale = 0; } else { Time.timeScale = 1; } if (panelOptions.activeInHierarchy) { panelOptions.SetActive(false); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using greenlife1.BLL; namespace greenlife1 { public class Patient { public int ID { get; set; } public string PatientId { set; get; } public string Name { get; set; } public string Gender { get; set; } public string Email { get; set; } public Image Image { set; get; } public DateTime DOB { get; set; } public string NID { get; set; } public string Address { get; set; } public string Problem { get; set; } public string Phone { set; get; } public List<Schedule> Schedules { get; set; } public Doctor Doctor { get; set; } public Patient() { this.Image = new Image(); this.Schedules = new List<Schedule>(); this.Doctor = new Doctor(); } public void GridviewLoad(DataGridView assignGrid) { DataTable dt = new DataTable(); DoctorManager doctorManager = new DoctorManager(); dt.Columns.Add("Doctor Id", typeof(string)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Qualification", typeof(string)); dt.Columns.Add("Speciality", typeof(string)); foreach (var doctor in doctorManager.GetAllDoctor()) { if (doctor.Name != "") { string specli = ""; if (doctor.Speciality != null) { foreach (var speciality in doctor.Speciality) { specli = specli + " " + speciality.Name; } } assignGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dt.Rows.Add(doctor.DoctorId,doctor.Name, doctor.Qualification, specli); assignGrid.DataSource = dt; } } DataGridViewButtonColumn assignButton = new DataGridViewButtonColumn(); assignButton.Text = "Assign"; assignButton.UseColumnTextForButtonValue = true; assignGrid.Columns.Add(assignButton); } public void patientGridLoad(DataGridView viewPatientGrid) { DataTable dt = new DataTable(); PatientManager patientManager = new PatientManager(); //Patient pat = new Patient(); dt.Columns.Add("Patient ID", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Gender", typeof(string)); dt.Columns.Add("Phone", typeof(string)); dt.Columns.Add("Address", typeof(string)); dt.Columns.Add("Problems", typeof(string)); dt.Columns.Add("Natitonal ID", typeof(string)); foreach (var patient in patientManager.GetAll()) { // if(pa) viewPatientGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dt.Rows.Add(patient.PatientId, patient.Name, patient.Gender, patient.Phone, patient.Address, patient.Problem, patient.NID); //); } viewPatientGrid.DataSource = dt; } public void searchPatientGridLoad(DataGridView viewPatientGrid, string search) { DataTable dt = new DataTable(); PatientManager patientManager = new PatientManager(); //Patient pat = new Patient(); dt.Columns.Add("Patient ID", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Gender", typeof(string)); dt.Columns.Add("Phone", typeof(string)); dt.Columns.Add("Address", typeof(string)); dt.Columns.Add("Problems", typeof(string)); dt.Columns.Add("Natitonal ID", typeof(string)); foreach (var patient in patientManager.GetSearchedPatient(search)) { // if(pa) viewPatientGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dt.Rows.Add(patient.PatientId, patient.Name, patient.Gender, patient.Phone, patient.Address, patient.Problem, patient.NID); //); } viewPatientGrid.DataSource = dt; } public int GetAge() { return DOB.Year - DateTime.Today.Day; } } }
// // - AddChildCommand.cs - // // Copyright 2014 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Carbonfrost.Commons.PropertyTrees.Schema; using Carbonfrost.Commons.PropertyTrees.Serialization; namespace Carbonfrost.Commons.PropertyTrees.Serialization { partial class TemplateMetaObject { [DebuggerDisplay("{debuggerDisplay}")] sealed class AddChildCommand : ITemplateCommand { readonly OperatorDefinition definition; readonly IReadOnlyDictionary<string, object> arguments; private string debuggerDisplay { get { return string.Format("{0} (Count = {1})", definition, arguments.Count); } } public AddChildCommand(OperatorDefinition definition, IReadOnlyDictionary<string, PropertyTreeMetaObject> arguments) { this.definition = definition; this.arguments = arguments.ToDictionary(t => t.Key, t => t.Value.Component); } void ITemplateCommand.Apply(Stack<object> values) { object component = values.Peek(); values.Push(definition.Apply(null, component, arguments)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; namespace XGhms.Web.Admin.CollegeControls { public partial class CollegeManage : Common.AdmPageBase { protected void Page_Load(object sender, EventArgs e) { /*权限控制 Begin*/ DataTable dt = (DataTable)Session["UserInfo"]; //获取session值 if (dt.Rows[0]["role_name"].ToString() == "CollegeAdmin") { Response.ContentType = "text/html"; Response.Write("<html><head><title>跳转中...</title><script language='javascript'>alert('抱歉,您没有权限访问该页面!');window.location.replace('CollegeList.aspx');</script></head><body></body></html>"); return; } /*权限控制 End*/ } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.Web.CodeGeneration.Contracts.Messaging; namespace Bai14.Models { public class MyDbContext:DbContext { //Khai báo các thuộc tính bên trong (tương ứng tạo thành các bảng) public DbSet<Loai> Loais { get; set; } public DbSet<HangHoa> HangHoas { get; set; } public DbSet<KhachHang> KhachHangs { get; set; } public DbSet<Customer> Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //chỉ định CSDKL dùng và chuỗi kết nối var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) //Nếu thư mục con thì nên Path.Combine để nối đường dẫn //Ví dụ: file json nằm trong thư mục Configs thì Path.Combine(Directory.GetCurrentDirectory(),"Config"); .AddJsonFile("appsettings.json"); //.AddJsonFile("myappsettings.json"); var config = builder.Build(); var connectionString = config.GetConnectionString("MyStoreEF"); optionsBuilder.UseSqlServer(connectionString); } //hàm tạo có tham số sử dụng chuỗi kết nối ở ConfirgureService() trong class startup public MyDbContext() { //this.Database.ProviderName } public MyDbContext(DbContextOptions opt) : base(opt) { //Add-Migration v1 trong cửa sổ Nuget để tạo script qua db } } }
using OpenMetaverse; using System; namespace OpenSim.Addons.Store.Data { public interface IStoreData { bool CheckTranExists(UUID tranid); bool CheckSessionExists(UUID session); void UpdateTranDeclined(UUID tranid); void UpdateTranAccepted(UUID tranid); void UpdateTranPaid(UUID tranid); void UpdateTranOffered(UUID tranid); void UpdateTranSession(UUID tranid, UUID session); UUID FetchTransFromSession(UUID session); TransactionData FetchTrans(UUID tranid); } }
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved. using UnityEngine; using UnityEngine.UIElements; namespace Naninovel { public class LineTextField : TextField { public LineTextField (string label = default, string value = default) { if (label != null) this.label = label; if (value != null) this.value = value; labelElement.name = "InputLabel"; multiline = true; var inputField = this.Q<VisualElement>("unity-text-input"); inputField.RegisterCallback<MouseDownEvent>(HandleFieldMouseDown); inputField.style.unityTextAlign = TextAnchor.UpperLeft; AddToClassList("Inlined"); RegisterCallback<ChangeEvent<string>>(HandleValueChanged); } private void HandleFieldMouseDown (MouseDownEvent evt) { if (focusController.focusedElement == this) return; // Prevent do-focusing the field on consequent clicks. // Propagate the event to the parent. var newEvt = MouseDownEvent.GetPooled(evt); newEvt.target = this; SendEvent(newEvt); } private void HandleValueChanged (ChangeEvent<string> evt) { if (evt.newValue != evt.previousValue) ScriptView.ScriptModified = true; } } }
#region License // Copyright (C) 2017 AlienGames // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 // USA #endregion using System; using System.ComponentModel; using System.Runtime.InteropServices; namespace AlienEngine { /// <summary> /// 3 row, 2 column matrix. /// </summary> [Serializable] [TypeConverter(typeof(StructTypeConverter<Matrix3x2f>))] [StructLayout(LayoutKind.Sequential)] public struct Matrix3x2f : IEquatable<Matrix3x2f>, ILoadFromString { #region Fields /// <summary> /// Value at row 1, column 1 of the matrix. /// </summary> public float M11; /// <summary> /// Value at row 1, column 2 of the matrix. /// </summary> public float M12; /// <summary> /// Value at row 2, column 1 of the matrix. /// </summary> public float M21; /// <summary> /// Value at row 2, column 2 of the matrix. /// </summary> public float M22; /// <summary> /// Value at row 3, column 1 of the matrix. /// </summary> public float M31; /// <summary> /// Value at row 3, column 2 of the matrix. /// </summary> public float M32; /// <summary> /// The zero matrix. /// </summary> public static readonly Matrix3x2f Zero = new Matrix3x2f(Vector2f.Zero); /// <summary> /// The matrix with values populated with 1. /// </summary> public static readonly Matrix3x2f One = new Matrix3x2f(Vector2f.One); #endregion #region Constructors /// <summary> /// Constructs a new 3 row, 2 column matrix. /// </summary> /// <param name="m11">Value at row 1, column 1 of the matrix.</param> /// <param name="m12">Value at row 1, column 2 of the matrix.</param> /// <param name="m21">Value at row 2, column 1 of the matrix.</param> /// <param name="m22">Value at row 2, column 2 of the matrix.</param> /// <param name="m31">Value at row 2, column 1 of the matrix.</param> /// <param name="m32">Value at row 2, column 2 of the matrix.</param> public Matrix3x2f(float m11, float m12, float m21, float m22, float m31, float m32) { M11 = m11; M12 = m12; M21 = m21; M22 = m22; M31 = m31; M32 = m32; } /// <summary> /// Initializes a new instance of the <see cref="Matrix3x2f"/> struct. /// The matrix is initialised with the <paramref name="rows"/> which represent an array of Vector2f. /// </summary> /// <param name="rows">The colums of the matrix.</param> public Matrix3x2f(Vector2f[] rows) { if (rows.Length < 3) throw new ArgumentException(); M11 = rows[0].X; M12 = rows[0].Y; M21 = rows[1].X; M22 = rows[1].Y; M31 = rows[2].X; M32 = rows[2].Y; } /// <summary> /// Initializes a new instance of the <see cref="Matrix3x2f"/> struct. /// </summary> /// <param name="row0">The first row of the matrix.</param> /// <param name="row1">The second row of the matrix.</param> public Matrix3x2f(Vector2f row0, Vector2f row1, Vector2f row2) { M11 = row0.X; M12 = row0.Y; M21 = row1.X; M22 = row1.Y; M31 = row2.X; M32 = row2.Y; } /// <summary> /// Initializes a new instance of the <see cref="Matrix3x2f"/> struct. /// </summary> /// <param name="row">The value used to populate the matrix</param> public Matrix3x2f(Vector2f row) { M11 = row.X; M12 = row.Y; M21 = row.X; M22 = row.Y; M31 = row.X; M32 = row.Y; } /// <summary> /// Initializes a new instance of the <see cref="Matrix3x2f"/> struct. /// </summary> /// <param name="matrix">The matrix used for copy</param> public Matrix3x2f(Matrix3x2f matrix) { M11 = matrix.M11; M12 = matrix.M12; M21 = matrix.M21; M22 = matrix.M22; M31 = matrix.M31; M32 = matrix.M32; } /// <summary> /// Initializes a new instance of the <see cref="Matrix3x2f"/> struct. /// </summary> /// <param name="values">An array of values used to populate the matrix.</param> public Matrix3x2f(float[] values) { if (values.Length < 6) throw new ArgumentOutOfRangeException(); M11 = values[0]; M12 = values[1]; M21 = values[2]; M22 = values[3]; M31 = values[4]; M32 = values[5]; } #endregion #region Public Members #region Properties /// <summary> /// Gets the transposed matrix of this instance. /// </summary> public Matrix2x3f Transposed { get { return new Matrix2x3f(Column0, Column1); } } /// <summary> /// Gets the first column of the matrix. /// </summary> public Vector3f Column0 { get { return new Vector3f(M11, M21, M31); } set { M11 = value.X; M21 = value.Y; M31 = value.Z; } } /// <summary> /// Gets the first column of the matrix. /// </summary> public Vector3f Column1 { get { return new Vector3f(M12, M22, M32); } set { M12 = value.X; M22 = value.Y; M32 = value.Z; } } /// <summary> /// Top row of the matrix. /// </summary> public Vector2f Row0 { get { return new Vector2f(M11, M12); } set { M11 = value.X; M12 = value.Y; } } /// <summary> /// Middle row of the matrix. /// </summary> public Vector2f Row1 { get { return new Vector2f(M21, M22); } set { M21 = value.X; M22 = value.Y; } } /// <summary> /// Bottom row of the matrix. /// </summary> public Vector2f Row2 { get { return new Vector2f(M31, M32); } set { M31 = value.X; M32 = value.Y; } } #endregion #region Indexers /// <summary> /// Gets or sets the <see cref="Vector2f"/> row at the specified index. /// </summary> /// <value> /// The <see cref="Vector2f"/> value. /// </value> /// <param name="row">The row index.</param> /// <returns>The row at index <paramref name="row"/>.</returns> public Vector2f this[int row] { get { if (row == 0) { return Row0; } if (row == 1) { return Row1; } if (row == 2) { return Row2; } throw new ArgumentOutOfRangeException(); } set { if (row == 0) { Row0 = value; } else if (row == 1) { Row1 = value; } else if (row == 2) { Row2 = value; } else throw new ArgumentOutOfRangeException(); } } /// <summary> /// Gets or sets the element at <paramref name="row"/> and <paramref name="column"/>. /// </summary> /// <value> /// The element at <paramref name="row"/> and <paramref name="column"/>. /// </value> /// <param name="row">The row index.</param> /// <param name="column">The column index.</param> /// <returns> /// The element at <paramref name="row"/> and <paramref name="column"/>. /// </returns> public float this[int row, int column] { get { if (row == 0) return Row0[column]; if (row == 1) return Row1[column]; if (row == 2) return Row2[column]; throw new ArgumentOutOfRangeException(); } set { if (row == 0) { if (column == 0) M11 = value; if (column == 1) M12 = value; } else if (row == 1) { if (column == 0) M21 = value; if (column == 1) M22 = value; } else if (row == 2) { if (column == 0) M31 = value; if (column == 1) M32 = value; } else throw new ArgumentOutOfRangeException(); } } #endregion #region Static /// <summary> /// Adds the two matrices together on a per-element basis. /// </summary> /// <param name="left">First matrix to add.</param> /// <param name="right">Second matrix to add.</param> /// <returns>Sum of the two matrices.</returns> public static Matrix3x2f Add(Matrix3x2f left, Matrix3x2f right) { Matrix3x2f res; Add(ref left, ref right, out res); return res; } /// <summary> /// Adds the two matrices together on a per-element basis. /// </summary> /// <param name="left">First matrix to add.</param> /// <param name="right">Second matrix to add.</param> /// <param name="result">Sum of the two matrices.</param> public static void Add(ref Matrix3x2f left, ref Matrix3x2f right, out Matrix3x2f result) { float m11 = left.M11 + right.M11; float m12 = left.M12 + right.M12; float m21 = left.M21 + right.M21; float m22 = left.M22 + right.M22; float m31 = left.M31 + right.M31; float m32 = left.M32 + right.M32; result.M11 = m11; result.M12 = m12; result.M21 = m21; result.M22 = m22; result.M31 = m31; result.M32 = m32; } /// <summary> /// Multiplies the two matrices. /// </summary> /// <param name="left">First matrix to multiply.</param> /// <param name="right">Second matrix to multiply.</param> /// <returns>Product of the multiplication.</returns> public static Matrix3x2f Multiply(Matrix3f left, Matrix3x2f right) { Matrix3x2f res; Multiply(ref left, ref right, out res); return res; } /// <summary> /// Multiplies the two matrices. /// </summary> /// <param name="left">First matrix to multiply.</param> /// <param name="right">Second matrix to multiply.</param> /// <param name="result">Product of the multiplication.</param> public static void Multiply(ref Matrix3f left, ref Matrix3x2f right, out Matrix3x2f result) { float resultM11 = left.M11 * right.M11 + left.M12 * right.M21 + left.M13 * right.M31; float resultM12 = left.M11 * right.M12 + left.M12 * right.M22 + left.M13 * right.M32; float resultM21 = left.M21 * right.M11 + left.M22 * right.M21 + left.M23 * right.M31; float resultM22 = left.M21 * right.M12 + left.M22 * right.M22 + left.M23 * right.M32; float resultM31 = left.M31 * right.M11 + left.M32 * right.M21 + left.M33 * right.M31; float resultM32 = left.M31 * right.M12 + left.M32 * right.M22 + left.M33 * right.M32; result.M11 = resultM11; result.M12 = resultM12; result.M21 = resultM21; result.M22 = resultM22; result.M31 = resultM31; result.M32 = resultM32; } /// <summary> /// Multiplies the two matrices. /// </summary> /// <param name="left">First matrix to multiply.</param> /// <param name="right">Second matrix to multiply.</param> /// <returns>Product of the multiplication.</returns> public static Matrix3x2f Multiply(Matrix4f left, Matrix3x2f right) { Matrix3x2f res; Multiply(ref left, ref right, out res); return res; } /// <summary> /// Multiplies the two matrices. /// </summary> /// <param name="a">First matrix to multiply.</param> /// <param name="b">Second matrix to multiply.</param> /// <param name="result">Product of the multiplication.</param> public static void Multiply(ref Matrix4f a, ref Matrix3x2f b, out Matrix3x2f result) { float resultM11 = a.M11 * b.M11 + a.M12 * b.M21 + a.M13 * b.M31; float resultM12 = a.M11 * b.M12 + a.M12 * b.M22 + a.M13 * b.M32; float resultM21 = a.M21 * b.M11 + a.M22 * b.M21 + a.M23 * b.M31; float resultM22 = a.M21 * b.M12 + a.M22 * b.M22 + a.M23 * b.M32; float resultM31 = a.M31 * b.M11 + a.M32 * b.M21 + a.M33 * b.M31; float resultM32 = a.M31 * b.M12 + a.M32 * b.M22 + a.M33 * b.M32; result.M11 = resultM11; result.M12 = resultM12; result.M21 = resultM21; result.M22 = resultM22; result.M31 = resultM31; result.M32 = resultM32; } /// <summary> /// Negates every element in the matrix. /// </summary> /// <param name="matrix">Matrix to negate.</param> /// <return>Negated matrix.</returns> public static Matrix3x2f Negate(Matrix3x2f matrix) { Matrix3x2f res; Negate(ref matrix, out res); return res; } /// <summary> /// Negates every element in the matrix. /// </summary> /// <param name="matrix">Matrix to negate.</param> /// <param name="result">Negated matrix.</param> public static void Negate(ref Matrix3x2f matrix, out Matrix3x2f result) { float m11 = -matrix.M11; float m12 = -matrix.M12; float m21 = -matrix.M21; float m22 = -matrix.M22; float m31 = -matrix.M31; float m32 = -matrix.M32; result.M11 = m11; result.M12 = m12; result.M21 = m21; result.M22 = m22; result.M31 = m31; result.M32 = m32; } /// <summary> /// Subtracts the two matrices from each other on a per-element basis. /// </summary> /// <param name="left">First matrix to subtract.</param> /// <param name="right">Second matrix to subtract.</param> /// <returns>Difference of the two matrices.</returns> public static Matrix3x2f Subtract(Matrix3x2f left, Matrix3x2f right) { Matrix3x2f res; Subtract(ref left, ref right, out res); return res; } /// <summary> /// Subtracts the two matrices from each other on a per-element basis. /// </summary> /// <param name="left">First matrix to subtract.</param> /// <param name="right">Second matrix to subtract.</param> /// <param name="result">Difference of the two matrices.</param> public static void Subtract(ref Matrix3x2f left, ref Matrix3x2f right, out Matrix3x2f result) { float m11 = left.M11 - right.M11; float m12 = left.M12 - right.M12; float m21 = left.M21 - right.M21; float m22 = left.M22 - right.M22; float m31 = left.M31 - right.M31; float m32 = left.M32 - right.M32; result.M11 = m11; result.M12 = m12; result.M21 = m21; result.M22 = m22; result.M31 = m31; result.M32 = m32; } /// <summary> /// Computes the transposed matrix of a matrix. /// </summary> /// <param name="matrix">Matrix to transpose.</param> /// <returns>Transposed matrix.</returns> public static Matrix2x3f Transpose(Matrix3x2f matrix) { Matrix2x3f res; Transpose(ref matrix, out res); return res; } /// <summary> /// Computes the transposed matrix of a matrix. /// </summary> /// <param name="matrix">Matrix to transpose.</param> /// <param name="result">Transposed matrix.</param> public static void Transpose(ref Matrix3x2f matrix, out Matrix2x3f result) { result = matrix.Transposed; } #endregion #region Operators /// <summary> /// Add two <see cref="Matrix3x2f"/>. /// </summary> /// <param name="left">The first matrix.</param> /// <param name="right">The second matrix.</param> /// <returns>The sum of matrices</returns> public static Matrix3x2f operator +(Matrix3x2f left, Matrix3x2f right) { Matrix3x2f res; Add(ref left, ref right, out res); return res; } /// <summary> /// Substract two <see cref="Matrix3x2f"/>. /// </summary> /// <param name="left">The first matrix.</param> /// <param name="right">The second matrix.</param> /// <returns>The sum of matrices</returns> public static Matrix3x2f operator -(Matrix3x2f left, Matrix3x2f right) { Matrix3x2f res; Subtract(ref left, ref right, out res); return res; } /// <summary> /// Negate a <see cref="Matrix3x2f"/>. /// </summary> /// <param name="matrix">The first matrix.</param> /// <returns>The sum of matrices</returns> public static Matrix3x2f operator -(Matrix3x2f matrix) { Matrix3x2f res; Negate(ref matrix, out res); return res; } /// <summary> /// Compare two <see cref="Matrix3x2f"/> for difference. /// </summary> /// <param name="left">The first matrix.</param> /// <param name="right">The second matrix.</param> /// <returns></returns> public static bool operator !=(Matrix3x2f left, Matrix3x2f right) { return !(left == right); } /// <summary> /// Multiplies the <paramref name="left"/> matrix by the <paramref name="right"/> matrix. /// </summary> /// <param name="left">The LHS matrix.</param> /// <param name="right">The RHS matrix.</param> /// <returns>The product of <paramref name="left"/> and <paramref name="right"/>.</returns> public static Matrix3x2f operator *(Matrix3f left, Matrix3x2f right) { Matrix3x2f result; Multiply(ref left, ref right, out result); return result; } /// <summary> /// Multiplies the <paramref name="left"/> matrix by the <paramref name="right"/> matrix. /// </summary> /// <param name="left">The LHS matrix.</param> /// <param name="right">The RHS matrix.</param> /// <returns>The product of <paramref name="left"/> and <paramref name="right"/>.</returns> public static Matrix3x2f operator *(Matrix4f left, Matrix3x2f right) { Matrix3x2f result; Multiply(ref left, ref right, out result); return result; } /// <summary> /// Compare two <see cref="Matrix3x2f"/> for equality. /// </summary> /// <param name="left">The left side.</param> /// <param name="right">The right side.</param> public static bool operator ==(Matrix3x2f left, Matrix3x2f right) { return left.Equals(right); } #endregion #region Overrides /// <summary> /// Overrides the Equals() method. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return (obj is Matrix3x2f) && (Equals((Matrix3x2f)obj)); } /// <summary> /// Compare two matrices and determine if their equal. /// </summary> /// <param name="other">The matrix to compare with this instance.</param> public bool Equals(Matrix3x2f other) { return (Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2); } /// <summary> /// Gets the hashcode of this instance. /// </summary> /// <returns>The hashcode</returns> public override int GetHashCode() { return ToString().GetHashCode(); } /// <summary> /// Load this instance from the <see cref="System.String"/> representation. /// </summary> /// <param name="value">The <see cref="System.String"/> value to convert.</param> void ILoadFromString.FromString(string value) { string[] parts = value.Trim('[', ']').Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Row0 = Vector2f.Parse(parts[0]); Row1 = Vector2f.Parse(parts[1]); Row2 = Vector2f.Parse(parts[2]); } /// <summary> /// Returns the matrix as an array of floats, column major. /// </summary> public float[] ToArray() { return new float[] { M11, M12, M21, M22, M31, M32 }; } /// <summary> /// Gets the <see cref="System.String"/> representation of the matrix. /// </summary> public override string ToString() { return string.Format("[{0},{1},{2}]", Row0, Row1, Row2); } #endregion #endregion } }
using Autofac; using NServiceBus; namespace Common.Infrastructure.Autofac { public class NServiceBusModule : Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); builder.Register(c => NServiceBus.Configure.With() .AutofacBuilder() .Log4Net() .MsmqTransport() .UnicastBus() .SendOnly()) .As<IBus>() .SingleInstance(); } } }
using System.Text.RegularExpressions; namespace HaloSharp.Validation.Common { public static class GamertagValidator { public static bool IsValidGamertag(this string gamertag) { var regex = new Regex(@"^[a-zA-Z0-9 ]{1,16}$"); return !string.IsNullOrWhiteSpace(gamertag) && regex.IsMatch(gamertag); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollidableScript : MonoBehaviour { Mesh mesh; public AudioSource audioSource; public float GetSize() { return mesh.bounds.size.magnitude * transform.localScale.magnitude; } private void Start() { mesh = GetComponent<MeshFilter>().mesh; audioSource = GetComponent<AudioSource>(); audioSource.pitch = Random.Range(0.75f, 1); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Options : MonoBehaviour { private GameObject optionsPanel; private GameObject videoPanel; private GameObject audioPanel; private GameObject controlsPanel; private GameObject gameplayPanel; private GameObject confirmationExitPanel; private Selectable videoResolutionSelectable; private Selectable videoFullscreenSelectable; private Selectable videoVSyncSelectable; private Slider audioSoundSlider; private Slider audioMusicSlider; private ButtonMapper controlsUpMapper; private ButtonMapper controlsDownMapper; private ButtonMapper controlsLeftMapper; private ButtonMapper controlsRightMapper; private ButtonMapper controlsInventoryMapper; private Selectable gameplayLanguageSelectable; private Selectable gameplayLoseMoneyOnDeathSelectable; public string defaultVideoResolution; public string defaultVideoFullscreen; public string defaultVideoVSync; public int defaultAudioSound; public int defaultAudioMusic; public KeyCode defaultControlsUpKeyCode; public KeyCode defaultControlsDownKeyCode; public KeyCode defaultControlsLeftKeyCode; public KeyCode defaultControlsRightKeyCode; public KeyCode defaultControlsInventoryKeyCode; public string defaultGameplayLanguage; public string defaultGameplayLoseMoneyOnDeath; private void Start() { optionsPanel = GameObject.Find("OptionsPanel"); videoPanel = GameObject.Find("OptionsVideoPanel"); audioPanel = GameObject.Find("OptionsAudioPanel"); controlsPanel = GameObject.Find("OptionsControlsPanel"); gameplayPanel = GameObject.Find("OptionsGameplayPanel"); confirmationExitPanel = GameObject.Find("ConfirmationExitPanel"); videoResolutionSelectable = videoPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionResolution").GetComponent<Selectable>(); videoFullscreenSelectable = videoPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionFullscreen").GetComponent<Selectable>(); videoVSyncSelectable = videoPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionVSync").GetComponent<Selectable>(); audioSoundSlider = audioPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionSound").GetComponent<Slider>(); audioMusicSlider = audioPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionMusic").GetComponent<Slider>(); controlsUpMapper = controlsPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionUp").GetComponent<ButtonMapper>(); controlsDownMapper = controlsPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionDown").GetComponent<ButtonMapper>(); controlsLeftMapper = controlsPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionLeft").GetComponent<ButtonMapper>(); controlsRightMapper = controlsPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionRight").GetComponent<ButtonMapper>(); controlsInventoryMapper = controlsPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionInventory").GetComponent<ButtonMapper>(); gameplayLanguageSelectable = gameplayPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionLanguage").GetComponent<Selectable>(); gameplayLoseMoneyOnDeathSelectable = gameplayPanel.transform.FindChild("Options").FindChild("Right").FindChild("OptionLoseMoneyOnDeath").GetComponent<Selectable>(); optionsPanel.SetActive(false); videoPanel.SetActive(false); audioPanel.SetActive(false); controlsPanel.SetActive(false); gameplayPanel.SetActive(false); confirmationExitPanel.SetActive(false); } public void Activate() { optionsPanel.SetActive(true); } public void Deactivate() { optionsPanel.SetActive(false); } public void Toggle() { if(optionsPanel.activeSelf) { Deactivate(); } else { Activate(); } } public void ActivateVideo() { videoPanel.SetActive(true); } public void DeactivateVideo() { videoPanel.SetActive(false); } public void ToggleVideo() { if(videoPanel.activeSelf) { DeactivateVideo(); } else { ActivateVideo(); } } public void ActivateAudio() { audioPanel.SetActive(true); } public void DeactivateAudio() { audioPanel.SetActive(false); } public void ToggleAudio() { if(audioPanel.activeSelf) { DeactivateAudio(); } else { ActivateAudio(); } } public void ActivateControls() { controlsPanel.SetActive(true); } public void DeactivateControls() { controlsPanel.SetActive(false); } public void ToggleControls() { if(controlsPanel.activeSelf) { DeactivateControls(); } else { ActivateControls(); } } public void ActivateGameplay() { gameplayPanel.SetActive(true); } public void DeactivateGameplay() { gameplayPanel.SetActive(false); } public void ToggleGameplay() { if(gameplayPanel.activeSelf) { DeactivateGameplay(); } else { ActivateGameplay(); } } public void ActivateConfirmationExit() { confirmationExitPanel.SetActive(true); } public void DeactivateConfirmationExit() { confirmationExitPanel.SetActive(false); } public void ToggleConfirmationExit() { if(confirmationExitPanel.activeSelf) { DeactivateConfirmationExit(); } else { ActivateConfirmationExit(); } } public void ResetAllToDefault() { ResetVideoPanelToDefault(); ResetAudioPanelToDefault(); ResetControlsPanelToDefault(); ResetGameplayPanelToDefault(); } public void ResetVideoPanelToDefault() { videoResolutionSelectable.SetCurrentOptionByText(defaultVideoResolution); videoFullscreenSelectable.SetCurrentOptionByText(defaultVideoFullscreen); videoVSyncSelectable.SetCurrentOptionByText(defaultVideoVSync); } public void ResetAudioPanelToDefault() { audioSoundSlider.SetSliderHandleByValue(defaultAudioSound); audioMusicSlider.SetSliderHandleByValue(defaultAudioMusic); } public void ResetControlsPanelToDefault() { controlsUpMapper.SetKeyCodeByDefault(defaultControlsUpKeyCode); controlsDownMapper.SetKeyCodeByDefault(defaultControlsDownKeyCode); controlsLeftMapper.SetKeyCodeByDefault(defaultControlsLeftKeyCode); controlsRightMapper.SetKeyCodeByDefault(defaultControlsRightKeyCode); controlsInventoryMapper.SetKeyCodeByDefault(defaultControlsInventoryKeyCode); } public void ResetGameplayPanelToDefault() { gameplayLanguageSelectable.SetCurrentOptionByText(defaultGameplayLanguage); gameplayLoseMoneyOnDeathSelectable.SetCurrentOptionByText(defaultGameplayLoseMoneyOnDeath); } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Music_Game.Resources; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.IO; using System.ComponentModel; using System.Xml.Linq; using System.Diagnostics; using System.Windows.Threading; using DropBoxImages; using Music_Game.Models; using System.IO.IsolatedStorage; using Microsoft.Live; using System.Net; using System.Net.Http; namespace Music_Game { public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged { string sourceImage; public string SourceImage { get { return sourceImage; } set { sourceImage = value; NotifyPropertyChanged("SourceImage"); } } DispatcherTimer DTimerShow; List<string> ListImages = new List<string>(); int currentImages = 0; public int CurrentImages { get { return currentImages; } set { if (value >= 3) currentImages = 0; else currentImages = value; } } // Constructor public MainPage() { InitializeComponent(); this.DataContext = this; for (int i = 0; i < 3; i++) { ListImages.Add("\\Assets\\BG_Images\\BG_Menu" + i + ".jpg"); } SourceImage = ListImages[CurrentImages]; DTimerShow = new DispatcherTimer(); DTimerShow.Interval = new TimeSpan(0, 0, 5); DTimerShow.Tick += DTimerShow_Tick; DTimerShow.Start(); MessageBox.Show("Excuse me! You must connect Internet to Play Game!"); } protected override void OnNavigatedTo(NavigationEventArgs e) { if (Global.IsBGMusic == false) BG_Player.Volume = 0; else BG_Player.Volume = 1; } void DTimerShow_Tick(object sender, EventArgs e) { DTimerShow.Stop(); SB_Hide.Begin(); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } private void SB_Show_Completed(object sender, EventArgs e) { DTimerShow.Start(); } private void SB_Hide_Completed(object sender, EventArgs e) { ++CurrentImages; SourceImage = ListImages[CurrentImages]; Debug.WriteLine(SourceImage); SB_Show.Begin(); } private void Btn_HScore_Click(object sender, RoutedEventArgs e) { try { NavigationService.Navigate(new Uri("/HScorePage.xaml", UriKind.Relative)); } catch { Debug.WriteLine("Error in Btn_HScore Click!"); } } private void Btn_Setting_Click(object sender, RoutedEventArgs e) { try { NavigationService.Navigate(new Uri("/SettingPage.xaml", UriKind.Relative)); } catch { Debug.WriteLine("Error in Btn_Setting Click!"); } } private void Btn_Start_Click(object sender, RoutedEventArgs e) { SP_MenuPage.Visibility = System.Windows.Visibility.Collapsed; SP_GamePage.Visibility = System.Windows.Visibility.Visible; ApplicationBar.IsVisible = true; } private bool IsSpaceIsAvailable(long spaceReq) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { long spaceAvail = store.AvailableFreeSpace; if (spaceReq > spaceAvail) { return false; } return true; } } void WClient_Download_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e1) { string Path; if (e1.Error == null) { try { string filename = "MyFile545.mp3"; bool isSpaceAvailable = IsSpaceIsAvailable(e1.Result.Length); if (isSpaceAvailable) { // Save mp3 to Isolated Storage try { using (var isfs = new IsolatedStorageFileStream(filename, FileMode.CreateNew, IsolatedStorageFile.GetUserStoreForApplication())) { long fileLen = 100 * 1024; byte[] b = new byte[fileLen]; e1.Result.Position = 300 * 1024; e1.Result.Read(b, 0, b.Length); isfs.Write(b, 0, b.Length); isfs.Flush(); Path = isfs.Name; //var client = new DropNetClient("8o22eryy1qg3m1z", "2timqmgbvjg1qjj"); //var uploaded = client.UploadFileTask("/", "music.mp3", b); } } catch (Exception ex) { } } else { MessageBox.Show("Not enough to save space available to download mp3."); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show(e1.Error.Message); } } protected override void OnBackKeyPress(CancelEventArgs e) { if(MessageBox.Show("Do you want leave Music Game?", "Exit Game", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) { e.Cancel = true; } else { Application.Current.Terminate(); } } private void Btn_SinglePlay_Click(object sender, RoutedEventArgs e) { try { Global.TypeGenre = "default"; NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative)); } catch { Debug.WriteLine("Error in Btn_HScore Click!"); } } private void Btn_ChallengeFriend_Click(object sender, RoutedEventArgs e) { try { NavigationService.Navigate(new Uri("/ChallengePage.xaml", UriKind.Relative)); } catch { Debug.WriteLine("Error in Challenge Page Click!"); } } private void Btn_CreateQuesition_Click(object sender, RoutedEventArgs e) { MessageBox.Show("We are developing!"); } private void ApplicationBarIconButton_Click(object sender, EventArgs e) { SP_MenuPage.Visibility = System.Windows.Visibility.Visible; SP_GamePage.Visibility = System.Windows.Visibility.Collapsed; ApplicationBar.IsVisible = false; } private void BG_Player_MediaEnded(object sender, RoutedEventArgs e) { BG_Player.Play(); } private void Btn_Profile_Click(object sender, RoutedEventArgs e) { try { NavigationService.Navigate(new Uri("/FacebookPage.xaml", UriKind.Relative)); } catch { Debug.WriteLine("Error in Btn_Proflie Click!"); } } } }
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; using coffeeSalesManag_CompApp.Models; namespace coffeeSalesManag_CompApp { public partial class manageEmployees : Form { public manageEmployees() { InitializeComponent(); fillGenderComboBox();//method call to fill combo box of gender. fillDataGridView();//method call to fill data grid view. } /********************CRUD OPERATIONS******************/ //ADD OPERATION. private void btnMngEmp_Add_Click(object sender, EventArgs e) { try { DbCoffeeContext _db = new DbCoffeeContext(); Employees empObj = new Employees(); empObj.UserName = txtMngEmp_userName.Text.Trim(); empObj.Password = txtMngEmp_Password.Text.Trim(); empObj.Name = txtMngEmp_Name.Text.Trim(); if (txtMngEmp_Age.Text.Trim() == string.Empty) { throw new InvalidCastException("Please enter employee age."); } empObj.Age = Convert.ToInt32(txtMngEmp_Age.Text.Trim()); empObj.Gender = cbMngEmp_Gender.Text.Trim(); if (txtMngEmp_MobNum.Text.Trim() == string.Empty) { throw new InvalidCastException("Please enter employee Mobile Number."); } empObj.MobileNumber = Convert.ToInt32(txtMngEmp_MobNum.Text.Trim()); empObj.Address = txtMngEmp_Address.Text.Trim(); empObj.DateTime = DateTime.Now; _db.employees.Add(empObj); _db.SaveChanges(); MessageBox.Show("Employee added."); fillDataGridView();//method call to fill data grid view emptyAllControls();//method call to empty all controls. } catch (Exception ex) { MessageBox.Show(ex.Message); } } //DELETE OPERATION. private void btnMngEmp_Delete_Click(object sender, EventArgs e) { try { if (MessageBox.Show("Are you sure you want to delete this employee?", "Delete Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { int empID = Convert.ToInt32(txtMngEmp_ID.Text); DbCoffeeContext _db = new DbCoffeeContext(); var empObj = _db.employees .Where(x => x.ID == empID).FirstOrDefault(); _db.employees.Remove(empObj); _db.SaveChanges(); fillDataGridView();//filling data grid view. emptyAllControls();//empty all controls. } } catch (Exception ex) { MessageBox.Show(ex.Message); } } //UPDATE OPERATION. private void btnMngEmp_Update_Click(object sender, EventArgs e) { try { int empID = Convert.ToInt32(txtMngEmp_ID.Text); DbCoffeeContext _db = new DbCoffeeContext(); var empObj = _db.employees .Where(x => x.ID == empID).FirstOrDefault(); empObj.ID = empID; empObj.Name = txtMngEmp_Name.Text.Trim(); if (txtMngEmp_Age.Text.Trim() == string.Empty) { throw new InvalidCastException("Please enter employee age."); } empObj.Age = Convert.ToInt32(txtMngEmp_Age.Text.Trim()); empObj.Gender = cbMngEmp_Gender.Text.Trim(); if (txtMngEmp_MobNum.Text.Trim() == string.Empty) { throw new InvalidCastException("Please enter employee Mobile Number."); } empObj.MobileNumber = Convert.ToInt32(txtMngEmp_MobNum.Text.Trim()); empObj.Address = txtMngEmp_Address.Text.Trim(); _db.Entry(empObj).Property(x => x.Name).IsModified = true; _db.Entry(empObj).Property(x => x.Age).IsModified = true; _db.Entry(empObj).Property(x => x.Gender).IsModified = true; _db.Entry(empObj).Property(x => x.MobileNumber).IsModified = true; _db.Entry(empObj).Property(x => x.Address).IsModified = true; _db.SaveChanges(); MessageBox.Show("Employee updated."); fillDataGridView(); emptyAllControls(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } /************************EVENTS******************/ //EVENT TO CONTROL USERNAME INPUT. private void txtMngEmp_userName_KeyPress(object sender, KeyPressEventArgs e) { Char ch = e.KeyChar; if (!char.IsLetter(ch) && !char.IsDigit(ch) && ch != (char)Keys.Back) { e.Handled = true; MessageBox.Show("Please enter only Letters and Digits"); } } //EVENT TO CONTROL INPUT OF PASWWROD FIELD. private void txtMngEmp_Password_KeyPress(object sender, KeyPressEventArgs e) { char ch = e.KeyChar; if (Control.IsKeyLocked(Keys.CapsLock)) { MessageBox.Show("Your caps lock is on."); } if (!char.IsDigit(ch) && !char.IsLetter(ch) && ch != ((char)Keys.Back)) { e.Handled = true; MessageBox.Show("Please enter only Digits"); } } //EVENT TO CONTROL INPUT OF NAME FIELD. private void txtMngEmp_Name_KeyPress(object sender, KeyPressEventArgs e) { char ch = e.KeyChar; if (!char.IsLetter(ch) && ch != (char)Keys.Back && ch != (char)Keys.Space) { e.Handled = true; MessageBox.Show("Please enter only letter."); } } //EVENT TO HANDLE INPUT OF AGE. private void txtMngEmp_Age_KeyPress(object sender, KeyPressEventArgs e) { char ch = e.KeyChar; if (!char.IsDigit(ch) && ch != ((char)Keys.Back)) { e.Handled = true; MessageBox.Show("Please enter only Digits"); } } //EVENT TO CONTROL INPUT OF GENDER FIELD. private void txtMngEmp_Gender_KeyPress(object sender, KeyPressEventArgs e) { char ch = e.KeyChar; if (char.IsDigit(ch) || char.IsLetter(ch) || ch == (char)Keys.Back) { e.Handled = true; MessageBox.Show("You can't write here."); } } //EVENT TO CONTROL INPUT OF MOBILE NUMBER FIELD. private void txtMngEmp_MobNum_KeyPress(object sender, KeyPressEventArgs e) { char ch = e.KeyChar; if (!char.IsDigit(ch) && ch != ((char)Keys.Back)) { e.Handled = true; MessageBox.Show("Please enter only Digits"); } } //EVENT TO CONTROL INPUT OF ADDRESS FIELD. private void txtMngEmp_Address_KeyPress(object sender, KeyPressEventArgs e) { char ch = e.KeyChar; if (!char.IsLetter(ch) && !char.IsDigit(ch) && ch != (char)Keys.Back && ch != (char)Keys.Space) { e.Handled = true; MessageBox.Show("Please enter only letters, digits and space."); } } //EVENT TO GET ROW FROM DATA GRID VIEW. private void dgvMngEmp_CellClick(object sender, DataGridViewCellEventArgs e) { try { DataGridViewRow row = dgvMngEmp.CurrentRow; int recId = Convert.ToInt32(row.Cells[0].Value); DbCoffeeContext _db = new DbCoffeeContext(); var empObj = _db.employees.Where(x => x.ID == recId).FirstOrDefault(); txtMngEmp_ID.Text = empObj.ID.ToString(); txtMngEmp_userName.Text = empObj.UserName; txtMngEmp_Password.Text = empObj.Password; txtMngEmp_Name.Text = empObj.Name; txtMngEmp_Age.Text = empObj.Age.ToString(); cbMngEmp_Gender.Text = empObj.Gender; txtMngEmp_MobNum.Text = empObj.MobileNumber.ToString(); txtMngEmp_Address.Text = empObj.Address; } catch (Exception ex) { MessageBox.Show(ex.Message); } } /*****************METHODS*************/ void fillGenderComboBox() { cbMngEmp_Gender.Items.Add("Male"); cbMngEmp_Gender.Items.Add("Female"); } //METHOD TO FILL DATAGRID VIEW. void fillDataGridView() { DbCoffeeContext _db = new DbCoffeeContext(); dgvMngEmp.DataSource = _db.employees.ToList(); } // method to empty all controls. void emptyAllControls() { txtMngEmp_ID.Text = string.Empty; txtMngEmp_userName.Text = string.Empty; txtMngEmp_Password.Text = string.Empty; txtMngEmp_Name.Text = string.Empty; txtMngEmp_Age.Text = string.Empty; cbMngEmp_Gender.Text = string.Empty; txtMngEmp_MobNum.Text = string.Empty; txtMngEmp_Address.Text = string.Empty; } } }
using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.Practices.Prism; using Microsoft.Practices.Prism.Events; using Microsoft.Practices.Prism.Logging; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.ViewModel; using Torshify.Radio.Framework; using Torshify.Radio.Framework.Commands; namespace Torshify.Radio.EchoNest.Views.Browse.Tabs { [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class SearchResultsViewModel : NotificationObject, IHeaderInfoProvider<HeaderInfo>, INavigationAware { #region Fields private readonly ObservableCollection<Track> _results; #endregion Fields #region Constructors public SearchResultsViewModel() { _results = new ObservableCollection<Track>(); HeaderInfo = new HeaderInfo { Title = "Results" }; CommandBar = new CommandBar(); GoToAlbumCommand = new StaticCommand<Track>(ExecuteGoToAlbum); GoToArtistCommand = new StaticCommand<string>(ExecuteGoToArtist); PlayTracksCommand = new StaticCommand<IEnumerable>(ExecutePlayTracks); QueueTracksCommand = new StaticCommand<IEnumerable>(ExecuteQueueTracks); } #endregion Constructors #region Properties [Import] public IEventAggregator EventAggregator { get; set; } [Import] public IRegionManager RegionManager { get; set; } [Import] public ILoadingIndicatorService LoadingIndicatorService { get; set; } [Import] public IRadio Radio { get; set; } [Import] public IToastService ToastService { get; set; } [Import] public ILoggerFacade Logger { get; set; } public HeaderInfo HeaderInfo { get; private set; } public ObservableCollection<Track> Results { get { return _results; } } public ICommandBar CommandBar { get; private set; } public StaticCommand<IEnumerable> PlayTracksCommand { get; private set; } public StaticCommand<IEnumerable> QueueTracksCommand { get; private set; } public StaticCommand<string> GoToArtistCommand { get; private set; } public StaticCommand<Track> GoToAlbumCommand { get; private set; } #endregion Properties #region Methods public void UpdateCommandBar(IEnumerable<Track> selectedItems) { CommandBar.Clear() .AddCommand(new CommandModel { Content = "Play", Icon = AppIcons.Play.ToImage(), Command = PlayTracksCommand, CommandParameter = selectedItems.ToArray() }) .AddCommand(new CommandModel { Content = "Queue", Icon = AppIcons.Add.ToImage(), Command = QueueTracksCommand, CommandParameter = selectedItems.ToArray() }) .AddCommand(new CommandModel { Content = "Add to favorites", Icon = AppIcons.AddToFavorites.ToImage(), Command = AppCommands.AddTrackToFavoriteCommand, CommandParameter = selectedItems.ToArray() }); } void INavigationAware.OnNavigatedTo(NavigationContext context) { if (!string.IsNullOrEmpty(context.Parameters[SearchBar.IsFromSearchBarParameter])) { string value = context.Parameters[SearchBar.ValueParameter]; ExecuteSearch(value); } } bool INavigationAware.IsNavigationTarget(NavigationContext context) { return true; } void INavigationAware.OnNavigatedFrom(NavigationContext context) { } private void ExecuteSearch(string query) { var ui = TaskScheduler.FromCurrentSynchronizationContext(); Task .Factory .StartNew(state => { LoadingIndicatorService.Push(); return Radio.GetTracksByName(state.ToString()); }, query) .ContinueWith(task => { if (task.Exception != null) { ToastService.Show("Error while search for " + task.AsyncState); Logger.Log(task.Exception.ToString(), Category.Exception, Priority.Medium); } else { _results.Clear(); foreach (var track in task.Result) { _results.Add(track); } } LoadingIndicatorService.Pop(); }, ui); } private void ExecuteGoToArtist(string artistName) { UriQuery q = new UriQuery(); q.Add("artistName", artistName); RegionManager.RequestNavigate(AppRegions.ViewRegion, typeof(ArtistView).FullName + q); } private void ExecuteGoToAlbum(Track track) { UriQuery q = new UriQuery(); q.Add("artistName", track.Artist); q.Add("albumName", track.Album); RegionManager.RequestNavigate(AppRegions.ViewRegion, typeof(AlbumView).FullName + q); } private void ExecutePlayTracks(IEnumerable tracks) { if (tracks == null) return; ITrackStream stream = tracks.OfType<Track>().ToTrackStream("Browsing"); Radio.Play(stream); } private void ExecuteQueueTracks(IEnumerable tracks) { if (tracks == null) return; ITrackStream stream = tracks.OfType<Track>().ToTrackStream("Browsing"); Radio.Queue(stream); foreach (Track track in tracks) { Logger.Log("Queued " + track.Name, Category.Debug, Priority.Low); } ToastService.Show(new ToastData { Message = "Tracks queued", Icon = AppIcons.Add }); } #endregion Methods } }
using System; using Minesweeper; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MinesweeperTests { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { MainForm test = new MainForm(); } } }
using System.Drawing; using System.Text.RegularExpressions; using System.Windows.Forms; namespace ITechnologyNET.FindUnusedFiles { public partial class PictureBox : Form { public PictureBox(int width, int height) { InitializeComponent(); // deactivated because treeview breaks focus all the time... //LostFocus += (s, o) => Hide(); Size = new Size(width, height); pictureBox1.Size = Size; } public void DisplayImage(string path) { if (Regex.IsMatch(path, @"\.(gif|jpg|jpeg|png|bmp|ico|wmf)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { pictureBox1.ImageLocation = path; StartPosition = FormStartPosition.Manual; //Location = new Point(MousePosition.X + 15, MousePosition.Y - 150); Show(); } else { Hide(); } } } }
namespace NDDDSample.Interfaces.HandlingService.WebService { #region Usings using System.Runtime.Serialization; #endregion [DataContract] public class HandlingReportException { private string Msg; public HandlingReportException(string msg) { Msg = msg; } [DataMember] public string ErrorMessage { get { return Msg; } set { Msg = value; } } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game; using Triton.Game.Mono; [Attribute38("Cheats")] public class Cheats : MonoClass { public Cheats(IntPtr address) : this(address, "Cheats") { } public Cheats(IntPtr address, string className) : base(address, className) { } public static string Cheat_ShowRewardBoxes(string parsableRewardBags) { object[] objArray1 = new object[] { parsableRewardBags }; return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "Cheats", "Cheat_ShowRewardBoxes", objArray1); } public AlertPopup.PopupInfo GenerateAlertInfo(string rawArgs) { object[] objArray1 = new object[] { rawArgs }; return base.method_14<AlertPopup.PopupInfo>("GenerateAlertInfo", objArray1); } public static Cheats Get() { return MonoClass.smethod_15<Cheats>(TritonHs.MainAssemblyPath, "", "Cheats", "Get", Array.Empty<object>()); } public string GetBoard() { return base.method_13("GetBoard", Array.Empty<object>()); } public string GetChallengeUrl(string type) { object[] objArray1 = new object[] { type }; return base.method_13("GetChallengeUrl", objArray1); } public QuickLaunchAvailability GetQuickLaunchAvailability() { return base.method_11<QuickLaunchAvailability>("GetQuickLaunchAvailability", Array.Empty<object>()); } public string GetQuickPlayMissionName(int missionId) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.I4 }; object[] objArray1 = new object[] { missionId }; return base.method_12("GetQuickPlayMissionName", enumArray1, objArray1); } public string GetQuickPlayMissionNameImpl(int missionId, string columnName) { object[] objArray1 = new object[] { missionId, columnName }; return base.method_13("GetQuickPlayMissionNameImpl", objArray1); } public string GetQuickPlayMissionShortName(int missionId) { Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.I4 }; object[] objArray1 = new object[] { missionId }; return base.method_12("GetQuickPlayMissionShortName", enumArray1, objArray1); } public bool HandleKeyboardInput() { return base.method_11<bool>("HandleKeyboardInput", Array.Empty<object>()); } public bool HandleQuickPlayInput() { return base.method_11<bool>("HandleQuickPlayInput", Array.Empty<object>()); } public static void Initialize() { MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "Cheats", "Initialize"); } public void InitializeImpl() { base.method_8("InitializeImpl", Array.Empty<object>()); } public bool IsLaunchingQuickGame() { return base.method_11<bool>("IsLaunchingQuickGame", Array.Empty<object>()); } public bool IsYourMindFree() { return base.method_11<bool>("IsYourMindFree", Array.Empty<object>()); } public void LaunchQuickGame(int missionId) { object[] objArray1 = new object[] { missionId }; base.method_8("LaunchQuickGame", objArray1); } public bool OnAlertProcessed(DialogBase dialog, object userData) { object[] objArray1 = new object[] { dialog, userData }; return base.method_11<bool>("OnAlertProcessed", objArray1); } public void OnAlertResponse(AlertPopup.Response response, object userData) { object[] objArray1 = new object[] { response, userData }; base.method_8("OnAlertResponse", objArray1); } public bool OnFindGameEvent(FindGameEventData eventData, object userData) { object[] objArray1 = new object[] { eventData, userData }; return base.method_11<bool>("OnFindGameEvent", objArray1); } public void OnProcessCheat_utilservercmd_OnResponse() { base.method_8("OnProcessCheat_utilservercmd_OnResponse", Array.Empty<object>()); } public void OnSceneLoaded(SceneMgr.Mode mode, Scene scene, object userData) { object[] objArray1 = new object[] { mode, scene, userData }; base.method_8("OnSceneLoaded", objArray1); } public void PositionLoginFixedReward(Reward reward) { object[] objArray1 = new object[] { reward }; base.method_8("PositionLoginFixedReward", objArray1); } public void PrintQuickPlayLegend() { base.method_8("PrintQuickPlayLegend", Array.Empty<object>()); } public bool QuickGameFlipHeroes() { return base.method_11<bool>("QuickGameFlipHeroes", Array.Empty<object>()); } public bool QuickGameMirrorHeroes() { return base.method_11<bool>("QuickGameMirrorHeroes", Array.Empty<object>()); } public string QuickGameOpponentHeroCardId() { return base.method_13("QuickGameOpponentHeroCardId", Array.Empty<object>()); } public bool QuickGameSkipMulligan() { return base.method_11<bool>("QuickGameSkipMulligan", Array.Empty<object>()); } public static void SubscribePartyEvents() { MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "Cheats", "SubscribePartyEvents"); } public AlertPopup m_alert { get { return base.method_3<AlertPopup>("m_alert"); } } public string m_board { get { return base.method_4("m_board"); } } public bool m_isYourMindFree { get { return base.method_2<bool>("m_isYourMindFree"); } } public List<string> m_lastUtilServerCmd { get { Class245 class2 = base.method_3<Class245>("m_lastUtilServerCmd"); if (class2 != null) { return class2.method_25(); } return null; } } public bool m_loadingStoreChallengePrompt { get { return base.method_2<bool>("m_loadingStoreChallengePrompt"); } } public QuickLaunchState m_quickLaunchState { get { return base.method_3<QuickLaunchState>("m_quickLaunchState"); } } public StoreChallengePrompt m_storeChallengePrompt { get { return base.method_3<StoreChallengePrompt>("m_storeChallengePrompt"); } } public static Logger PartyLogger { get { return MonoClass.smethod_15<Logger>(TritonHs.MainAssemblyPath, "", "Cheats", "get_PartyLogger", Array.Empty<object>()); } } public static bool s_hasSubscribedToPartyEvents { get { return MonoClass.smethod_6<bool>(TritonHs.MainAssemblyPath, "", "Cheats", "s_hasSubscribedToPartyEvents"); } } public enum QuickLaunchAvailability { OK, FINDING_GAME, ACTIVE_GAME, SCENE_TRANSITION, COLLECTION_NOT_READY } [Attribute38("Cheats.QuickLaunchState")] public class QuickLaunchState : MonoClass { public QuickLaunchState(IntPtr address) : this(address, "QuickLaunchState") { } public QuickLaunchState(IntPtr address, string className) : base(address, className) { } public bool m_flipHeroes { get { return base.method_2<bool>("m_flipHeroes"); } } public bool m_launching { get { return base.method_2<bool>("m_launching"); } } public bool m_mirrorHeroes { get { return base.method_2<bool>("m_mirrorHeroes"); } } public string m_opponentHeroCardId { get { return base.method_4("m_opponentHeroCardId"); } } public bool m_skipMulligan { get { return base.method_2<bool>("m_skipMulligan"); } } } } }
namespace SuicideWeb.Models { public class BlackGroup { public int Id { get; set; } public long GroupId { get; set; } } }
namespace OmniSharp.Extensions.JsonRpc { internal class RequestContext : IRequestContext { public IHandlerDescriptor Descriptor { get; set; } = null!; } }
// Copyright (c) 2008 Josh Cooley // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Text; using Tivo.Hme.Host; namespace Tivo.Hme.Events { class DisplayInfo : EventInfo { public const long Type = 8; private const long _rootStreamId = 1; private long _metricsPerResolutionInfo; private ResolutionInfo _currentResolution; private List<ResolutionInfo> _supportedResolutions = new List<ResolutionInfo>(); public ResolutionInfo CurrentResolution { get { return _currentResolution; } } public List<ResolutionInfo> SupportedResolutions { get { return _supportedResolutions; } } public override void Read(HmeReader reader) { long streamId = reader.ReadInt64(); System.Diagnostics.Debug.Assert(_rootStreamId == streamId); _metricsPerResolutionInfo = reader.ReadInt64(); _currentResolution = new ResolutionInfo(reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64()); SkipExtraResolutionMetrics(reader); long count = reader.ReadInt64(); for (int i = 0; i < count; ++i) { _supportedResolutions.Add(new ResolutionInfo( reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64(), reader.ReadInt64())); SkipExtraResolutionMetrics(reader); } reader.ReadTerminator(); } private void SkipExtraResolutionMetrics(HmeReader reader) { for (int i = ResolutionInfo.FieldCount; i < _metricsPerResolutionInfo; ++i) { reader.ReadInt64(); } } public override void RaiseEvent(Application application) { application.OnDisplayInfoReceived(this); } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append(GetType().Name); builder.AppendFormat(": (MetricsPerResolutionInfo,{0})(CurrentResolution,{1}) ", _metricsPerResolutionInfo, CurrentResolution); int index = 0; foreach (ResolutionInfo entry in _supportedResolutions) { builder.AppendFormat("(SupportedResolution[{0}],{1})", index++, entry); } return builder.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Script_MenuPrincipal : MonoBehaviour { public InputField inputDia; public InputField inputMes; public InputField inputAño; void Start() { } void Update() { /*if () { }*/ } public void cargarEscena(string nombreNivel) { SceneManager.LoadScene(nombreNivel); } public void QuitGame() { Application.Quit(); Debug.Log("Hemos salido"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Common; using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.EnterpriseLibrary.Data.Sql; using Operation.Contract; using Operation.DataFactory; namespace Operation.DataFactory { public class OrderContainerDAL { private Database db; private DbTransaction currentTransaction = null; private DbConnection connection = null; /// <summary> /// Constructor /// </summary> public OrderContainerDAL() { db = DatabaseFactory.CreateDatabase("LogiCon"); } #region IDataFactory Members public List<OrderContainer> GetList(short branchId, string orderNo) { return db.ExecuteSprocAccessor(DBRoutine.LISTORDERCONTAINER, MapBuilder<OrderContainer>.BuildAllProperties(),branchId,orderNo).ToList(); } public List<OrderContainer> SearchOrderContainerList(string containerNo) { return db.ExecuteSprocAccessor(DBRoutine.SEARCHORDERCONTAINERLIST, MapBuilder<OrderContainer>.BuildAllProperties(), containerNo).ToList(); } public bool SaveList<T>(List<T> items, DbTransaction parentTransaction) where T : IContract { var result = true; if (items.Count == 0) result = true; foreach (var item in items) { result = Save(item, parentTransaction); if (result == false) break; } return result; } public bool Save<T>(T item, DbTransaction parentTransaction) where T : IContract { currentTransaction = parentTransaction; return Save(item); } public bool Save<T>(T item) where T : IContract { var result = 0; var ordercontainer = (OrderContainer)(object)item; if (currentTransaction == null) { connection = db.CreateConnection(); connection.Open(); } var transaction = (currentTransaction == null ? connection.BeginTransaction() : currentTransaction); try { var savecommand = db.GetStoredProcCommand(DBRoutine.SAVEORDERCONTAINER); db.AddInParameter(savecommand, "BranchID", System.Data.DbType.Int16, ordercontainer.BranchID); db.AddInParameter(savecommand, "OrderNo", System.Data.DbType.String, ordercontainer.OrderNo ?? ""); db.AddInParameter(savecommand, "ContainerKey", System.Data.DbType.String, ordercontainer.ContainerKey ?? ""); db.AddInParameter(savecommand, "ContainerNo", System.Data.DbType.String, ordercontainer.ContainerNo ?? ""); db.AddInParameter(savecommand, "Size", System.Data.DbType.String, ordercontainer.Size ?? ""); db.AddInParameter(savecommand, "Type", System.Data.DbType.String, ordercontainer.Type ?? ""); db.AddInParameter(savecommand, "SealNo", System.Data.DbType.String, ordercontainer.SealNo ?? ""); db.AddInParameter(savecommand, "SealNo2", System.Data.DbType.String, ordercontainer.SealNo2 ?? ""); db.AddInParameter(savecommand, "ContainerGrade", System.Data.DbType.Int16, ordercontainer.ContainerGrade); db.AddInParameter(savecommand, "Temprature", System.Data.DbType.String, ordercontainer.Temprature ?? ""); db.AddInParameter(savecommand, "TemperatureMode", System.Data.DbType.Int16, ordercontainer.TemperatureMode); db.AddInParameter(savecommand, "Vent", System.Data.DbType.String, ordercontainer.Vent ?? ""); db.AddInParameter(savecommand, "VentMode", System.Data.DbType.Int16, ordercontainer.VentMode); db.AddInParameter(savecommand, "GrossWeight", System.Data.DbType.String, ordercontainer.GrossWeight ?? ""); db.AddInParameter(savecommand, "CargoWeight", System.Data.DbType.String, ordercontainer.CargoWeight ?? ""); db.AddInParameter(savecommand, "IMOCode", System.Data.DbType.Int16, ordercontainer.IMOCode); db.AddInParameter(savecommand, "UNNo", System.Data.DbType.String, ordercontainer.UNNo ?? ""); db.AddInParameter(savecommand, "CargoType", System.Data.DbType.Int16, ordercontainer.CargoType); db.AddInParameter(savecommand, "TrailerType", System.Data.DbType.Int16, ordercontainer.TrailerType); db.AddInParameter(savecommand, "RequiredDate", System.Data.DbType.DateTime, ordercontainer.RequiredDate); db.AddInParameter(savecommand, "DehireDate", System.Data.DbType.DateTime, ordercontainer.DehireDate); db.AddInParameter(savecommand, "SpecialHandling", System.Data.DbType.Int16, ordercontainer.SpecialHandling); db.AddInParameter(savecommand, "CargoHandling", System.Data.DbType.String, ordercontainer.CargoHandling ?? ""); db.AddInParameter(savecommand, "Volume", System.Data.DbType.String, ordercontainer.Volume ?? ""); db.AddInParameter(savecommand, "Remarks", System.Data.DbType.String, ordercontainer.Remarks ?? ""); db.AddInParameter(savecommand, "ContainerRef", System.Data.DbType.String, ordercontainer.ContainerRef ?? ""); db.AddInParameter(savecommand, "CreatedBy", System.Data.DbType.String, ordercontainer.CreatedBy ?? ""); db.AddInParameter(savecommand, "ModifiedBy", System.Data.DbType.String, ordercontainer.ModifiedBy ?? ""); result = db.ExecuteNonQuery(savecommand, transaction); if (currentTransaction == null) transaction.Commit(); } catch (Exception ex) { if (currentTransaction == null) transaction.Rollback(); throw; } return (result > 0 ? true : false); } public bool Delete<T>(T item) where T : IContract { var result = false; var ordercontainer = (OrderContainer)(object)item; var connnection = db.CreateConnection(); connnection.Open(); var transaction = connnection.BeginTransaction(); try { var deleteCommand = db.GetStoredProcCommand(DBRoutine.DELETEORDERCONTAINER); db.AddInParameter(deleteCommand, "BranchID", System.Data.DbType.Int16, ordercontainer.BranchID); db.AddInParameter(deleteCommand, "ContainerKey", System.Data.DbType.String, ordercontainer.ContainerKey); db.AddInParameter(deleteCommand, "OrderNo", System.Data.DbType.String, ordercontainer.OrderNo); result = Convert.ToBoolean(db.ExecuteNonQuery(deleteCommand, transaction)); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw ex; } return result; } public IContract GetItem<T>(IContract lookupItem) where T : IContract { var item = ((OrderContainer)lookupItem); var ordercontainerItem = db.ExecuteSprocAccessor(DBRoutine.SELECTORDERCONTAINER, MapBuilder<OrderContainer>.BuildAllProperties(), item.BranchID,item.OrderNo,item.ContainerKey).FirstOrDefault(); if (ordercontainerItem == null) return null; return ordercontainerItem; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace coffeeSalesManag_CompApp.Models.CoffeeManagement { public class Coffee { public int ID { get; set; } private string _coffeeName; [Required] [RegularExpression(@"^[a-zA-Z ]{3,20}$", ErrorMessage = "Please enter a valid Coffee Name. Length should be between 3 and 20.")] public string CoffeeName { get { return _coffeeName; } set { Validator .ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "CoffeeName" }); _coffeeName = value; } } private string _coffeePrice; [Required] [RegularExpression("^[0-9]{1,5}.[0-9]{2}$", ErrorMessage ="Please enter a valid amount with precision of 2 digits.")] public string CoffePrice { get { return _coffeePrice; } set { Validator .ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "CoffePrice" }); _coffeePrice = value; } } [Required] public DateTime DateTimeStamp { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FiletCollider : MonoBehaviour { private GameObject curFly; private List<GameObject> flyCatchs; private void Start() { flyCatchs = new List<GameObject>(); } private void OnTriggerEnter(Collider other) { if(other.gameObject.CompareTag("Fly")) { curFly = other.gameObject; } } private void OnTriggerExit(Collider other) { if(other.gameObject.CompareTag("Fly")) { curFly = null; } } public void DestroyFly() { GameObject flyToCatch = curFly; flyCatchs.Add(flyToCatch); StartCoroutine(DesactivateFly(flyToCatch)); } public IEnumerator DesactivateFly(GameObject flyToDesactivate) { yield return new WaitForSeconds(0.2f); flyToDesactivate.SetActive(false); } public void RespawnFly() { for(int i = 0; i < flyCatchs.Count;++i) { flyCatchs[i].SetActive(true); } curFly = null; flyCatchs.Clear(); } public bool HasFly { get => curFly != null; } public bool IsGoldFly { get => curFly?.GetComponent<GoldFly>() != null; } }