text
stringlengths
13
6.01M
using UnityEngine; using System.Collections; public class PauseMenu : MonoBehaviour { private bool m_isPause = true; [SerializeField]private GameObject m_pauseMenu; [SerializeField]private GameObject m_waveMenu; [SerializeField]private GameObject m_buildMenu; public void OnButtonPress() { if (m_isPause) { m_isPause = false; m_pauseMenu.SetActive(true); m_waveMenu.SetActive(false); m_buildMenu.SetActive(false); Time.timeScale = 0; } else if (!m_isPause) { m_isPause = true; m_pauseMenu.SetActive(false); m_waveMenu.SetActive(true); Time.timeScale = 1; } } }
using InstaSharp.Endpoints; using InstaSharp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace InstaMagic { public class RelationshipViewModel { public List<User> Follows { get; set; } } public partial class RelationshipsPage : ContentPage { public RelationshipViewModel ViewModel { get; set; } public UserProfileViewModel UserViewModel { get; private set; } public RelationshipsPage(UserProfileViewModel userViewModel) { InitializeComponent(); UserViewModel = userViewModel; Init(); } private async void Init() { var relationships = new Relationships(App.InstagramConfig, App.Auth); ViewModel = new RelationshipViewModel(); var userResponce = await relationships.FollowedBy(); ViewModel.Follows = userResponce.Data; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Character_Movement_JoystickConf : MonoBehaviour { private Joystick_Move_Pattern _current; Transform MainCamera; public ActionObject ReachDestAct; public Player_Object player; private CharacterController _controller; private Quaternion _rotation; private float angle, offsetAngle, walkspeed, rotatespeed; public float RotationFloat, SpeedFloat; //private bool enabled; private bool CRRunning; public TransformData target; public BoolData ReachedDestination; public Vector3Data Load_Destination; public QuaternionData Rotation_Destination; private Vector3 _destination; void Start() { CRRunning = false; _controller = GetComponent<CharacterController> (); MainCamera = Camera.main.transform; EnableCC(); } private void FixedUpdate() { _current = player.Current; _current.Move(transform, _controller, MainCamera); } public void DisableCC() { _controller.enabled = false; enabled = false; } public void EnableCC() { _controller.enabled = true; enabled = true; } public void WalkTowards(float speed) { StartCoroutine(Walk_Towards(speed)); } public void WalkBack(float speed) { StartCoroutine(Walk_Backward(speed)); } public void SetPosition() { transform.position = target.trans.position; transform.rotation = target.trans.rotation; } public void LoadDest() { transform.position = Load_Destination.vector; transform.rotation = Rotation_Destination.rotation; } public IEnumerator Walk_Towards(float speed) { walkspeed = speed; rotatespeed = RotationFloat; _rotation = target.trans.rotation; _rotation.y += 180; ReachedDestination.value = false; CRRunning = true; StartCoroutine(Rotate()); yield return new WaitUntil( () => CRRunning == false); StartCoroutine(Walk()); yield return new WaitUntil( () => CRRunning == false); ReachDestAct.Action.Invoke(); } public void TurnTowards() { walkspeed = 0; rotatespeed = RotationFloat; _rotation = target.trans.rotation; _rotation.y += 180; StartCoroutine(Rotate()); } public IEnumerator Walk_Backward(float speed) { walkspeed = speed; rotatespeed = RotationFloat; ReachedDestination.value = false; _rotation = target.trans.rotation; CRRunning = true; StartCoroutine(Rotate()); yield return new WaitUntil( () => CRRunning == false); StartCoroutine(Walk()); yield return new WaitUntil( () => CRRunning == false); //Reach_Destination.Invoke(); ReachDestAct.Action.Invoke(); } public IEnumerator Rotate() { Debug.Log("Rotate"); CRRunning = true; _rotation = target.trans.rotation; while (!CheckRot(.5f)) { transform.rotation = Quaternion.Lerp(transform.rotation, _rotation, rotatespeed * Time.deltaTime); yield return new WaitForFixedUpdate(); } Debug.Log("Rotate Done"); CRRunning = false; } public IEnumerator Walk() { Debug.Log("Walk"); CRRunning = true; _destination = target.trans.position; _destination.y = transform.position.y; while (!ReachedDestination.value && (((transform.position.x > _destination.x + .1f) || (transform.position.x < _destination.x - .1f)) || ((transform.position.z > _destination.z + .1f) || (transform.position.z < _destination.z - .1f)))) { Debug.Log("Walking"); transform.position = Vector3.Lerp(transform.position, _destination, walkspeed * Time.deltaTime); yield return new WaitForFixedUpdate(); } Debug.Log("Walk Done"); SetPosition(); CRRunning = false; } private bool CheckRot(float offset) { if((transform.rotation.eulerAngles.y <= (_rotation.eulerAngles.y + offset)) && (transform.rotation.eulerAngles.y >= (_rotation.eulerAngles.y - offset))) return true; else { return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Clubber.Data { public enum Club_Category { Arts, Books, Academic, Games, Social, Humanitarian, Food, International} public class Club { [Key] public int ClubId { get; set; } [Required] public string Title { get; set; } [ForeignKey("Sponsor")] public int SponsorId { get; set; } public virtual Sponsor Sponsor { get; set; } [Display(Name = "Meeting Day")] public DayOfWeek MeetingDay { get; set; } [Required] [DataType(DataType.Time)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:H:mm}")] public DateTime MeetingTime { get; set; } [Required] [Display(Name="Club Category")] public Club_Category ClubType { get; set; } } }
using System; using System.Collections.Generic; namespace RestApiEcom.Models { public partial class VResCollecteRealisee { public int ColId { get; set; } public string ActcontPlaque { get; set; } public string FactCode { get; set; } public string TaxLibelle { get; set; } public string ActLibelle { get; set; } public string Zone { get; set; } public DateTime ColDate { get; set; } public float ColMontant { get; set; } public int ZoneId { get; set; } public float? FactMontant { get; set; } public string AcolMatricule { get; set; } public bool ColBExportPaiement { get; set; } public int AcolId { get; set; } public int? CommuneId { get; set; } public int? QuartierId { get; set; } public int? IlotId { get; set; } public int? LotId { get; set; } public string CommuneLibelle { get; set; } public string QuartierLibelle { get; set; } public string IlotLibelle { get; set; } public string LotLibelle { get; set; } } }
using System; namespace Point_on_Rectangle_Border { class Point_on_Rectangle_Border { static void Main(string[] args) { float x1, y1, x2, y2, x, y; x1 = float.Parse(Console.ReadLine()); y1 = float.Parse(Console.ReadLine()); x2 = float.Parse(Console.ReadLine()); y2 = float.Parse(Console.ReadLine()); x = float.Parse(Console.ReadLine()); y = float.Parse(Console.ReadLine()); if( ((x == x1) || (x == x2)) && ((y >= y1) && (y <= y2)) ) { Console.WriteLine("Border"); } else if ( ((y == y1) || (y == y2)) && ( (x >= x1) && (x <= x2)) ) { Console.WriteLine("Border"); } else { Console.WriteLine("Inside / Outside"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BPiaoBao.Client.UIExt.CommonControl { /// <summary> /// 按照步骤 1a 或 1b 操作,然后执行步骤 2 以在 XAML 文件中使用此自定义控件。 /// /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。 /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根 /// 元素中: /// /// xmlns:MyNamespace="clr-namespace:BPiaoBao.Client.UIExt.CommonControl" /// /// /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。 /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根 /// 元素中: /// /// xmlns:MyNamespace="clr-namespace:BPiaoBao.Client.UIExt.CommonControl;assembly=BPiaoBao.Client.UIExt.CommonControl" /// /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用, /// 并重新生成以避免编译错误: /// /// 在解决方案资源管理器中右击目标项目,然后依次单击 /// “添加引用”->“项目”->[浏览查找并选择此项目] /// /// /// 步骤 2) /// 继续操作并在 XAML 文件中使用控件。 /// /// <MyNamespace:PromptChrome/> /// /// </summary> public class PromptChrome : Control { static PromptChrome() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PromptChrome), new FrameworkPropertyMetadata(typeof(PromptChrome))); } protected override Size ArrangeOverride(Size arrangeBounds) { this.Width = 34; this.Height = 34; this.HorizontalAlignment = System.Windows.HorizontalAlignment.Right; this.VerticalAlignment = System.Windows.VerticalAlignment.Top; TranslateTransform tt = new TranslateTransform(); tt.X = 10; tt.Y = 5; this.RenderTransform = tt; return base.ArrangeOverride(arrangeBounds); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OthelloConsole; using System.Windows; using Microsoft.Win32; using System.IO; namespace Othello { class Game : IPlayable { public int boardsize; public Tile[,] tiles; private List<Tuple<int, int>> flips; private List<Tuple<int, int>> potentialFlips; int[,] direction = { { 1, 0 }, { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 1 }, { 1, -1 }, { -1, -1 }, { -1, 1 } }; public Game(bool isWhiteTurn, int size) { /* List used to flips the right tiles*/ flips= new List<Tuple<int, int>>(); potentialFlips = new List<Tuple<int, int>>(); /* Board size */ boardsize = size; /* List of the 64 tiles */ tiles = new Tile[boardsize, boardsize]; /*Tiles initialisation*/ for (int i=0;i< boardsize; i++) { for(int j=0;j< boardsize; j++) { tiles[i, j] = new Tile(); } } /* Board initialisation */ tiles[4, 4].state = state.white; tiles[3, 3].state = state.white; tiles[4, 3].state = state.black; tiles[3, 4].state = state.black; /* Search playable */ updatePlayables(isWhiteTurn); } /*Interface fuction isPlayable used as wrapper for our playable function*/ public bool isPlayable(int column, int line, bool isWhite) { bool tilePlayabe = false; if(isWhite) tilePlayabe=playable(column, line, state.white); else tilePlayabe=playable(column, line, state.black); return tilePlayabe; } /* Our perfekt algorithme to find the playables */ public bool playable(int c, int l, state s) { bool found = false; state otherState; if (s == state.white) otherState = state.black; else otherState = state.white; for(int i=0;i<8; i++) { if (found == true) { break; } int sl = l + direction[i, 0]; int sc = c + direction[i, 1]; bool got = false; while (sl >=0 && sl<=boardsize-1 && sc>=0 && sc<=boardsize-1) { if(tiles[sc,sl].state==state.empty || tiles[sc, sl].state==state.isAbleToPlay) { got = false; break; } if (tiles[sc, sl].state == otherState) { got = true; } if (tiles[sc, sl].state == s && got == false) { got = false; break; } if (tiles[sc, sl].state == s && got == true) { found = true; break; } sl = sl + direction[i, 0]; sc = sc + direction[i, 1]; } } return found; } /* Interface playmove function */ public bool playMove(int column, int line, bool isWhite) { if (tiles[column, line].state == state.isAbleToPlay) { if (isWhite == true) return verify(column, line, state.white, isWhite); else return verify(column, line, state.black, isWhite); } else return false; } /* Function that play and verify if a player won */ public bool verify(int column, int line, state s, bool isWhite) { tiles[column, line].state = s; flipPieces(column, line, s); if (updatePlayables(!isWhite)) return true; else return false; } /* Clear all playables field, is called after a move */ public void clearPlayables() { for (int i = 0; i < boardsize; i++) { for (int j = 0; j < boardsize; j++) { if (tiles[i, j].state == state.isAbleToPlay) { tiles[i, j].state = state.empty; } } } } /*Update the playable after a move */ public bool updatePlayables(bool isWhiteTurn) { clearPlayables(); int numberOfPlayables = 0; for (int i = 0; i < boardsize; i++) { for (int j = 0; j < boardsize; j++) { if(isPlayable(i,j, isWhiteTurn)) { if(tiles[i,j].state==state.empty) { tiles[i, j].state = state.isAbleToPlay; numberOfPlayables++; } } } } if(numberOfPlayables==0) return false; else return true; } /* Our perfekt flip algorithm */ public void flipPieces(int c, int l, state s) { flips.Clear(); state otherState=state.white; if (s == state.white) otherState = state.black; for (int i = 0; i < 8; i++) { int sl = l + direction[i, 0]; int sc = c + direction[i, 1]; potentialFlips.Clear(); bool got = false; while (sl >= 0 && sl <= boardsize - 1 && sc >= 0 && sc <= boardsize - 1) { if (tiles[sc, sl].state == state.empty || tiles[sc, sl].state == state.isAbleToPlay) { got = false; break; } if (tiles[sc, sl].state == otherState) { got = true; potentialFlips.Add(new Tuple<int, int>(sc, sl)); } if (tiles[sc, sl].state == s && got == false) { potentialFlips.Clear(); got = false; break; } if (tiles[sc, sl].state == s && got == true) { foreach (Tuple<int, int> item in potentialFlips) { int cVal = item.Item1; int lVal = item.Item2; flips.Add(new Tuple<int, int>(cVal, lVal)); } potentialFlips.Clear(); break; } sl = sl + direction[i, 0]; sc = sc + direction[i, 1]; } } foreach (Tuple<int, int> item in flips) { int cVal = item.Item1; int lVal= item.Item2; tiles[cVal, lVal].state = s; } } /* Interface part for IA */ public Tuple<char, int> getNextMove(int[,] game, int level, bool whiteTurn) { Tuple<char, int> tuple = new Tuple<char, int>('a',0); return tuple; } /* Interface function that get black score */ public int getBlackScore() { return getScore(state.black); } /* Interface function that get white score */ public int getWhiteScore() { return getScore(state.white); } /* Function that get the score using state */ public int getScore(state s) { int score = 0; for (int i = 0; i < boardsize; i++) { for (int j = 0; j < boardsize; j++) { if (tiles[i, j].state == s) score++; } } return score; } /* Function to reset, restart a game */ public void resetGame() { for (int i = 0; i < boardsize; i++) { for (int j = 0; j < boardsize; j++) { tiles[i, j].state = state.empty; } } tiles[4, 4].state = state.white; tiles[3, 3].state = state.white; tiles[4, 3].state = state.black; tiles[3, 4].state = state.black; updatePlayables(false); } /* Function to save a game state */ public void saveGame(bool isWhite) { string datas = ""; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Text file (*.txt)|*.txt"; if (saveFileDialog.ShowDialog() == true) { for (int i = 0; i < boardsize; i++) { for (int j = 0; j < boardsize; j++) { if(tiles[i, j].state==state.empty) datas += "e;"; if (tiles[i, j].state == state.black) datas += "b;"; if (tiles[i, j].state == state.white) datas += "w;"; if (tiles[i, j].state == state.isAbleToPlay) datas += "i;"; } } if (isWhite) datas += "t;"; else datas += "f;"; File.WriteAllText(saveFileDialog.FileName, datas); } } /* Function to Open a game state */ public void openGame(string datas,int i, int j) { if (datas == "e") tiles[i, j].state = state.empty; if (datas == "i") tiles[i, j].state = state.isAbleToPlay; if (datas == "w") tiles[i, j].state = state.white; if (datas == "b") tiles[i, j].state = state.black; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data.OleDb; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using CSHP230_Final.WebForms.Models; using CSHP230_Final.WebForms.Repository; namespace CSHP230_Final.WebForms { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public List<Class> ClassList { get { return GetAllClasses(); } } private List<Class> GetAllClasses() { // TODO: Have this method called once per request. It's called three times. CourseRegistrationRepository repo = new CourseRegistrationRepository(); List<Class> classes; repo.GetAllClasses(out classes); return classes; } } }
using System; using System.Reflection; namespace Terminal.Interactive.PoorMans { internal static class ReflectionExtensions { public static Type GetTraverseType(this MemberInfo member) { switch (member) { case PropertyInfo p: return p.PropertyType; case FieldInfo f: return f.FieldType; } return null; } public static object GetValue(this MemberInfo member, object parameter) { switch (member) { case PropertyInfo p: return p.GetValue(parameter); case FieldInfo f: return f.IsStatic ? f.GetValue(null) : f.GetValue(parameter); } throw new InvalidOperationException($"Cannot get value from {member.MemberType}"); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAppBackend.Models; using WebAppBackend.Models.DBmodels; using WebAppBackend.Models.IOmodels; namespace WebAppBackend.Controllers.IOControllers { [Route("api/[controller]")] [ApiController] public class IOUserController : Controller { private readonly IODBContext _context; public IOUserController(IODBContext context) { _context = context; } // GET: IOUserController/Details/username [HttpGet("{username}")] public async Task<ActionResult<IEnumerable<IOUser>>> GetUserWithUserFlowers(string username) { if(username == null) { return NotFound(); } var user = await _context.Users.FindAsync(username); if(user == null) { return NotFound(); } var userFlower = _context.User_Flowers.Where(uf => uf.Username.Contains(username)).ToList<User_Flower>(); return Ok(new IOUser( user.Username, user.First_name, user.Last_name, user.Password, userFlower )); } } }
using ClassLibrary1.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1.Repository { public class CamisaRepository : BaseRepository <Camisa> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.TransientFaultHandling; using Microsoft.ServiceBus; using RetryPolicy = Microsoft.Practices.TransientFaultHandling.RetryPolicy; namespace PushoverQ { class SubscriptionDisposer : ISubscription { private readonly NamespaceManager _namespaceManager; private readonly RetryPolicy _retryPolicy; private readonly string _topic; private readonly string _subscription; private readonly bool _isTransient; public SubscriptionDisposer(string topic, string subscription, bool isTransient, NamespaceManager namespaceManager, RetryPolicy retryPolicy) { _topic = topic; _subscription = subscription; _isTransient = isTransient; _namespaceManager = namespaceManager; _retryPolicy = retryPolicy; } public void Dispose(bool disposing) { if (disposing || _isTransient) _retryPolicy.ExecuteAction(() => _namespaceManager.DeleteSubscription(_topic, _subscription)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public async Task Unsubscribe() { await _retryPolicy.ExecuteAsync(() => _namespaceManager.DeleteSubscriptionAsync(_topic, _subscription)); GC.SuppressFinalize(this); } ~SubscriptionDisposer() { Dispose(false); } } }
using Android.App; using Android.Widget; using Android.OS; using Android.Net; using Com.Facebook.Drawee.View; namespace Fresco.Test { [Activity(Label = "Fresco.Test", MainLauncher = true)] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Com.Facebook.Drawee.Backends.Pipeline.Fresco.Initialize(this); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); { var uri = Uri.Parse("https://raw.githubusercontent.com/facebook/fresco/master/docs/static/logo.png"); var draweeView = (SimpleDraweeView)FindViewById(Resource.Id.basic_image); draweeView.SetImageURI(uri); } { var uri = Uri.Parse("http://www.gstatic.com/webp/gallery/2.webp"); var draweeView = (SimpleDraweeView)FindViewById(Resource.Id.webp_static); draweeView.SetImageURI(uri); } { var uri = Uri.Parse("https://www.gstatic.com/webp/gallery3/5_webp_ll.webp"); var draweeView = (SimpleDraweeView)FindViewById(Resource.Id.webp_translucent); draweeView.SetImageURI(uri); } { var uri = Uri.Parse("https://www.gstatic.com/webp/animated/1.webp"); var draweeView = (SimpleDraweeView)FindViewById(Resource.Id.webp_animated); var builder = Com.Facebook.Drawee.Backends.Pipeline.Fresco.NewDraweeControllerBuilder(); builder.SetAutoPlayAnimations(true); builder.SetOldController(draweeView.Controller); builder.SetUri(uri); draweeView.Controller = builder.Build(); } { var uri = Uri.Parse("http://frescolib.org/static/sample-images/fresco_logo_anim_full_frames_with_pause_s.gif"); var draweeView = (SimpleDraweeView)FindViewById(Resource.Id.gif_animated); var builder = Com.Facebook.Drawee.Backends.Pipeline.Fresco.NewDraweeControllerBuilder(); builder.SetAutoPlayAnimations(true); builder.SetOldController(draweeView.Controller); builder.SetUri(uri); draweeView.Controller = builder.Build(); } } } }
using System; using System.Text.RegularExpressions; namespace AddressBook { internal class AddRecord { /// <summary> /// Creates A Contact Object And Initialises All Its Fields /// </summary> /// <returns>Returns A Contact Object To Menu</returns> public static Contact AddDetails() { string Name; string OrganisationName; GetContactDetails: try { Name = ContactDetails.TakeName(); OrganisationName = ContactDetails.TakeOrganisationName(); } catch(InvalidSyntaxException exp) { Console.WriteLine(exp.Message); goto GetContactDetails; } Contact NewContact = new Contact(Name, OrganisationName); int NumberOfInputs = 1; PhoneNumberDetails: try { Console.WriteLine(Constants.NumberOfContact); NumberOfInputs = int.Parse(Console.ReadLine()); while (NumberOfInputs > 0) { PhoneNumber NewPhoneData = SetFields.SetPhoneNumber(); NewContact.addPhoneNumbers(NewPhoneData); NumberOfInputs--; } } catch(Exception exp) { Console.WriteLine(exp.Message+"\n"); goto PhoneNumberDetails; } AddressDetails: try { Console.WriteLine(Constants.NumberOfAddress); NumberOfInputs = int.Parse(Console.ReadLine()); while (NumberOfInputs > 0) { Address NewAddressData = SetFields.SetAddress(); NewContact.addAddresses(NewAddressData); NumberOfInputs--; } } catch(Exception exp) { Console.WriteLine(exp.Message+"\n"); goto AddressDetails; } return NewContact; } } }
using System.Windows.Forms; using GetLogsClient.ViewModels; namespace GetLogsClient.Commands { public class SelectPathCommand : CommandBase<SelectPathCommand> { public override void Execute(object parameter) { if (parameter is IMainWindowViewModel viewModel) { using (var dialog = new System.Windows.Forms.FolderBrowserDialog()) { System.Windows.Forms.DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrEmpty(dialog.SelectedPath)) { viewModel.SaveDirectory = dialog.SelectedPath; } } } } } }
using System; namespace Mccole.Geodesy.Calculator { /// <summary> /// Base class for all Geodesy calculators. /// </summary> public class CalculatorBase : ICoordinateFactory { private Func<ICoordinate> _factory = () => { return new Coordinate(); }; /// <summary> /// Base class for all Geodesy calculators. /// </summary> protected CalculatorBase() { } /// <summary> /// Validate the value as a bearing to ensure it's between 0 and 360. /// </summary> /// <param name="bearing">The value to validate.</param> protected static void ValidateBearing(double bearing) { ValidateBearing(bearing, nameof(bearing)); } /// <summary> /// Validate the value as a bearing to ensure it's between 0 and 360. /// </summary> /// <param name="bearing">The value to validate.</param> /// <param name="argumentName">The name of the value.</param> protected static void ValidateBearing(double bearing, string argumentName) { if (bearing < 0 || bearing > 360) { throw new ArgumentOutOfRangeException(argumentName, "A bearing cannot be less than zero or greater than 360."); } } /// <summary> /// Validate the value as a radius to ensure it's between the lower and upper boundaries of the various radius values of the Earth. /// <para>Works for both metres and kilometres.</para> /// </summary> /// <param name="radius">The value to validate.</param> protected static void ValidateRadius(double radius) { double kimometresMinimum = 6350; double kimometresMaximum = 6400; double metresMinimum = kimometresMinimum * 1000; double metresMaximum = kimometresMaximum * 1000; if (((radius >= metresMinimum && radius <= metresMaximum) || (radius >= kimometresMinimum && radius <= kimometresMaximum)) == false) { throw new ArgumentOutOfRangeException(nameof(radius), string.Format("The radius must be within the expected range {0}km to {1}km (in metres or kilometres).", kimometresMinimum, kimometresMaximum)); } } /// <summary> /// Create a new object that implements ICoordinate using the factory method previously supplied. /// </summary> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> /// <returns></returns> protected ICoordinate NewCoordinate(double latitude, double longitude) { ICoordinate coordinate = ((ICoordinateFactory)this).Create(); coordinate.Latitude = latitude; coordinate.Longitude = longitude; return coordinate; } /// <summary> /// Create a new object that implements ICoordinate using the factory method previously supplied. /// </summary> /// <returns></returns> public ICoordinate Create() { return _factory(); } /// <summary> /// Override the default factory method for creating an object that implements ICoordinate. /// </summary> /// <param name="factory"></param> public bool SetFactoryMethod(Func<ICoordinate> factory) { if (factory == null) { throw new ArgumentNullException(nameof(factory), "The argument cannot be null."); } _factory = factory; return true; } } }
using System; namespace DownloadExtractLib.Interfaces { public interface IDownloadedEvent { void GotItem(string parentUrl, string childUrl, Exception exception, int totalRefs, int doneRefs); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class GhostBehaviour : MonoBehaviour { //怪物对象 private Ghost ghost; private GameObject player; //属性参数 private Transform g_transform; private Animator anim; [SerializeField] public int ghostBlood = 1000; [SerializeField] private int maxBlood = 1000; [SerializeField] private float ghostAR = 2000f; [SerializeField] private float ghostFR = 20f; [SerializeField] private float ghostMS = 1f; private int preBlood; public FUntyEvent OnBloodChanged; private bool isInRange =true; private bool isAttack = false; //是否攻击 private int isDeadID = Animator.StringToHash("IsDead"); private int isStandingID = Animator.StringToHash("IsStanding"); private int skillID = Animator.StringToHash("Skill"); private int isRunID = Animator.StringToHash("IsRun"); private int isFightID = Animator.StringToHash("IsFight"); private bool isdead = false; private float offset; void Start() { preBlood = maxBlood; ghostBlood = maxBlood; g_transform = gameObject.transform.parent.transform.parent.GetComponent<Transform>(); anim = gameObject.transform.parent.transform.parent.GetComponent<Animator>(); player = GameObject.FindGameObjectWithTag("Player"); ghost = new Ghost(ghostBlood, ghostAR, g_transform.position, ghostFR, ghostMS, false); OnBloodChanged.Invoke((float)ghostBlood / maxBlood); } void Update() { offset = (player.transform.position - transform.position).magnitude; if (preBlood <= 0 && !isdead) { isdead = true; anim.SetBool(isDeadID, true); anim.SetBool(isStandingID, false); anim.SetBool(isRunID, false); anim.SetBool(isFightID, false); player.GetComponent<Animator>().SetBool("isAttacking", false); if (player.GetComponent<Shoot>() != null) player.GetComponent<Shoot>().hasTarget = false; if (player.GetComponent<Fight>() != null) player.GetComponent<Fight>().hasTarget = false; gameObject.GetComponent<AudioSource>().Play(); Invoke("dead", 2f); return; } else if (!isdead) { if (preBlood != ghostBlood) { OnBloodChanged.Invoke((float)ghostBlood / maxBlood); } preBlood = ghostBlood; Fight(); } } void Fight() { if (offset < ghostAR&&isAttack) //检测主角 { ghost.IsFightStatus = true; transform.LookAt(player.transform.parent.parent); if (ghost.IsFightStatus) { //不在攻击范围 if (Vector3.Distance(player.transform.position, gameObject.transform.parent.transform.parent.transform.position) > ghost.FightRange) { //走 anim.SetBool(isDeadID, false); anim.SetBool(isStandingID, false); anim.SetBool(isRunID, true); anim.SetBool(isFightID, false); //超出活动范围 if (Vector3.Distance(gameObject.transform.parent.transform.parent.transform.position, ghost.DefoultPosition) >= ghost.ActivityRange) { ghost.IsFightStatus = false; //isInRange = false; isAttack = false; } else { //活动范围内,朝玩家走 // isInRange = true; gameObject.transform.parent.transform.parent.transform.LookAt(player.transform); Vector3 dir = (player.transform.position - gameObject.transform.parent.transform.parent.transform.position).normalized; gameObject.transform.parent.transform.parent.transform.position += ghost.MoveSpeed * dir * Time.deltaTime; } } //在攻击范围内 else { //开始打 anim.SetBool(isStandingID, false); anim.SetBool(isFightID, true); anim.SetBool(isRunID, false); } } } else { //不让自动主角追怪物 // player.GetComponent<Player>().shoot.hasTarget = false; //超出活动范围,不想打了 if (Vector3.Distance(gameObject.transform.parent.transform.parent.transform.position, ghost.DefoultPosition) != 0) { if (Vector3.Distance(gameObject.transform.parent.transform.parent.transform.position, ghost.DefoultPosition) < 0.1f) { gameObject.transform.parent.transform.parent.transform.position = ghost.DefoultPosition; //站立,血满 gameObject.transform.parent.transform.parent.transform.LookAt(player.transform); anim.SetBool(isDeadID, false); anim.SetBool(isStandingID, true); anim.SetBool(isRunID, false); anim.SetBool(isFightID, false); } else { gameObject.transform.parent.transform.parent.transform.LookAt(ghost.DefoultPosition); anim.SetBool(isDeadID, false); anim.SetBool(isStandingID, false); anim.SetBool(isRunID, true); anim.SetBool(isFightID, false); Vector3 dir = (ghost.DefoultPosition - gameObject.transform.parent.transform.parent.transform.position).normalized; gameObject.transform.parent.transform.parent.transform.position += ghost.MoveSpeed * dir * Time.deltaTime; //回血 if (ghostBlood < maxBlood) { ghostBlood += (int)(maxBlood * 0.003f); } else ghostBlood = maxBlood; } } else { //回到原地,检测主角攻击 isAttack = true; } } } void dead() { Destroy(gameObject.transform.parent.parent.gameObject); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bank { public abstract class Account { //Filds private Customer customer; private decimal balance; private decimal intrestRate; //Properties public Customer Customer { get { return this.customer; } } public decimal Balance { get { return this.balance; } set { this.balance = value; } } public decimal IntrestRate { get { return this.intrestRate; } } //Constructor public Account(Customer customer, decimal balance, decimal intrestRate) { this.customer = customer; this.balance = balance; this.intrestRate = intrestRate / 100; } //Virtual methods public virtual decimal CalculateIntrestForPeriodOfMonths(int months) { if (months < 0) { throw new Exception("Months can't be negative number."); } return this.intrestRate * months; } //Methods that are the same for all accounts. public void Deposit(decimal money) { if (money < 0) { throw new Exception("Can't deposit negative amounts."); } this.Balance += money; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Player : MonoBehaviour { Animator animator; Rigidbody2D rb; Vector2 inputDir; bool canBreathe; float airStorage = 0f; bool isDying; bool isDead; SpriteRenderer sprite; GameObject particles; public GameObject FinishCanvasThing; public RectTransform airImage; public Vector2 minMaxVerSpeed = new Vector2(1f, 5f); public Vector2 minMaxHorSpeed = new Vector2(2f, 10f); public float burstAirSpeed = 5f; public float maxAir = 250f; public float airFillSpeed = 25f; public float airLoss = 1f; public float dieTime; public float dieFallSpeed = 50f; public Vector2 airImageSize = new Vector2(0f, 200f); void Start () { ScreenFader.FadeIn(); particles = transform.GetChild(1).gameObject; animator = GetComponentInChildren<Animator>(); rb = GetComponent<Rigidbody2D>(); sprite = GetComponentInChildren<SpriteRenderer>(); inputDir = new Vector2(); airStorage = maxAir; airImage.sizeDelta = new Vector2(maxAir, maxAir); } void Update () { if (!isDead) { bool breathing = Input.GetKey(KeyCode.Space); inputDir = new Vector2(); if (canBreathe && breathing) { //Inhale if (airStorage < maxAir) { float fillAmount = airFillSpeed * Time.deltaTime; airStorage += fillAmount; //float mappedAmount = map(fillAmount, 0f, maxAir, airImageSize.x, airImageSize.y); airImage.sizeDelta += new Vector2(fillAmount, fillAmount); } } else if (!breathing) { //Can move float hor = Input.GetAxis("Horizontal"); float ver = Input.GetAxis("Vertical"); if (canBreathe && ver > 0f) ver = 0f; inputDir = new Vector2(hor * map(airStorage, 0f, 250f, minMaxVerSpeed.y, minMaxVerSpeed.x), ver * map(airStorage, 0f, 250f, minMaxHorSpeed.y, minMaxHorSpeed.x)); } /*else if(!canBreathe && breathing) { if (airStorage > airLoss * 5f) { float fillAmount = -airLoss * 5f * Time.deltaTime; airStorage += fillAmount; airImage.sizeDelta += new Vector2(fillAmount, fillAmount); inputDir = new Vector2(0f, burstAirSpeed); } }*/ if (!canBreathe) { //Drain air if (airStorage > 0f) { float fillAmount = airLoss * Time.deltaTime; airStorage -= fillAmount; //float mappedAmount = map(fillAmount, 0f, maxAir, airImageSize.x, airImageSize.y); airImage.sizeDelta -= new Vector2(fillAmount, fillAmount); } } if (airStorage <= 100f) { animator.SetBool("isDrowning", true); } else if (airStorage > 100f) { animator.SetBool("isDrowning", false); } if(airStorage <= 0f && !isDead) { Dying(); } } } private void FixedUpdate() { if (!isDead && inputDir != Vector2.zero) rb.AddForce(inputDir, ForceMode2D.Force); if (inputDir != Vector2.zero) { Vector2 dir = inputDir; float angle = Mathf.Atan2(-dir.y, -dir.x) * Mathf.Rad2Deg; if (-angle >= 0f && -angle < 90f) { sprite.flipX = false; sprite.flipY = false; } else if (-angle >= 90f && -angle < 180f) { sprite.flipX = false; sprite.flipY = true; } if (-angle >= 180f && -angle < 270f) { sprite.flipX = false; sprite.flipY = true; } if (-angle >= 270f && -angle < 360f) { sprite.flipX = false; sprite.flipY = false; } transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0f, 0f, angle), Time.fixedDeltaTime * 20f); } } void Dying() { StartCoroutine(ScreenFader.FadeOut()); animator.SetBool("isDrowning", false); animator.SetTrigger("Die"); Camera.main.GetComponent<CameraMovement>().target = null; GetComponent<CircleCollider2D>().enabled = false; isDead = true; rb.velocity = new Vector2(0f, dieFallSpeed); Camera.main.GetComponent<CameraMovement>().PlayBubblesSound(); FinishCanvasThing.SetActive(true); //GameObject.FindGameObjectWithTag("ScoreScreen").SetActive(true); StartCoroutine(CountScore.Activate(CollectableSystem.instance.score)); } float map(float x, float in_min, float in_max, float out_min, float out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Breathable")) { animator.SetBool("isSwimming", false); particles.SetActive(false); rb.AddForce(new Vector2(0, -rb.velocity.y * 10f)); canBreathe = true; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.CompareTag("Breathable")) { animator.SetBool("isSwimming", true); particles.SetActive(true); canBreathe = false; } } }
using System.Collections.Generic; /// <summary> /// Advent of Code - Day 2 namespace /// </summary> namespace AdventOfCodeDay2 { /// <summary> /// Intcode class /// </summary> public class Intcode { /// <summary> /// Intcode /// </summary> private List<int> intcode = new List<int>(); /// <summary> /// Instruction pointer /// </summary> public uint InstructionPointer { get; private set; } /// <summary> /// Array access operator /// </summary> /// <param name="index">Index</param> /// <returns></returns> public int this[int index] { get => intcode[index]; set => intcode[index] = value; } /// <summary> /// Constructor /// </summary> /// <param name="intcode">Intcode</param> public Intcode(IEnumerable<int> intcode) { AddRange(intcode); } /// <summary> /// Add code /// </summary> /// <param name="code">Code</param> public void Add(int code) { intcode.Add(code); } /// <summary> /// Add intcode range /// </summary> /// <param name="intcode"></param> public void AddRange(IEnumerable<int> intcode) { if (intcode != null) { this.intcode.AddRange(intcode); } } /// <summary> /// Validate address /// </summary> /// <param name="address">Address</param> /// <param name="atAddress">At address</param> /// <exception cref="IntcodeInvalidAddressException">Invalid address</exception> private void ValidateAddress(int address, uint atAddress) { if ((address < 0) || (address >= intcode.Count)) { throw new IntcodeInvalidAddressException(address, atAddress); } } /// <summary> /// Get arguments /// </summary> /// <param name="leftAddress">Left address</param> /// <param name="rightAddress">Right address</param> /// <param name="outputAddress">Output address</param> /// <exception cref="IntcodeInsufficientArgumentsException">Insufficient arguments</exception> private void GetArguments(out int leftAddress, out int rightAddress, out int outputAddress) { if ((InstructionPointer + 3) >= intcode.Count) { throw new IntcodeInsufficientArgumentsException(((uint)(intcode.Count) - InstructionPointer) - 1U); } leftAddress = intcode[(int)(InstructionPointer + 1U)]; rightAddress = intcode[(int)(InstructionPointer + 2U)]; outputAddress = intcode[(int)(InstructionPointer + 3U)]; ValidateAddress(leftAddress, InstructionPointer + 1U); ValidateAddress(rightAddress, InstructionPointer + 2U); ValidateAddress(outputAddress, InstructionPointer + 3U); } /// <summary> /// Program step /// </summary> /// <returns>"true" if instruction was executed, except "false" if opcode was "99"</returns> /// <exception cref="IntcodeInvalidOpcodeException">Invalid opcode</exception> /// <exception cref="IntcodeInsufficientArgumentsException">Insufficient arguments</exception> /// <exception cref="IntcodeInvalidAddressException">Invalid address</exception> public bool Step() { bool ret = false; int left_address; int right_address; int output_address; if (InstructionPointer < intcode.Count) { switch (intcode[(int)InstructionPointer]) { case 1: GetArguments(out left_address, out right_address, out output_address); intcode[output_address] = intcode[left_address] + intcode[right_address]; InstructionPointer += 4U; ret = true; break; case 2: GetArguments(out left_address, out right_address, out output_address); intcode[output_address] = intcode[left_address] * intcode[right_address]; InstructionPointer += 4U; ret = true; break; case 99: ++InstructionPointer; break; default: throw new IntcodeInvalidOpcodeException(intcode[(int)InstructionPointer], InstructionPointer); } } return ret; } /// <summary> /// Execute program /// </summary> /// <exception cref="IntcodeInvalidOpcodeException">Invalid opcode</exception> /// <exception cref="IntcodeInsufficientArgumentsException">Insufficient arguments</exception> /// <exception cref="IntcodeInvalidAddressException">Invalid address</exception> public void Execute() { while (Step()) ; } /// <summary> /// Reset position /// </summary> public void ResetPosition() { InstructionPointer = 0U; } /// <summary> /// Clear intcode /// </summary> public void ClearIntcode() { intcode.Clear(); } /// <summary> /// Clear /// </summary> public void Clear() { ResetPosition(); ClearIntcode(); } } }
using CMS_Database.Entities; using CMS_Database.Interfaces; using CMS_Database.Repositories; using System; using System.Linq; using System.Reflection; using System.Web.Mvc; using System.Web.Routing; using WebMatrix.WebData; namespace CMS_ShopOnline.App_Start { public class SecurityFilter : ActionFilterAttribute { private bool _authenticate; private readonly INhanVien _NhanVien = new NhanVienRepository(); private readonly IPhanQuyen _PhanQuyen = new PhanQuyenRepository(); private readonly IListController _ListController = new ListControllerRepository(); private readonly ILoaiNV _LoaiNV = new LoaiNVRepository(); public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.IsChildAction) { CMS_ShopOnline.Helpers.Helper.Request(); } //_authenticate = (filterContext.ActionDescriptor.GetCustomAttributes(typeof(OverrideAuthenticationAttribute), true).Length == 0); //bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true); //if (skipAuthorization) //{ // return; //} if (!WebSecurity.Initialized) { WebSecurity.InitializeDatabaseConnection("DBConnection", "NhanVien", "Id", "TenTaiKhoan", true); } //base.OnActionExecuting(filterContext); string sControlerName = filterContext.RouteData.Values["Controller"] != null ? filterContext.RouteData.Values["Controller"].ToString().ToLower() : ""; string sActionName = filterContext.RouteData.Values["Action"] != null ? filterContext.RouteData.Values["Action"].ToString().ToLower() : ""; if (sActionName != "login".ToLower() && sActionName != "logoff" && sControlerName != "task" && sControlerName != "user") { if (!AccessRight(sControlerName)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "User" }, { "action", "NotPage" }, { "area", "Administration" } }); } } //Lấy danh sách các controller hiện có //Assembly asm = Assembly.GetExecutingAssembly(); //var controllerTypes = from t in asm.GetExportedTypes() // where typeof(IController).IsAssignableFrom(t) // select t; ////Nếu chưa có gì trong bảng thì thêm controller vô //if(_ListController.SelectAll().Count() == 0) //{ // foreach (var item in controllerTypes) // { // var ctl = new ListController(); // ctl.ControllerName = item.Name.Replace("Controller", ""); // ctl.IsDelete = false; // _ListController.Insert(ctl); // _ListController.Save(); // } // var getlistctl = _ListController.SelectAll().Where(x => x.IsDelete != true); // var getlistrole = _LoaiNV.SelectAll().Where(x => x.IsDelete != true); // foreach (var itemrole in getlistrole) // { // foreach (var itemctl in getlistctl) // { // var pq = new PhanQuyen(); // pq.IdControllerName = itemctl.Id; // pq.IdRole = itemrole.Id; // pq.IsDelete = false; // _PhanQuyen.Insert(pq); // _PhanQuyen.Save(); // } // } //} ////nếu thay thêm/xóa controlle thì cập nhật lại //if(controllerTypes.Count() != _ListController.SelectAll().Count()) //{ // _ListController.DeleteAll(); // _ListController.Save(); // _PhanQuyen.DeleteAll(); // _PhanQuyen.Save(); // //----- // foreach (var item in controllerTypes) // { // var ctl = new ListController(); // ctl.ControllerName = item.Name.Replace("Controller", ""); // ctl.IsDelete = false; // _ListController.Insert(ctl); // _ListController.Save(); // } // var getlistctl = _ListController.SelectAll().Where(x => x.IsDelete != true); // var getlistrole = _LoaiNV.SelectAll().Where(x => x.IsDelete != true); // foreach (var itemrole in getlistrole) // { // foreach (var itemctl in getlistctl) // { // var pq = new PhanQuyen(); // pq.IdControllerName = itemctl.Id; // pq.IdRole = itemrole.Id; // pq.IsDelete = false; // _PhanQuyen.Insert(pq); // _PhanQuyen.Save(); // } // } //} DeleteKMQH(); } public static void DeleteKMQH() { IKhuyenMai KhuyenMai = new KhuyenMaiRepository(); var daynow = DateTime.Now.Date; var abc = KhuyenMai.SelectAll().Where(x => x.IsDelete != true); foreach (var item in abc) { if (daynow > item.NgayKT.Date) { item.IsDelete = true; KhuyenMai.Update(item); KhuyenMai.Save(); } } } public static bool AccessRight(string ControlerName) { string sControlerName = ControlerName != null ? ControlerName.ToLower() : ""; if (sControlerName == "") return false; if (WebSecurity.IsAuthenticated) { var IdRole = Helpers.Helper.CurrentUser.IdLoaiNV; IListController _lc = new ListControllerRepository(); IPhanQuyen _pq = new PhanQuyenRepository(); var ListController = _lc.GetIdByName(sControlerName); var list = _pq.GetByName(ListController.Id,IdRole); if (list == null) { return false; } else { return true; } } else return false; } } }
using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections; /// <summary> /// Summary description for AarmsUser /// </summary> public class AarmsUser { string connStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString; string connJun = ConfigurationManager.ConnectionStrings["SCMCon"].ConnectionString; ArrayList arr = new ArrayList(); int resp = 0; SqlConnection obj_BizConn = new SqlConnection(); SqlConnection obj_SCMConn = new SqlConnection(); DataSet ds; public AarmsUser() { // // TODO: Add constructor logic here // string BizConnStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString; string SCMConnStr = ConfigurationManager.ConnectionStrings["SCMCon"].ConnectionString; obj_BizConn.ConnectionString = BizConnStr; obj_SCMConn.ConnectionString = SCMConnStr; obj_BizConn.Open(); obj_SCMConn.Open(); } //Insertion for UserLogDb Table public Int32 Insert_Aarmsuser(string obj_EmailID,string obj_Password, string obj_FirstName, string obj_MiddleName, string obj_LastName, int obj_DesignationID, string obj_Department, int obj_Age, int obj_GenderID, string obj_Mobile) { using (SqlCommand comm1 = new SqlCommand("Insert_BizConnect_UserLogDB", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into user log table da.SelectCommand.Parameters.AddWithValue("@obj_EmailID", obj_EmailID); da.SelectCommand.Parameters.AddWithValue("@obj_Password", obj_Password); da.SelectCommand.Parameters.AddWithValue("@obj_FirstName", obj_FirstName); da.SelectCommand.Parameters.AddWithValue("@obj_MiddleName", obj_MiddleName); da.SelectCommand.Parameters.AddWithValue("@obj_LastName", obj_LastName); da.SelectCommand.Parameters.AddWithValue("@obj_DesignationID", obj_DesignationID); da.SelectCommand.Parameters.AddWithValue("@obj_Department", obj_Department); da.SelectCommand.Parameters.AddWithValue("@obj_Age", obj_Age); da.SelectCommand.Parameters.AddWithValue("@obj_GenderID", obj_GenderID); da.SelectCommand.Parameters.AddWithValue("@obj_Phone","No Phone"); da.SelectCommand.Parameters.AddWithValue("@obj_Mobile", obj_Mobile); da.SelectCommand.Parameters.AddWithValue("@obj_Aarmsrep", "1"); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } // //Insert data into mapping table public Int32 Insert_ClientMapping() { int res = 0; using (SqlCommand comm = new SqlCommand("Insert_BizConnect_AarmsUserClientCustomerMapping", obj_BizConn)) { SqlDataAdapter ada = new SqlDataAdapter(comm); ada.SelectCommand.CommandType = CommandType.StoredProcedure; try { ada.SelectCommand.ExecuteNonQuery(); res = 1; } catch (Exception e) { res = 0; } } return res; } //Insertion for AarmsProfile public Int32 Insert_AarmsProfile(int obj_TLID, string obj_Business, string obj_FirstName, string obj_MiddleName, string obj_LastName, string obj_Department, int obj_Age, string obj_Designation, string obj_Address, string obj_area, string obj_city, string obj_pincode, string obj_ESI, string obj_PF, string obj_PAN, string obj_BloodGroup, string obj_Mobile, int obj_GenderID, string obj_EmailID, string obj_Password) { using (SqlCommand comm1 = new SqlCommand("Aarms_profileInsert", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into user log table da.SelectCommand.Parameters.AddWithValue("@TID", obj_TLID); da.SelectCommand.Parameters.AddWithValue("@Business", obj_Business); da.SelectCommand.Parameters.AddWithValue("@Firstname", obj_FirstName); da.SelectCommand.Parameters.AddWithValue("@Middlename", obj_MiddleName); da.SelectCommand.Parameters.AddWithValue("@Lastname", obj_LastName); da.SelectCommand.Parameters.AddWithValue("@Department", obj_Department ); da.SelectCommand.Parameters.AddWithValue("@age", obj_Age); da.SelectCommand.Parameters.AddWithValue("@Designation", obj_Designation); da.SelectCommand.Parameters.AddWithValue("@Address", obj_Address); da.SelectCommand.Parameters.AddWithValue("@Area", obj_area ); da.SelectCommand.Parameters.AddWithValue("@City", obj_city); da.SelectCommand.Parameters.AddWithValue("@Pincode", obj_pincode); da.SelectCommand.Parameters.AddWithValue("@Esinumber", obj_ESI); da.SelectCommand.Parameters.AddWithValue("@PFnumber", obj_PF); da.SelectCommand.Parameters.AddWithValue("@PANnumber", obj_PAN); da.SelectCommand.Parameters.AddWithValue("@BloadGroup", obj_BloodGroup); da.SelectCommand.Parameters.AddWithValue("@Mobilenumber", obj_Mobile); da.SelectCommand.Parameters.AddWithValue("@Gender", obj_GenderID); da.SelectCommand.Parameters.AddWithValue("@EmailID", obj_EmailID); da.SelectCommand.Parameters.AddWithValue("@Password", obj_Password); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } //Insert User permission public Int32 Insert_Userpermission(string obj_serviceid,string obj_accessid) { using (SqlCommand comm1 = new SqlCommand("User_permission", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into BizConnect_UserPermission table da.SelectCommand.Parameters.AddWithValue("@obj_serviceid", obj_serviceid); da.SelectCommand.Parameters.AddWithValue("@obj_accessid", obj_accessid); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } public DataSet Bizconnect_ShowLogisticsplan() { using (SqlCommand cmd = new SqlCommand("Bizconnect_ShowLogisticsplan", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.ExecuteNonQuery (); ds = new DataSet(); da.Fill(ds); } return ds; } public DataSet Bizconnect_ShowQuotedRates() { using (SqlCommand cmd = new SqlCommand("Bizconnect_ShowQuotedRates", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.ExecuteNonQuery(); ds = new DataSet(); da.Fill(ds); } return ds; } //Get_ClientsPostedADs public DataSet Get_ClientsPostedADs(int ClientID) { using (SqlCommand cmd = new SqlCommand("Get_ClientsPostedADs", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@obj_ClientID", ClientID); da.SelectCommand.ExecuteNonQuery(); ds = new DataSet(); da.Fill(ds); } return ds; } //Get_ReceivedQuoted public DataSet Get_ReceivedQuoted(int ClientID, DateTime FromDate, DateTime ToDate) { using (SqlCommand cmd = new SqlCommand("Get_ReceivedQuoted", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@obj_ClientID", ClientID); da.SelectCommand.Parameters.AddWithValue("@FromDate", FromDate); da.SelectCommand.Parameters.AddWithValue("@ToDate", ToDate); da.SelectCommand.ExecuteNonQuery(); ds = new DataSet(); da.Fill(ds); } return ds; } //TripRequested public DataSet TripRequested(int ClientID) { using (SqlCommand cmd = new SqlCommand("TripRequested", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@obj_Client", ClientID); da.SelectCommand.ExecuteNonQuery(); ds = new DataSet(); da.Fill(ds); } return ds; } //Trip cofirmed public DataSet TripConfirmed(int ClientID) { using (SqlCommand cmd = new SqlCommand("TripConfirmed", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@obj_Client", ClientID); da.SelectCommand.ExecuteNonQuery(); ds = new DataSet(); da.Fill(ds); } return ds; } //Insert Bizconnect_InsertActivity public Int32 Bizconnect_InsertActivity(string obj_ClientName, string obj_Location, string obj_Industry, string obj_ContactPerson, string obj_MobileNumber, string obj_Department, string obj_EnteredBy, DateTime obj_AppDate,string obj_emailid,string obj_action,string obj_Remarks) { using (SqlCommand comm1 = new SqlCommand("Bizconnect_InsertActivity", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into user log table da.SelectCommand.Parameters.AddWithValue("@ClientName", obj_ClientName); da.SelectCommand.Parameters.AddWithValue("@Location", obj_Location); da.SelectCommand.Parameters.AddWithValue("@Industry", obj_Industry); da.SelectCommand.Parameters.AddWithValue("@ContactPerson", obj_ContactPerson); da.SelectCommand.Parameters.AddWithValue("@MobileNumber", obj_MobileNumber); da.SelectCommand.Parameters.AddWithValue("@Department", obj_Department); da.SelectCommand.Parameters.AddWithValue("@EnteredBy", obj_EnteredBy); da.SelectCommand.Parameters.AddWithValue("@AppointmentDate", obj_AppDate); da.SelectCommand.Parameters.AddWithValue("@EmailID", obj_emailid); da.SelectCommand.Parameters.AddWithValue("@Action", obj_action); da.SelectCommand.Parameters.AddWithValue("@Remarks", obj_Remarks); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } //DisplayAppointDetails public DataSet DisplayAppointDetails(DateTime AppDate,int mode) { using (SqlCommand cmd = new SqlCommand("DisplayAppointDetails", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@AppDate", AppDate); da.SelectCommand.Parameters.AddWithValue("@Mode", mode); da.SelectCommand.ExecuteNonQuery(); ds = new DataSet(); da.Fill(ds); } return ds; } //Bizconnect_UpdateStatus public Int32 Bizconnect_UpdateStatus(string obj_ContactPerson, string obj_MobileNumber,string obj_EmailID ,string obj_Department, string obj_EnteredBy, DateTime obj_AppDate,string obj_MetBy ,string obj_Tripplan,string obj_action,string obj_Remarks,int obj_ActivityID ) { using (SqlCommand comm1 = new SqlCommand("Bizconnect_UpdateStatus", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //Update into user log table da.SelectCommand.Parameters.AddWithValue("@ContactPerson", obj_ContactPerson); da.SelectCommand.Parameters.AddWithValue("@MobileNumber", obj_MobileNumber); da.SelectCommand.Parameters.AddWithValue("@EmailID", obj_EmailID); da.SelectCommand.Parameters.AddWithValue("@Department", obj_Department); da.SelectCommand.Parameters.AddWithValue("@EnteredBy", obj_EnteredBy); da.SelectCommand.Parameters.AddWithValue("@AppointmentDate", obj_AppDate); da.SelectCommand.Parameters.AddWithValue("@MetBy", obj_MetBy); da.SelectCommand.Parameters.AddWithValue("@Tripplan", obj_Tripplan); da.SelectCommand.Parameters.AddWithValue("@Action", obj_action); da.SelectCommand.Parameters.AddWithValue("@Remarks", obj_Remarks); da.SelectCommand.Parameters.AddWithValue("@ActivityID", obj_ActivityID); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } public Int32 Bizconnect_InsertAARMSOperation(DateTime obj_CalDate, string obj_client, DateTime obj_ReceiveDate,string obj_transporter, int obj_Quotereceive, DateTime obj_ActionDate, int obj_rebid,string obj_marketaction,string EnteredBy) { using (SqlCommand comm1 = new SqlCommand("Bizconnect_InsertAARMSOperation", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into user log table da.SelectCommand.Parameters.AddWithValue("@obj_CalDate", obj_CalDate); da.SelectCommand.Parameters.AddWithValue("@obj_client", obj_client); da.SelectCommand.Parameters.AddWithValue("@obj_ReceiveDate", obj_ReceiveDate); da.SelectCommand.Parameters.AddWithValue("@obj_transporter", obj_transporter); da.SelectCommand.Parameters.AddWithValue("@obj_Quotereceive", obj_Quotereceive); da.SelectCommand.Parameters.AddWithValue("@obj_ActionDate", obj_ActionDate); da.SelectCommand.Parameters.AddWithValue("@obj_rebid", obj_rebid); da.SelectCommand.Parameters.AddWithValue("@obj_marketaction", obj_marketaction); da.SelectCommand.Parameters.AddWithValue("@obj_EnteredBy", EnteredBy); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } public DataSet AARMSPageReport() { DataSet ds_Report = new DataSet(); using (SqlCommand cmd = new SqlCommand("Get_AARMSPageReport", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { da.Fill(ds_Report); } catch (Exception e) { resp = 0; } finally { } } return ds_Report; } //Update Client Price public Int32 Update_ClientPrice(float ClientPrice, int LogisticsPlanid) { using (SqlCommand comm1 = new SqlCommand("Bizconnect_UpdateClientQuoteprice", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into BizConnect_UserPermission table da.SelectCommand.Parameters.AddWithValue("@ClientPrice",ClientPrice); da.SelectCommand.Parameters.AddWithValue("@LogisticsPlanID",LogisticsPlanid); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } // Update CostperTruck price public Int32 Update_CostperTruck(float Costpertruck,float clientPrice, int LogisticsPlanid) { using (SqlCommand comm1 = new SqlCommand("Bizconnect_UpdateCostPerTruck", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into BizConnect_UserPermission table da.SelectCommand.Parameters.AddWithValue("@LogisticSplanID", LogisticsPlanid); da.SelectCommand.Parameters.AddWithValue("@CostperTruck", Costpertruck); da.SelectCommand.Parameters.AddWithValue("@ClientPrice", clientPrice); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } public Int32 ScmJunPostReply_UpdateQuoteprice(int Replyid,float QuotePrice,string Type) { using (SqlCommand comm1 = new SqlCommand("ScmJunPostReply_UpdateQuoteprice", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into BizConnect_UserPermission table da.SelectCommand.Parameters.AddWithValue("@ReplyId", Replyid); da.SelectCommand.Parameters.AddWithValue("@QuotePrice", QuotePrice); da.SelectCommand.Parameters.AddWithValue("@Type", Type); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } //Tracking Updates public DataTable Bizconnect_TrackingUpdates() { DataTable dt = new DataTable(); using (SqlCommand cmd = new SqlCommand("Bizconnect_TrackingUpdates", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.ExecuteNonQuery(); da.Fill(dt); } return dt; } //Insert Tracking Log in Database public Int32 Bizconnect_InsertTrackingLog(int obj_AcceptanceID, string obj_Remarks) { using (SqlCommand comm1 = new SqlCommand("Bizconnect_InsertTrackingLog", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(comm1); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { //inserting into BizConnect_UserPermission table da.SelectCommand.Parameters.AddWithValue("@obj_AcceptanceID", obj_AcceptanceID); da.SelectCommand.Parameters.AddWithValue("@obj_Remarks", obj_Remarks); da.SelectCommand.ExecuteNonQuery(); resp = 1; } catch (Exception e) { resp = 0; } finally { } } return resp; } public DataSet Get_PrelaodClients() { DataSet ds_Report = new DataSet(); using (SqlCommand cmd = new SqlCommand("Bizconect_PreloadClients", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; try { da.Fill(ds_Report); } catch (Exception e) { resp = 0; } finally { } } return ds_Report; } public DataSet Get_PrelaodClientsReport(int ClientID, int Month) { DataSet Report = new DataSet(); using (SqlCommand cmd = new SqlCommand("Bizconnect_PreloadReport", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@obj_Client", ClientID); da.SelectCommand.Parameters.AddWithValue("@obj_Month", Month); try { da.Fill(Report); } catch (Exception e) { resp = 0; } finally { } } return Report; } public DataTable Search_DisplayAppointDetails(string SearchBy, int Mode) { DataTable dt = new DataTable(); using (SqlCommand cmd = new SqlCommand("Search_DisplayAppointDetails", obj_BizConn)) { SqlDataAdapter da = new SqlDataAdapter(cmd); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue("@SearchBy", SearchBy); da.SelectCommand.Parameters.AddWithValue("@Mode", Mode); try { da.Fill(dt); } catch (Exception e) { resp = 0; } finally { } } return dt; } }
using ComputerBuilderSystem.Contracts; namespace ComputerBuilderSystem.SystemComponents { public class Cpu64Bit : BaseCpu, ICentralProcessingUnit { private const int Bit64Size = 1000; public Cpu64Bit(byte numberOfCores) : base(numberOfCores, Bit64Size) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Model.Domain.Cost { class ExpenseUseEdit { } }
using UnityEngine; using System.Collections; public class CharacterController : MonoBehaviour { public void Move(float x, float y) { transform.Translate(x, y, 0); } }
using ClassLibrary.Entity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary.Configuration { class FormationFluent : EntityTypeConfiguration<Formation> { public FormationFluent() { ToTable("APP_FORMATION"); HasKey(e => e.Id); Property(f => f.Id).HasColumnName("EMP_ID").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(f => f.Title).HasColumnName("FOR_INTITULE").IsRequired(); Property(f => f.Date).HasColumnName("FOR_DATE"); HasRequired(ff => ff.Employee).WithMany(f => f.Formations).HasForeignKey(c => c.FkEmployee); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using HoloToolkit.Unity.InputModule; public class FloorPlaneController : MonoBehaviour, IInputClickHandler { public static float FloorPosY { get; private set; } public static bool isFloorPosYDone { get; private set; } [SerializeField] GameObject FloorPlane; [SerializeField] UnityEvent SpatialMappingDisable = new UnityEvent(); void Start() { InputManager.Instance.AddGlobalListener(this.gameObject); FloorPlane.SetActive(false); } void Update() { var hitObj = GazeManager.Instance.HitObject; if (hitObj == null || hitObj.layer != 31) { FloorPlane.SetActive(false); return; } var hitPos = GazeManager.Instance.HitPosition; if (Camera.current.transform.position.y < hitPos.y) { FloorPlane.SetActive(false); return; } //hitPos.y += 0.001f; // FloorPlaneを1mm浮かす FloorPlane.transform.position = hitPos; var angles = Quaternion.LookRotation(Camera.current.transform.position - FloorPlane.transform.position).eulerAngles; FloorPlane.transform.rotation = Quaternion.Euler(0f, angles.y, angles.z); FloorPlane.SetActive(true); } public void OnInputClicked(InputClickedEventData eventData) { var hitObj = GazeManager.Instance.HitObject; if (hitObj == null || hitObj.layer != 31) return; var y = GazeManager.Instance.HitPosition.y; FloorPosY = y; FloorPlane.SetActive(false); isFloorPosYDone = true; SpatialMappingDisable.Invoke(); } }
using ApplicationLibrary; using LRB; using LRB.Lib; using LRB.Lib.Domain; using LRBMvc.Models; using SimpleSecurity; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace LRBMvc.Controllers { [Authorize] public class LandApplicationController : Controller { LandBureau Bureau; public LandApplicationController() : base() { Bureau = new LandBureau(this); } // // GET: /LandApplication public ActionResult Index() { var username = User.Identity.Name; return View(LandRecords.GetApplications(WebSecurity.CurrentUserName)); } public ActionResult Create() { Requirement model = new Requirement(); return View(model); } [HttpPost] public ActionResult Create(Requirement model) { var app = LandRecords.CreateApplication(model); Bureau.SetAppId(app.Id); Bureau.setRequirement(model); return RedirectToAction("ContactInformation"); } public ActionResult ContactInformation() { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } var app = LandRecords.GetApplication(int.Parse(appId.ToString())); if (null == app) { return RedirectToAction("Index"); } var appType = Bureau.GetRequirement().applicationType; ViewBag.ApplicationType = appType; Party model = app.ContactPerson; if (model == null) { model = new Party(); } return View(model); } public ActionResult Continue(int id) { var app = LandRecords.GetApplication(id); Bureau.SetAppId(id); var requirement = new Requirement() { applicationType = app.ApplicationType, landSize = Convert.ToInt32(app.PrimaryProperty.LandSize), landUse = app.PrimaryProperty.LandUse, landSizeUnit = app.PrimaryProperty.LandSizeUnit }; Bureau.setRequirement(requirement); return RedirectToAction("ContactInformation"); } [HttpPost] public ActionResult ContactInformation(Party model) { var appId = Session["appId"]; if (appId == null) { //Flash.Instance.Notice("Your Session Has Expired, Please select incomplete application"); return RedirectToAction("Index"); } if (ModelState.IsValid) { LandRecords.SaveApplication(int.Parse(appId.ToString()), model); } return RedirectToAction("PropertyInformation"); } public ActionResult PropertyInformation() { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } var app = LandRecords.GetApplication(int.Parse(appId.ToString())); if (null == app) { return RedirectToAction("Index"); } List<int> months = new List<int>(); List<int> years = new List<int>(); for (int i = 0; i < 100; i++) { years.Add(i); } for (int i = 1; i < 13; i++) { months.Add(i); } ViewBag.Months = months; ViewBag.Years = years; Property model = app.Properties.FirstOrDefault(); return View(model); } [HttpPost] public ActionResult PropertyInformation(Property model) { var appId = Session["appId"]; if (appId == null) { //Flash.Instance.Notice("Your Session Has Expired, Please select incomplete application"); return RedirectToAction("Index"); } if (ModelState.IsValid) { LandRecords.SaveApplication(int.Parse(appId.ToString()), model); } return RedirectToAction("OptionalInformation"); } public ActionResult OptionalInformation() { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } var app = LandRecords.GetApplication(int.Parse(appId.ToString())); if (null == app) { return RedirectToAction("Index"); } Optional model = app.OptionalRequirement; if (model == null) { model = new Optional(); } return View(model); } [HttpPost] public ActionResult OptionalInformation(Optional model) { var appId = Session["appId"]; if (appId == null) { return RedirectToAction("Index"); } if (ModelState.IsValid) { LandRecords.SaveApplication(int.Parse(appId.ToString()), model); } return RedirectToAction("RequiredDocuments"); } public ActionResult RequiredDocuments() { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } var app = LandRecords.GetApplication(int.Parse(appId.ToString())); var requirement = Bureau.GetRequirement(); ViewBag.Requirement = requirement; if (null == app) { return RedirectToAction("Index"); } DocumentManager model = LandRecords.GetDocumentManager(Bureau.GetAppId().Value); if (model == null) { model = new DocumentManager(); } ViewBag.Documents = app.Documents; ViewBag.MissingDocuments = Bureau.GetRemainingDocuments(app.Documents); ViewBag.IsComplete = Bureau.IsComplete(app.Documents); return View(model); } [HttpPost] public ActionResult RequiredDocuments(DocumentManager model, IEnumerable<HttpPostedFileBase> files, HttpPostedFileBase evidence, HttpPostedFileBase developmentlevy, HttpPostedFileBase fireservice, HttpPostedFileBase policereport, HttpPostedFileBase certificate, HttpPostedFileBase feasibilityreport, HttpPostedFileBase powers, HttpPostedFileBase passport, HttpPostedFileBase surveyplan) { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } Bureau.SaveDocument(evidence, Bureau.EVIDENCE, "standardDocument"); Bureau.SaveDocument(developmentlevy, Bureau.DEVELOPMENT_LEVY, "standardDocument"); Bureau.SaveDocument(certificate, Bureau.CERTIFICATE, "standardDocument"); Bureau.SaveDocument(surveyplan, Bureau.SURVEY_PLAN, "cadastralSurvey"); Bureau.SaveDocument(fireservice, Bureau.FIRE_SERVICE, "standardDocument"); Bureau.SaveDocument(policereport, Bureau.POLICE_REPORT, "standardDocument"); Bureau.SaveDocument(feasibilityreport, Bureau.FEASIBILITY, "standardDocument"); Bureau.SaveDocument(powers, Bureau.POWERS, "powerOfAttorney"); Bureau.SaveDocument(passport, Bureau.PASSPORT, "idVerification"); LandRecords.SaveApplication(int.Parse(appId.ToString()), model); return RedirectToAction("RequiredDocuments"); } public ActionResult Summary() { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } var model = LandRecords.GetApplication(int.Parse(appId.ToString())); var c = model.ContactPerson; var p = model.PrimaryProperty; if (null == model) { return RedirectToAction("Index"); } return View(model); } public ActionResult Complete() { var appId = Session["appId"]; if (null == appId) { return RedirectToAction("Index"); } var model = LandRecords.GetApplication(int.Parse(appId.ToString())); if (null == model) { //Flash.Instance.Error("Application with that Id does not exist"); return RedirectToAction("Index"); } SolaService solaService = new SolaService(int.Parse(appId.ToString())); var solaApp = solaService.SubmitToSola(); LandRecords.UpdateStatus(Bureau.GetAppId().Value, solaApp.statusCode, solaApp.id, solaApp.nr); int Id = Convert.ToInt32(appId); LandRecords.SubmitApplication(Id); Session["appId"] = null; return RedirectToAction("View", "LandApplication", new { id = Id }); } public ActionResult View(int id) { //if (Bureau.isSolaOnline() == true) //{ // Bureau.UpdateApplicationStatus(id); //} var app = LandRecords.GetApplication(id); var fees = LandFees.Calculate_C_of_O_Charges( 2014, (float)app.PrimaryProperty.LandSize, LandFees.getLandValue(app), LandFees.getLandDevelopment(app), LandFees.getLandUse(app) ); ViewBag.Fee = fees; ViewBag.LandSize = app.PrimaryProperty.LandSize; ViewBag.LandUnit = app.PrimaryProperty.LandSizeUnit; ViewBag.Use = LandFees.getLandUse(app); return View(app); } // // GET: /LandApplications/Delete/5 [Authorize] public ActionResult Delete(int id = 0) { var app = LandRecords.GetApplication(id); if (app == null) { return HttpNotFound(); } return View(app); } // // POST: /LandApplications/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { LandRecords.Remove(id); return RedirectToAction("Index"); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; using System.Collections; using System.Collections.Generic; namespace DotNetNuke.Collections.Internal { public class NaiveLockingList<T> : IList<T> { private readonly SharedList<T> _list = new SharedList<T>(); //TODO is no recursion the correct policy void DoInReadLock(Action action) { DoInReadLock(() =>{ action.Invoke(); return true; }); } TRet DoInReadLock<TRet>(Func<TRet> func) { using (_list.GetReadLock()) { return func.Invoke(); } } void DoInWriteLock(Action action) { DoInWriteLock(() => { action.Invoke(); return true; }); } private TRet DoInWriteLock<TRet>(Func<TRet> func) { using (_list.GetWriteLock()) { return func.Invoke(); } } /// <summary> /// Access to the underlying SharedList /// <remarks> /// Allows locking to be explicitly managed for the sake of effeciency /// </remarks> /// </summary> public SharedList<T> SharedList { get { return _list; } } public IEnumerator<T> GetEnumerator() { //disposal of enumerator will release read lock //TODO is there a need for some sort of timed release? the timmer must release from the correct thread //if using RWLS var readLock = _list.GetReadLock(); return new NaiveLockingEnumerator(_list.GetEnumerator(), readLock); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(T item) { DoInWriteLock(() => _list.Add(item)); } public void Clear() { DoInWriteLock(() => _list.Clear()); } public bool Contains(T item) { return DoInReadLock(() => _list.Contains(item)); } public void CopyTo(T[] array, int arrayIndex) { DoInReadLock(() => _list.CopyTo(array, arrayIndex)); } public bool Remove(T item) { return DoInWriteLock(() => _list.Remove(item)); } public int Count { get { return DoInReadLock(() => _list.Count); } } public bool IsReadOnly { get { return false; } } public int IndexOf(T item) { return DoInReadLock(() => _list.IndexOf(item)); } public void Insert(int index, T item) { DoInWriteLock(() => _list.Insert(index, item)); } public void RemoveAt(int index) { DoInWriteLock(() => _list.RemoveAt(index)); } public T this[int index] { get { return DoInReadLock(() => _list[index]); } set { DoInWriteLock(() => _list[index] = value); } } public class NaiveLockingEnumerator : IEnumerator<T> { private readonly IEnumerator<T> _enumerator; private bool _isDisposed; private readonly ISharedCollectionLock _readLock; public NaiveLockingEnumerator(IEnumerator<T> enumerator, ISharedCollectionLock readLock) { _enumerator = enumerator; _readLock = readLock; } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } public T Current { get { return _enumerator.Current; } } object IEnumerator.Current { get { return Current; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { //dispose managed resrources here _enumerator.Dispose(); _readLock.Dispose(); } //dispose unmanaged resrources here _isDisposed = true; } } ~NaiveLockingEnumerator() { Dispose(false); } } } }
using AutoMapper; using iCopy.Model.Request; using iCopy.SERVICES.Extensions; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using iCopy.Database.Context; namespace iCopy.SERVICES.Services { public class CountryService : CRUDService<Database.Country, Model.Request.Country, Model.Request.Country, Model.Response.Country, Model.Request.CountrySearch, int> { public CountryService(DBContext ctx, IMapper mapper) : base(ctx, mapper) { } public override async Task<Tuple<List<Model.Response.Country>, int>> GetByParametersAsync(CountrySearch search, string order, string nameOfColumnOrder, int start, int length) { var query = ctx.Countries.AsQueryable(); if (!string.IsNullOrWhiteSpace(search.Name)) query = query.Where(x => x.Name.Contains(search.Name, StringComparison.CurrentCultureIgnoreCase)); if (!string.IsNullOrWhiteSpace(search.ShortName)) query = query.Where(x => x.ShortName.Contains(search.ShortName, StringComparison.CurrentCultureIgnoreCase)); if (!string.IsNullOrWhiteSpace(search.PhoneCode)) query = query.Where(x => x.PhoneNumberCode == search.PhoneCode); if (search.Active != null) query = query.Where(x => x.Active == search.Active); if (nameof(Database.Country.Name) == nameOfColumnOrder) query = query.OrderByAscDesc(x => x.Name, order); else if (nameof(Database.Country.ShortName) == nameOfColumnOrder) query = query.OrderByAscDesc(x => x.ShortName, order); else if (nameof(Database.Country.PhoneNumberCode) == nameOfColumnOrder) query = query.OrderByAscDesc(x => x.PhoneNumberCode, order); else if (nameof(Database.Country.ID) == nameOfColumnOrder) query = query.OrderByAscDesc(x => x.ID, order); var count = await query.CountAsync(); query = query.Skip(start).Take(length); return new Tuple<List<Model.Response.Country>, int>(mapper.Map<List<Model.Response.Country>>(await query.ToListAsync()), count); } } }
using System; using Parse; namespace AssemblyCSharp { public class LeaderBoardEntry { public int deathCount { get; set; } public float time { get; set; } public string playerName { get; set; } public string levelName { get; set; } public LeaderBoardEntry (ParseObject po) { this.deathCount = po.Get<int> ("deathCount"); this.time = po.Get<float> ("timeCompletedInSeconds"); this.playerName = po.Get<string> ("playerName"); this.levelName = po.Get<string> ("levelName"); } public LeaderBoardEntry () { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Estante : MonoBehaviour { public AudioSource source; public Prateleira[] prat; public int quantidade; bool movimento; Animator anim; [SerializeField] Animator mask; // Start is called before the first frame update void Start() { source = GetComponent<AudioSource>(); anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { if (quantidade >= 18) { quantidade = 0; Controller.pontos += 100; anim.SetTrigger("IrEsquerda"); mask.SetTrigger("Mask"); } } public void Resetar() { foreach (var p in prat) { p.Resetar(); } Controller.vida = 7; } public void Som() { source.Play(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MPD.Entities.Domain { public partial class DocumentType { public DocumentType() { Document = new HashSet<Document>(); } public short DocumentTypeId { get; set; } [Required] [StringLength(50)] public string Type { get; set; } [InverseProperty("DocumentTypeNavigation")] public ICollection<Document> Document { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; namespace Enrollment.Domain { static class WriterForEnums { #region Constants const string VALUES = "#Values#"; //const string SAVE_PATH = @"C:\.NetCore\Samples\EnrollmentUniversity\DomainFiles"; const string SAVE_PATH = @"C:\.github\BlaiseD\Enrollment.XPlatform\Enrollment.Domain"; #endregion Constants internal static void Write() { typeof(Data.BaseDataClass).Assembly.GetTypes() .Where(p => p.IsEnum) .ToList() .ForEach(t => WriteEnum(t)); } private static void WriteEnum(Type type) { void DoWrite(string name, IEnumerable<string> values, string path) { using (StreamWriter sr = new StreamWriter(string.Format(CultureInfo.InvariantCulture, "{0}\\{1}.cs", SAVE_PATH, name), false, Encoding.UTF8)) { sr.Write ( File.ReadAllText(string.Format(CultureInfo.InvariantCulture, "{0}\\EnumTemplate.txt", path)) .Replace("#Name#", name) .Replace(VALUES, string.Join(string.Concat(",", Environment.NewLine), values)) ); } } DoWrite ( type.Name, type.GetEnumNames().Select(n => string.Format("\t\t{0}", n)), Directory.GetCurrentDirectory() ); } } }
namespace Promact.Oauth.Server.Models.ApplicationClasses { public class LoginAsync { public string UserId { get; set; } public string Role { get; set; } } }
using FatCat.Nes.OpCodes.Transfers; using JetBrains.Annotations; namespace FatCat.Nes.Tests.OpCodes.Transfers { [UsedImplicitly] public class TransferAccumulatorToXRegisterTests : TransferTests { protected override byte CpuTransferFromItem { get => cpu.Accumulator; set => cpu.Accumulator = value; } protected override string ExpectedName => "TAX"; protected override byte ExpectedValue => Accumulator; protected override byte CpuTransferItem => cpu.XRegister; public TransferAccumulatorToXRegisterTests() => opCode = new TransferAccumulatorToXRegister(cpu, addressMode); } }
using MessageContract; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EASEntity { /// <summary> /// 人员信息 /// </summary> public class Person : IPerson, IPrimarykey { /// <summary> /// 名字 /// </summary> public string Name { get; set; } /// <summary> /// 邮箱 /// </summary> public string Email { get; set; } /// <summary> /// 电话 /// </summary> public string Telephone { get; set; } /// <summary> /// 身份证 /// </summary> public string IdentityCard { get; set; } /// <summary> /// 地址 /// </summary> public string Address { get; set; } /// <summary> /// EAS系统中对象主键 /// </summary> public string EASPrimaryKey { get; set; } public long PrimaryKey { get; set; } /// <summary> /// 编号 /// </summary> public string FNumber { get; set; } /// <summary> /// 发布状态 /// </summary> public PublishStatus PublishStatus { get; set; } /// <summary> /// 历史操作信息记录 /// </summary> public List<VersionHistory<IPerson>> VersionHistorys { get; set; } /// <summary> /// 注意不对主键进行判断 ! /// </summary> /// <param name="obj">被比较的对象</param> /// <returns></returns> public override bool Equals(object obj) { if (obj == null || obj as Person == null) { return false; } else { var p = obj as Person; if (p.Address != this.Address) { return false; } if (p.Email != this.Email) { return false; } if (p.IdentityCard != this.IdentityCard) { return false; } if (p.Name != this.Name) { return false; } if (p.Telephone != this.Telephone) { return false; } if (p.Address != this.Address) { return false; } return true; } } public override int GetHashCode() { return base.GetHashCode(); } public Person() { this.VersionHistorys = new List<VersionHistory<IPerson>>(); } public IPerson ToPersonInterface() { return new Person() { Address = this.Address, EASPrimaryKey = this.EASPrimaryKey, Email = this.Email, IdentityCard = this.IdentityCard, Name = this.Name, PublishStatus = this.PublishStatus, Telephone = this.Telephone, FNumber = this.FNumber }; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class PressuredDoorPuzzle : NetworkBehaviour { private enum TypeOfDoor { singleSwitch, doubleSwitch } [SerializeField] private TypeOfDoor puzzleDoor; public GameObject door; public GameObject presssurePlate1; public GameObject pressurePlate2; // Use this for initialization void Start () { } // Update is called once per frame void Update () { switch (puzzleDoor) { case TypeOfDoor.singleSwitch: if (presssurePlate1.GetComponent<platformScript>().isTriggered == true) { door.GetComponent<Animator>().SetBool("OpenDoor", true); } else if (pressurePlate2.GetComponent<platformScript>().isTriggered == true) { door.GetComponent<Animator>().SetBool("OpenDoor", true); } else { door.GetComponent<Animator>().SetBool("OpenDoor", false); } break; case TypeOfDoor.doubleSwitch: if (presssurePlate1.GetComponent<platformScript>().isTriggered == true && pressurePlate2.GetComponent<platformScript>().isTriggered == true) { door.GetComponent<Animator>().SetBool("OpenDoor", true); } else { door.GetComponent<Animator>().SetBool("OpenDoor", false); } break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using QOMS.Model; namespace QOMS.Class { public class ListViewAdapter_Gwbg : BaseAdapter<M_tb_gwbg> { Activity context; public List<M_tb_gwbg> mings; public ListViewAdapter_Gwbg(Activity context, List<M_tb_gwbg> mings) { this.context = context; this.mings = mings; } public override int Count { get { return this.mings.Count; } } public override long GetItemId(int position) { return position; } public override M_tb_gwbg this[int position] { get { return this.mings[position]; } } public override View GetView(int position, View convertView, ViewGroup parent) { var itme = this.mings[position]; convertView = LayoutInflater.From(context).Inflate(Resource.Layout.PostChangeRecord_Items, parent, false); TextView tv_xh = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_xh); TextView tv_gw = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_gw); TextView tv_yry = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_yry); TextView tv_bgry = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_bgry); TextView tv_bgrq = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_bgrq); TextView tv_bgly = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_bgly); TextView tv_czr = convertView.FindViewById<TextView>(Resource.Id.gwbg_item_czr); tv_xh.Text = (position + 1).ToString(); tv_gw.SetText(itme.Post, TextView.BufferType.Normal); tv_yry.SetText(itme.OldName, TextView.BufferType.Normal); tv_bgry.SetText(itme.NewName, TextView.BufferType.Normal); tv_bgrq.SetText(itme.ChangeTime, TextView.BufferType.Normal); tv_bgly.SetText(itme.ChangesSource, TextView.BufferType.Normal); tv_czr.SetText(itme.Operation, TextView.BufferType.Normal); return convertView; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DotNetWebIDE.SolutionResolve { public class RegexExpressionConst { /// <summary> /// GUID的正则表达式,格式 FAE04EC0-301F-11D3-BF4B-00C04F79EFBC /// </summary> public const string GuidExp = @"\w{8}-(\w{4}-){3}\w{12}"; /// <summary> /// 匹配[工程文件命名] /// </summary> public const string ProjectExt = @"[a-z][\s\.\-\w]+"; /// <summary> /// 匹配[相对路径] /// </summary> public const string RelativePathExt = @"(\\?([a-z][\s\.\-\w]+))+"; } }
using System; namespace Paydock.SDK { public static class MimeTypes { public const String FORM_ENCODED_DATA = "application/x-www-form-urlencoded"; public const String JSON = "application/json"; } }
using Domain.Entities; using Library_System_v1.Models; using MongoDB.Bson; using RepositoryDB; using RepositoryDB.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Security; using Utilities; namespace Library_System_v1.Controllers { public class LoginController : Controller { // GET: Login public ActionResult Index() { // We do not want to use any existing identity information EnsureLoggedOut(); return View(); } #region == Login Function == //GET: EnsureLoggedOut private void EnsureLoggedOut() { // If the request is (still) marked as authenticated we send the user to the logout action if (Request.IsAuthenticated) Logout(); } //POST: Login Function [HttpPost] public async Task<ActionResult> Index(LoginModel _logModel) { #region -- Variables Declaractions -- string OldHASHValue = string.Empty; #endregion -- END -- try { //_adminMaster.adEmail = _logModel.Email; //_adminMaster.adPassword = _logModel.Password; if (_logModel != null && !string.IsNullOrEmpty(_logModel.Email) && !string.IsNullOrEmpty(_logModel.Password)) { var context = new MongoDataContext(); //AdminMaster logDetails = await new GenericRepository<AdminMaster>(context).GetByCustomAsync(new AdminMaster(), _logModel.Email); AdminMaster logDetails = await new GenericRepository<AdminMaster>(context).GetByCustomAsync(x => x.adEmail != null, "adEmail", _logModel.Email); if (logDetails != null) { ObjectId _useId = new ObjectId(); _useId = logDetails.Id; OldHASHValue = logDetails.PasswordHashKey; //_logModel.PasswordHashKey == null ? new Cipher().Encrypt(_logModel.Email + _logModel.Password) : logDetails.PasswordHashKey; if (OldHASHValue != null) { bool isLogin = CompareHashValue(_logModel.Email.ToString(), _logModel.Password, OldHASHValue); if (isLogin) { //Login Success //For Set Authentication in Cookie (Remeber ME Option) SignInRemember(logDetails.adEmail.ToString(), false); Session["User_Email"] = logDetails.adEmail; Session["User_Name"] = logDetails.adName; Session["UserID"] = _useId.ToString(); //Set A Unique ID in session if (logDetails.adCode == "Admin") { return Json(new { redirectionURL = "/Admin/AdminDashboard/Index", logDetails = logDetails }, JsonRequestBehavior.AllowGet); } else { return Json(new { redirectionURL = "/Customer/Admin_Category", logDetails = logDetails }, JsonRequestBehavior.AllowGet); } } } } } } catch (Exception ex) { throw; } return Json(new { error = "Invalid Login Credentails. Please check your account or try forget password if your existing user. Else Contact to your Admin." }, JsonRequestBehavior.AllowGet); } public bool CompareHashValue(string pharse1, string pharse2, string OldHASHValue) { try { string expectedHashString = new Cipher().Encrypt((pharse1 + pharse2)); return (OldHASHValue == expectedHashString); } catch { return false; } } //GET: SignInAsync private void SignInRemember(string userName, bool isPersistent = false) { try { // Clear any lingering authencation data FormsAuthentication.SignOut(); // Write the authentication cookie FormsAuthentication.SetAuthCookie(userName, isPersistent); } catch (Exception) { throw; } } //GET: RedirectToLocal private ActionResult RedirectToLocal(string returnURL = "") { try { // If the return url starts with a slash "/" we assume it belongs to our site // so we will redirect to this "action" if (!string.IsNullOrWhiteSpace(returnURL) && Url.IsLocalUrl(returnURL)) return Redirect(returnURL); // If we cannot verify if the url is local to our host we redirect to a default location return RedirectToAction("loginAccess", "loginAccess"); } catch { throw; } } //POST: Logout [HttpGet] public ActionResult Logout() { try { // First we clean the authentication ticket like always //required NameSpace: using System.Web.Security; FormsAuthentication.SignOut(); // Second we clear the principal to ensure the user does not retain any authentication //required NameSpace: using System.Security.Principal; HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); Session.Clear(); System.Web.HttpContext.Current.Session.RemoveAll(); // Last we redirect to a controller/action that requires authentication to ensure a redirect takes place // this clears the Request.IsAuthenticated flag since this triggers a new request return RedirectToAction("Index"); } catch { throw; } } #endregion #region == Forget Password == // GET: Forgot Password public ActionResult forgetPassword() { return View(); } // POST: Forgot Password [HttpPost] public async Task<ActionResult> forgetPassword(ForgetPasswordModel _forgetPasswordModel) { var context = new MongoDataContext(); AdminMaster logDetails = await new GenericRepository<AdminMaster>(context).GetByCustomAsync(x => x.adEmail != null, "adEmail", _forgetPasswordModel.Email); if (logDetails != null) { Session["fpEmail"] = _forgetPasswordModel.Email; var OTP = new GenerateOTP().OTPGenerate(true, 6); Session["OtpCode"] = new Cipher().Encrypt(OTP + "&" + logDetails.adEmail); // new SMSsend().sendSMS(logDetails.adPhone, "Hi " + logDetails.adName + ", please find the OTP code : " + new GenerateOTP().OTPGenerate(true, 6)); return Json(new { obj = logDetails, otpCode = OTP }, JsonRequestBehavior.AllowGet); } return Json(new { error = "Email Doesn't match." }, JsonRequestBehavior.AllowGet); } [HttpPost] public async Task<ActionResult> VerifyOtp(ForgetPasswordModel _fPass) { try { if (!string.IsNullOrEmpty(_fPass.Otp) && !string.IsNullOrEmpty(Session["OtpCode"].ToString())) { if (Session["OtpCode"].ToString() == new Cipher().Encrypt(_fPass.Otp + "&" + Session["fpEmail"].ToString())) { var context = new MongoDataContext(); AdminMaster logDetails = await new GenericRepository<AdminMaster>(context).GetByCustomAsync(x => x.adEmail != null, "adEmail", Session["fpEmail"].ToString()); if (logDetails != null) { return Json(new { obj = logDetails }, JsonRequestBehavior.AllowGet); } } } } catch (Exception ex) { throw; } return Json(new { error = "Invalid OTP." }, JsonRequestBehavior.AllowGet); } [HttpPost] public async Task<ActionResult> PasswordReset(LoginModel _lgModel) { try { if (!string.IsNullOrEmpty(_lgModel.Password)) { var context = new MongoDataContext(); AdminMaster logDetails = await new GenericRepository<AdminMaster>(context).GetByCustomAsync(x => x.adEmail != null, "adEmail", Session["fpEmail"].ToString()); if(logDetails != null) { ObjectId _id = logDetails.Id; logDetails.adPassword = new Cipher().Encrypt(_lgModel.Password); logDetails.PasswordHashKey = new Cipher().Encrypt(Session["fpEmail"].ToString() + _lgModel.Password); await new GenericRepository<AdminMaster>(context).SaveAsync(logDetails); return Json(new { obj = string.Empty }, JsonRequestBehavior.AllowGet); } } } catch (Exception ex) { throw; } return Json(new { error = "Unable to change the password. Server ERROR." }, JsonRequestBehavior.AllowGet); } #endregion } }
using System.Collections; using System.Collections.Generic; using Game.Graphics.Effects; using UnityEngine; using UnityEngine.UI; namespace Game.Online.Notifications { public class NotificationPrefab : MonoBehaviour { public GameObject Type, NoficationText; [SerializeField] private Sprite Warning_sprite, Info_sprite; public AudioClip DeleteFX; public void NotificationSettings(string nofType, string nofText) { switch (nofType) { case "Warning": Type.GetComponent<Image>().sprite = Warning_sprite; break; case "Info": Type.GetComponent<Image>().sprite = Info_sprite; break; } NoficationText.GetComponent<Text>().text = nofText; } public void DeleteNotification() { Lerping Lerp = gameObject.AddComponent<Lerping>(); NotificationsCreator.Source.PlayOneShot(DeleteFX); StartCoroutine(Lerp.LerpAction(transform,0,1,0.5f)); } } }
using UnityEngine; using System.Collections; public class CarGenerator : GridGenerator<Car> { // Use this for initialization void Start () { generate(); } // Update is called once per frame void Update () { } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("TrackMouseMovement")] public class TrackMouseMovement : MonoBehaviour { public TrackMouseMovement(IntPtr address) : this(address, "TrackMouseMovement") { } public TrackMouseMovement(IntPtr address, string className) : base(address, className) { } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void Update() { base.method_8("Update", Array.Empty<object>()); } } }
using System; using System.Collections.Generic; using System.Text; namespace HackerRank_HomeCode { public class SuperReducedString { public void getSuperReducedString() { string s = Console.ReadLine(); var sb = new StringBuilder(); sb.Append(s[0]); for(int i = 1;i<s.Length;i++) { if(sb.Length >0 && s[i] == sb[sb.Length - 1]) { sb.Remove(sb.Length - 1, 1); } else { sb.Append(s[i]); } } if (sb.Length > 0) { Console.WriteLine(sb.ToString()); } else { Console.WriteLine("Empty String"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Idealize.VO { public class Questionario { [Required] [Display(Name = "Questionário")] public int idQuestionario { get; set; } [Required] [Display(Name = "Campanha")] public int idCampanha { get; set; } [Required] [Display(Name = "Nome")] public string nome { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace MB.Models.POCO { public class StaffMember { public StaffMember() { this.BookingInfos = new HashSet<BookingInfo>(); } public string Firstname { get; set; } public string Surname { get; set; } [Key, ForeignKey("UserInfo")] public string UserID { get; set; } public virtual ICollection<BookingInfo> BookingInfos { get; set; } public virtual UserInfo UserInfo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ToolsImages.Structures; namespace ToolsImages.Segmentation { public class UnionFind { #region Properties public SetList Sets { get; set; } public Vector Roots { get; set; } #endregion #region Constructors public UnionFind(SetList sets) { this.Sets = sets; this.Roots = new Vector(); this.Initialize(); this.Start(); } #endregion #region Methods public void Initialize() { //initialize Roots (add all items to Roots) Roots.Clear(); foreach (int index in Sets.Keys) { foreach (int item in Sets[index]) { if (!Roots.ContainsKey(item)) { Roots.Add(item, -1); } } } //assign root of each item as first-element of item's set foreach (int index in Sets.Keys) { foreach (int item in Sets[index]) { Roots[item] = Sets[index][0]; } } } public bool Find(int item1, int item2) { return Roots[item1] == Roots[item2]; } //to merge two sets containing item1 & item2, //set root of all items of item1's set to item2's root. public void Unite(int item1, int item2) { int item1Root = Roots[item1]; for (int index = 0; index < Roots.Count; index++) { int item = Roots.Keys.ElementAt(index); if (Roots[item] == item1Root) { Roots[item] = Roots[item2]; } } } public void Start() { foreach (int index in Sets.Keys) { var set = Sets[index]; for (int i = 0; i < set.Count; i++) { for (int j = i + 1; j < set.Count; j++) { Unite(set[i], set[j]); } } } } public override string ToString() { string result = string.Empty; foreach (int item in Roots.Keys) { result += item + ":" + Roots[item] + Environment.NewLine; } return result; } #endregion } }
using MvvmCross.Core.ViewModels; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EsMo.Sina.SDK.Model { public class MenuItemViewModel : MvxNotifyPropertyChanged { string text; public string Text { get { return text; } protected set { this.RaiseAndSetIfChanged(ref text, value, () => this.Text); } } public MenuType MenuType { get; private set; } Stream icon; public Stream Icon { get { return icon; } protected set { this.RaiseAndSetIfChanged(ref icon, value, () => this.Icon); } } public MenuItemViewModel(MenuType menuType, string iconPath = "") { if (!string.IsNullOrEmpty(iconPath)) { string path = iconPath.ToAssetsImage(); this.Icon = this.GetApplication().ResourceCache.Get(path); } this.MenuType = menuType; this.Text = this.MenuType.GetResourceString(); } } public enum MenuType { UserProfile, Home, Mention, Comment, SNS, Setting, Draft, Favorite, HotTopic, } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Obstacle : MonoBehaviour { private void OnCollisionEnter(Collision collision) { if (collision.collider.CompareTag("Player")) { collision.collider.GetComponent<PlayerMove>().PlayGameOver(); collision.collider.GetComponent<PlayerMove>().enabled = false ; collision.collider.GetComponent<Animator>().SetTrigger("Start"); FindObjectOfType<GameManager>().EndScreen(); } } }
using System.Threading.Tasks; namespace Micro.Net.Abstractions.Sagas { public interface ISagaFinder<TData> where TData : ISagaData { public interface IFor<TMessage> where TMessage : ISagaContract { Task<TData> Find(TMessage message, ISagaFinderContext context); } } public interface IDefaultSagaFinder { Task<TData> Find<TData, TMessage>(TMessage message, ISagaFinderContext context) where TMessage : ISagaContract; } public interface IDefaultSagaFinder<TData> { Task<TData> Find(ISagaContract message, ISagaFinderContext context); } }
using Modelos.Cadastros.Produtos; using Modelos.Formulas; using Modelos.SimulacaoLista; using SessionControl; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorys.Simulacao { public static class SimulacaoFactory { private static SqlConnection conecxao = SqlManagement.GetConnection(); private static IList<EstruturaProduto> MakeEstruturaByArray(string[,] array, string filial, string grupo) { double percentualFurmula; double custoMateriaPrima; IList<EstruturaProduto> estrutura = new List<EstruturaProduto>(); for (int i = 1; i < array.GetLength(0); i++) { try { percentualFurmula = Convert.ToDouble(array[i, 6].Replace('.', ',')); custoMateriaPrima = Convert.ToDouble(array[i, 7].Replace('.', ',')); } catch(Exception e) { percentualFurmula = 0; custoMateriaPrima = 0; Console.WriteLine(e.Message); } //so alimenta se tiver preechido o percentual da fórmula if (percentualFurmula>0) { estrutura.Add(new EstruturaProduto() { Filial = filial, Nivel = Convert.ToInt32(array[i, 1]), Produto = array[i, 2], Componente = array[i, 3], Tipo = array[i, 4], Unidade = array[i, 5], PercentualFormula = percentualFurmula, CustoMateriPrima = custoMateriaPrima, // CustoTotalComponente = Convert.ToDouble(array[i, 8]), CentroCustoComponente = GetCentroCustoByCod(array[i, 3], filial), CentroCustoProduto = GetCentroCustoByCod(array[i, 2], filial), DescricaoComponente = GetDescricaoByCod(array[i, 3], filial), DespesaOperacional = GetCustoOperacional(grupo, filial), Rendimento = 0, UltimoCustoMedio = 0, // CustoMedioUnitario = 0 }); } } return estrutura; } /// <summary> /// Cria um produto utilizando um retorno json /// </summary> /// <param name="json">The json.</param> /// <returns></returns> public static Produto MakeProdutoByJson(JsonSimulacao json) { Produto produto = new Produto(); produto.Estrutura = MakeEstruturaByArray(json.Estrutura, json.Filial, json.Familia); produto.CustoEmbalagem = json.CustoEmbalagem; produto.CustoEmbalagemPercent = json.CustoEmbalagemPercent; produto.CustoIndustrial = json.CustoIndustrial; produto.CustoOperacional = json.CustoOperacional; produto.CustoTotalDoProduto = json.CustoTotalDoProduto; produto.CustoTotalDoProdutoMargem = json.CustoTotalDoProdutoMargem; produto.Descricao = json.Descricao; produto.DescricaoCCusto = json.DescricaoCCusto; produto.DespesasOperacionais = json.DespesasOperacionais; produto.Familia = json.Familia; produto.Filial = json.Filial; produto.Formula = json.Formula; produto.Id = json.Id; produto.MargemLucro = json.MargemLucro; //produto.DespesasOperacionaisCalculada = json.DespesasOperacionaisCalculada; //produto.PrecoBase = json.PrecoBase; //produto.PrecoBaseIcm12 = json.PrecoBaseIcm12; //produto.PrecoBaseIcm18 = json.PrecoBaseIcm18; //produto.PrecoBaseIcm7 = json.PrecoBaseIcm7; produto.Rendimento = json.Rendimento; produto.CentroCusto = json.CentroCusto; produto.Codigo = json.Codigo; return produto; } /// <summary> /// Retorna a Descrição de um Produto cadastrado no SB1 /// </summary> /// <param name="codigo"></param> /// <param name="filial"></param> /// <returns></returns> private static string GetDescricaoByCod(string codigo, string filial) { using (SqlCommand command = conecxao.CreateCommand()) { string query = String.Format("SELECT B1_DESC " + " FROM SB1010 " + " WHERE " + " D_E_L_E_T_='' " + " AND B1_FILIAL='{0}' " + " AND B1_COD='{1}'", filial, codigo); command.CommandType = System.Data.CommandType.Text; command.CommandText = query; using (SqlDataReader leitor = command.ExecuteReader()) { leitor.Read(); if (leitor.HasRows) { return leitor["B1_DESC"].ToString(); } return ""; } } } /// <summary> /// retorna o Despesa Operacional de um grupo de Produto /// </summary> /// <param name="grupo"></param> /// <param name="filial"></param> /// <returns></returns> private static double GetCustoOperacional(string grupo, string filial) { using (SqlCommand command = conecxao.CreateCommand()) { string query = String.Format("SELECT ISNULL(Z07_CUSTO1,0) as Z07_CUSTO1 " + " FROM Z07010 " + " WHERE " + " Z07_GRUPO='{0}' " + " AND D_E_L_E_T_='' " + " and Z07_FILIAL='{1}'", grupo, filial); command.CommandType = System.Data.CommandType.Text; command.CommandText = query; using (SqlDataReader leitor = command.ExecuteReader()) { leitor.Read(); if (leitor.HasRows) { return Convert.ToDouble(leitor["Z07_CUSTO1"]); } return 0; } } } /// <summary> /// Retorna o Centro de Custo de um Produto cadastrado no SB1 /// </summary> /// <param name="codigo"></param> /// <param name="filial"></param> /// <returns></returns> private static string GetCentroCustoByCod(string codigo, string filial) { using (SqlCommand command = conecxao.CreateCommand()) { string query = String.Format("SELECT B1_CC " + " FROM SB1010 " + " WHERE " + " D_E_L_E_T_='' " + " AND B1_FILIAL='{0}' " + " AND B1_COD='{1}'", filial, codigo); command.CommandType = System.Data.CommandType.Text; command.CommandText = query; using (SqlDataReader leitor = command.ExecuteReader()) { leitor.Read(); if (leitor.HasRows) { return leitor["B1_CC"].ToString(); } return ""; } } } } }
using System; using System.Collections.Generic; using System.Linq; using SubSonic.Extensions; using System.Linq.Dynamic; namespace Pes.Core { public partial class StatusUpdate { public static StatusUpdate GetStatusUpdateByID(Int32 StatusUpdateID) { return StatusUpdate.Single(StatusUpdateID); } public static List<StatusUpdate> GetTopNStatusUpdatesByAccountID(Int32 AccountID, Int32 Number) { return StatusUpdate.GetTop(Number, "CreateDate descending", "AccountID=" + AccountID).ToList(); } public static List<StatusUpdate> GetStatusUpdatesByAccountID(Int32 AccountID) { IEnumerable<StatusUpdate> statusUpdates = from su in StatusUpdate.All() where su.AccountID == AccountID orderby su.CreateDate descending select su; return statusUpdates.ToList(); } public static void SaveStatusUpdate(StatusUpdate statusUpdate) { if (statusUpdate.StatusUpdateID > 0) { StatusUpdate.Update(statusUpdate); } else { statusUpdate.CreateDate = DateTime.Now; StatusUpdate.Add(statusUpdate); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stackoverflowpost { class Program { static void Main(string[] args) { try { var post = new Post("Test Post", "Test Description", DateTime.Now); Console.WriteLine($"Votes:{post.VoteCount}"); post.UpVote(); post.UpVote(); post.DownVote(); Console.WriteLine($"Votes:{post.VoteCount}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtonPressed : MonoBehaviour { public GameObject ObjectToDeactive; public GameObject ObjectToActivate; private void OnTriggerEnter(Collider other) { if(other.tag == "Button") { ObjectToDeactive.SetActive(false); ObjectToActivate.SetActive(true); } } }
using Calcifer.Engine.Graphics; using Calcifer.Engine.Graphics.Animation; namespace Calcifer.Engine.Scenegraph { public class AnimationNode: SceneNode { private AnimationComponent animation; public Pose Pose { get { return animation.Pose; } } public AnimationNode(SceneNode parent, AnimationComponent animation): base(parent) { this.animation = animation; } public override void AcceptPass(RenderPass pass) { pass.Visit(this); } } }
using System; using GalaSoft.MvvmLight.Helpers; using System.Collections.Generic; namespace Ts.Core.Extensions { public static class BindingExtension { public static void AttachTo(this Binding binding, List<Binding> bindings) { bindings?.Add (binding); } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace NMoSql.Helpers { public class EqualExpression : Helper, IConditionalHelper, IExpressionHelper { ExpressionBuilder _expressionBuilder; public EqualExpression(ExpressionBuilder expressionBuilder) { _expressionBuilder = expressionBuilder ?? throw new ArgumentNullException(nameof(expressionBuilder)); } public string Fn(string column, JToken expression, IList<object> values, ISet<string> tableAliases, JToken collection, JToken original) { if (string.IsNullOrWhiteSpace(column)) throw new ArgumentException(nameof(EqualExpression) + " expected " + nameof(column), nameof(column)); return column + " = " + _expressionBuilder.Build(expression, values); } } }
using Discord; using Discord.Commands; using System; namespace Bot { class MyBot { DiscordClient discord; CommandService commands; Random rand; string[] meme; public MyBot() { rand = new Random(); meme = new string[] { "mem/1.jpg", "mem/2.jpg", "mem/3.jpg", "mem/4.jpg", "mem/5.jpg", "mem/6.jpg", "mem/7.jpg", "mem/8.jpg", "mem/9.jpg", "mem/10.png", "mem/11.jpg", "mem/12.jpg", "mem/13.jpg", "mem/14.jpg", "mem/15.jpg", "mem/16.jpg", "mem/17.png", "mem/18.png", "mem/19.png", "mem/20.png", "mem/21.png", "mem/22.png", "mem/23.jpg", "mem/24.jpg", "mem/25.jpg", "mem/26.png", "mem/27.gif", "mem/28.jpg", "mem/29.jpg", "mem/30.png", "mem/31.jpg" }; discord = new DiscordClient(x => { x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); discord.UsingCommands(x => { x.PrefixChar = '!'; x.AllowMentionPrefix = true; }); commands = discord.GetService<CommandService>(); RegisterMemeCommand(); RegisterPurgeCommand(); commands.CreateCommand("Hello") .Do(async (e) => { await e.Channel.SendMessage("Why are you introducing your self to a bot."); }); RegisterMemeCommand(); discord.ExecuteAndWait(async () => { await discord.Connect("MzIyNzk5ODE2NjYyODQzMzkz.DFCHmg.OGmgLOaMJ_M5OF2MYOl529AX42E", TokenType.Bot); }); } private void RegisterMemeCommand() { commands.CreateCommand("post random meme") .Do(async (e) => { int randomMemeIndex = rand.Next(meme.Length); string memeToPost = meme[randomMemeIndex]; await e.Channel.SendFile(memeToPost); }); } private void RegisterPurgeCommand() { commands.CreateCommand("Purge") .Do(async (e) => { Message[] messagesToDelete; messagesToDelete = await e.Channel.DownloadMessages(100); await e.Channel.DeleteMessages(messagesToDelete); }); } private void Log(object sender, LogMessageEventArgs e) { Console.WriteLine(e.Message); } } }
using Crt.Data.Database; using Crt.Data.Repositories; using Crt.Domain.Services.Base; using Crt.Model; using Crt.Model.Dtos.FinTarget; using Crt.Model.Utils; using System.Collections.Generic; using System.Threading.Tasks; namespace Crt.Domain.Services { public interface IFinTargetService { Task<FinTargetDto> GetFinTargetByIdAsync(decimal finTargetId); Task<(decimal finTargetId, Dictionary<string, List<string>> errors)> CreateFinTargetAsync(FinTargetCreateDto finTarget); Task<(bool NotFound, Dictionary<string, List<string>> errors)> UpdateFinTargetAsync(FinTargetUpdateDto finTarget); Task<(bool NotFound, Dictionary<string, List<string>> errors)> DeleteFinTargetAsync(decimal projectId, decimal finTargetId); Task<(bool NotFound, decimal id)> CloneFinTargetAsync(decimal projectId, decimal finTargetId); } public class FinTargetService : CrtServiceBase, IFinTargetService { private IFinTargetRepository _finTargetRepo; private IUserRepository _userRepo; public FinTargetService(CrtCurrentUser currentUser, IFieldValidatorService validator, IUnitOfWork unitOfWork, IFinTargetRepository finTargetRepo, IUserRepository userRepo) : base(currentUser, validator, unitOfWork) { _finTargetRepo = finTargetRepo; _userRepo = userRepo; } public async Task<FinTargetDto> GetFinTargetByIdAsync(decimal finTargetId) { return await _finTargetRepo.GetFinTargetByIdAsync(finTargetId); } public async Task<(decimal finTargetId, Dictionary<string, List<string>> errors)> CreateFinTargetAsync(FinTargetCreateDto finTarget) { finTarget.TrimStringFields(); var errors = new Dictionary<string, List<string>>(); errors = _validator.Validate(Entities.FinTarget, finTarget, errors); await ValidateFinTarget(finTarget, errors); if (errors.Count > 0) { return (0, errors); } var crtFinTarget = await _finTargetRepo.CreateFinTargetAsync(finTarget); _unitOfWork.Commit(); return (crtFinTarget.FinTargetId, errors); } public async Task<(bool NotFound, Dictionary<string, List<string>> errors)> UpdateFinTargetAsync(FinTargetUpdateDto finTarget) { finTarget.TrimStringFields(); var crtFinTarget = await _finTargetRepo.GetFinTargetByIdAsync(finTarget.FinTargetId); if (crtFinTarget == null || crtFinTarget.ProjectId != finTarget.ProjectId) { return (true, null); } var errors = new Dictionary<string, List<string>>(); errors = _validator.Validate(Entities.FinTarget, finTarget, errors); await ValidateFinTarget(finTarget, errors); if (errors.Count > 0) { return (false, errors); } await _finTargetRepo.UpdateFinTargetAsync(finTarget); _unitOfWork.Commit(); return (false, errors); } public async Task<(bool NotFound, Dictionary<string, List<string>> errors)> DeleteFinTargetAsync(decimal projectId, decimal finTargetId) { var crtFinTarget = await _finTargetRepo.GetFinTargetByIdAsync(finTargetId); if (crtFinTarget == null || crtFinTarget.ProjectId != projectId) { return (true, null); } var errors = new Dictionary<string, List<string>>(); await _finTargetRepo.DeleteFinTargetAsync(finTargetId); _unitOfWork.Commit(); return (false, errors); } private async Task ValidateFinTarget(FinTargetSaveDto target, Dictionary<string, List<string>> errors) { if (!await _finTargetRepo.ElementExists(target.ElementId)) { errors.AddItem(Fields.ElementId, $"Element ID [{target.ElementId}] does not exists"); } } public async Task<(bool NotFound, decimal id)> CloneFinTargetAsync(decimal projectId, decimal finTargetId) { var crtFinTarget = await _finTargetRepo.GetFinTargetByIdAsync(finTargetId); if (crtFinTarget == null || crtFinTarget.ProjectId != projectId) { return (true, 0); } var finTarget = await _finTargetRepo.CloneFinTargetAsync(finTargetId); _unitOfWork.Commit(); return (false, finTarget.FinTargetId); } } }
using UnityEngine; using System.Collections; public class SimpleBullet : ProjectileBase { public float Lifetime = 1.0f; [RangeAttribute(0.0f,1.0f)] public float Inaccuracy = 0.0f; void Start() { transform.forward = (transform.forward + Random.insideUnitSphere * Random.Range(0.0f,Inaccuracy)).normalized; } // Update is called once per frame void Update () { transform.position += transform.forward * Time.fixedDeltaTime * Speed; Lifetime -= Time.fixedDeltaTime; if (Lifetime <= 0.0f) Destroy(gameObject); } }
namespace ModelAndroidAppSimples { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class Clientes { public int ID { get; set; } [StringLength(500)] public string Nome { get; set; } [StringLength(500)] public string Endereco { get; set; } [StringLength(500)] public string Bairro { get; set; } [StringLength(500)] public string Cidade { get; set; } [StringLength(10)] public string UF { get; set; } [StringLength(15)] public string Cep { get; set; } [StringLength(100)] public string Email { get; set; } [StringLength(20)] public string Telefone { get; set; } public int? IDCliente { get; set; } public int? IDVendedor { get; set; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("BoosterPackReward")] public class BoosterPackReward : Reward { public BoosterPackReward(IntPtr address) : this(address, "BoosterPackReward") { } public BoosterPackReward(IntPtr address, string className) : base(address, className) { } public void HideReward() { base.method_8("HideReward", Array.Empty<object>()); } public void InitData() { base.method_8("InitData", Array.Empty<object>()); } public void OnDataSet(bool updateVisuals) { object[] objArray1 = new object[] { updateVisuals }; base.method_8("OnDataSet", objArray1); } public void OnUnopenedPackPrefabLoaded(string name, GameObject go, object callbackData) { object[] objArray1 = new object[] { name, go, callbackData }; base.method_8("OnUnopenedPackPrefabLoaded", objArray1); } public void ShowReward(bool updateCacheValues) { object[] objArray1 = new object[] { updateCacheValues }; base.method_8("ShowReward", objArray1); } public void UpdatePackStacks() { base.method_8("UpdatePackStacks", Array.Empty<object>()); } public GameObject m_BoosterPackBone { get { return base.method_3<GameObject>("m_BoosterPackBone"); } } public GameLayer m_Layer { get { return base.method_2<GameLayer>("m_Layer"); } } public UnopenedPack m_unopenedPack { get { return base.method_3<UnopenedPack>("m_unopenedPack"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DuplicateChecker : MonoBehaviour { public bool isDuplicate(string[] names, string aName, int nameIndex){ for (int i = 0; i < nameIndex; i++) { if (aName == names [i]) { Debug.Log("Duplicate Found!"); return true; } } return false; } }
using UnityEditor.Timeline; namespace UnityUIPlayables.Editor { [CustomTimelineEditor(typeof(SliderAnimationClip))] public class SliderAnimationClipEditor : AnimationTimelineClipEditor<SliderAnimationBehaviour> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletController : MonoBehaviour { public float speed = 5.0f; public Camera originCamera; public int currentDungeonId = 0; private GunController parentGun; public string hitTag = ""; public float damage = 0f; public bool special = false; private Game _game = null; public bool isWarping = false; //public BulletController(GunController gun) { public void initParentGun(GunController gun) { parentGun = gun; } // Use this for initialization private void Start () { _game = GameObject.FindObjectOfType<Game>(); } // Update is called once per frame private void FixedUpdate () { transform.Translate(Vector3.forward * speed * Time.deltaTime); Vector3 viewPos = originCamera.WorldToViewportPoint(transform.position); if(viewPos.x < 0 || viewPos.x > 1 || viewPos.y < 0 || viewPos.y > 1) { if (special == false) { parentGun.DisableBullet (this); } else { DirectionEnum direction = _game.GetDirection(currentDungeonId, transform.position); if (isWarping == true && direction == DirectionEnum.NONE) { isWarping = false; } else if (isWarping == false && direction != DirectionEnum.NONE) { if (_game.IsAvailableDirection(currentDungeonId, direction) == true) { int dungeonId = _game.GetDungeonId(currentDungeonId, direction); Vector3 newPosition = _game.GetPosition(transform.position, direction, currentDungeonId, dungeonId); transform.position = newPosition; isWarping = true; } else { parentGun.DisableBullet(this); } } } } } private void OnTriggerEnter (Collider collider) { if (collider.gameObject.tag == hitTag) { if (hitTag == "monster") { if (parentGun.gunFrequency == collider.GetComponent<EnemyController> ().frequency) { collider.gameObject.GetComponent<EnemyController> ().HitByBullet (this); } } else if (hitTag == "player") collider.gameObject.GetComponent<PlayerController> ().Hit (damage); GameObject.Destroy (this.gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Photogf.Models; namespace Photogf.Controllers { public class AdminController : Controller { // GET: Admin public ActionResult Login() { return View(); } [Power] public ActionResult Index() { Entities dbHelper = new Entities(); var model = dbHelper.fileManager.FirstOrDefault(db => db.fileType == "0"); ViewBag.model = model; return View(); } [Power] public ActionResult AddItem() { return View(); } [Power] public ActionResult EditItem() { return View(); } [Power] public ActionResult EditItemType() { return View(); } [Power] public ActionResult fileList() { return View(); } [Power] public ActionResult fileUploadPage() { return View(); } [Power] public ActionResult ItemList() { return View(); } [Power] public ActionResult ProductType() { return View(); } [Power] public ActionResult AddItemType() { return View(); } [Power] public ActionResult NewsManager() { Entities dbHelper = new Entities(); var list = dbHelper.News.OrderByDescending(db => db.LastTime).ToList(); ViewBag.NewsList = list; return View(); } [Power] public ActionResult AddNews() { return View(); } [Power] public ActionResult EditNews(int id) { Entities dbHelper = new Entities(); var model = dbHelper.News.FirstOrDefault(db => db.id == id); if (model == null) RedirectToAction("NewsManager"); ViewBag.model = model; return View(); } [Power] public ActionResult ShowNews(int id) { Entities dbHelper = new Entities(); var model = dbHelper.News.FirstOrDefault(db => db.id == id); if (model == null) RedirectToAction("NewsManager"); ViewBag.model = model; return View(); } [Power] public ActionResult FrendLinkManage() { Entities dbHelper = new Entities(); List<frendLink> linkList = dbHelper.frendLink.OrderBy(db => db.Sort).ToList(); ViewBag.links = linkList; return View(); } [Power] public ActionResult ModifyPassword() { return View(); } } }
using System.Data.Entity; using LibrarySystem.Data; using LibrarySystem.Data.Migrations; namespace LibrarySystem { public class DatabaseConfig { public static void Initialize() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<LibrarySystemDbContext, Configuration>()); } } }
using Hybrid; using Hybrid.EventBus.Abstractions; using Microsoft.Extensions.DependencyInjection; using System; // ReSharper disable once CheckNamespace namespace Microsoft.AspNetCore.Builder { /// <summary> /// builder extensions for <see cref="IHybridBuilder" /> /// </summary> public static class RabbitMQBuilderExtensions { public static IApplicationBuilder UseRabbitMQ(this IHybridBuilder builder, Action<IEventBus> subscribeOption) { IApplicationBuilder app = builder.Builder; if (app == null) { throw new ArgumentNullException(nameof(app)); } var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>(); subscribeOption?.Invoke(eventBus); eventBus.StartSubscribe(); return app; //if (app == null) //{ // throw new ArgumentNullException(nameof(app)); //} //IServiceProvider provider = app.ApplicationServices; //var functionHandler = provider.GetServices<IHandlerTypeFinder>().ToList().Where(p => p.GetType() == typeof(IIntegrationEventHandler)).ToList(); //var eventBus = provider.GetRequiredService<IEventBus>(); //// todo: 向服务窗口注册所有IHandler类型 //var services = provider.GetService<IServiceCollection>(); //var handlerTypeFinder = // services.GetOrAddTypeFinder<HandlerTypeFinder>(assemblyFinder => new HandlerTypeFinder(assemblyFinder)); ////向服务窗口注册所有IHandler类型 //Type[] handlerTypes = handlerTypeFinder.FindAll(); //foreach (var handlerType in handlerTypes) //{ // Type handlerInterface = handlerType.GetInterface("IIntegrationEventHandler`1"); //获取该类实现的泛型接口 // if (handlerInterface == null) // { // continue; // } // Type eventDataType = handlerInterface.GetGenericArguments()[0]; //泛型的EventData类型 // var iEvent = handlerType.GetInterfaces().Where(x => x.IsGenericType).FirstOrDefault()?.GetGenericArguments().FirstOrDefault(); // if (iEvent != null) // { // eventBus.Subscribe < typeof(eventDataType), IIntegrationEventHandler <>> (); // } //} } } }
using System; using System.Collections.Generic; using ReadyGamerOne.Common; namespace ReadyGamerOne.MemorySystem { public interface IHotUpdatePath { string OriginMainManifest { get; } string LocalMainPath { get; } string WebServeMainPath { get; } string WebServeMainManifest { get; } string WebServeVersionPath { get; } string WebServeBundlePath { get; } string WebServeConfigPath { get; } Func<string,string> GetServeConfigPath { get; } Func<string,string,string> GetServeBundlePath { get; } Func<string,string,string> GetLocalBundlePath { get; } } #region IOriginAssetBundleUtil public interface IOriginAssetBundleUtil { Dictionary<string, string> KeyToName { get; } Dictionary<string, string> KeyToPath { get; } Dictionary<string,string> NameToPath { get; } } public class OriginBundleUtil<T>: Singleton<T>, IOriginAssetBundleUtil where T :OriginBundleUtil<T>,new() { public virtual Dictionary<string, string> KeyToName => null; public virtual Dictionary<string, string> KeyToPath => null; public virtual Dictionary<string, string> NameToPath => null; } #endregion #region IAssetConstUtil public class AssetConstUtil<T> : Singleton<T>, IAssetConstUtil where T :AssetConstUtil<T>, new() { public virtual Dictionary<string, string> NameToPath { get { throw new Exception("就不该走到这里"); } } } public interface IAssetConstUtil { Dictionary<string,string> NameToPath { get; } } #endregion public class OriginBundleKey { public const string Self = @"Self"; public const string Audio = @"Audio"; public const string File = @"File"; } }
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 System.Windows.Input; using System.Drawing.Drawing2D; namespace lab13 { public partial class Form1 : Form { byte ShowIcon; Point[] octagon; Point ImageCorner; Point CheckPoint,MousePoint; Region OctagonRegion; byte MouseClicked; int XDistance,YDistance; private void ShowGraphic() { graph.Image = new Bitmap(graph.Width, graph.Height); Graphics g = Graphics.FromImage(graph.Image); Image newImage; if(ShowIcon==1) newImage = Image.FromFile("image.ico"); else newImage = Image.FromFile("image.jpg"); Pen RedPen = new Pen(Color.Red, 3); g.DrawImage(newImage,ImageCorner); g.DrawPolygon(RedPen,octagon); } public Form1() { InitializeComponent(); ShowIcon=0; MouseClicked=0; int HalfX=graph.Width/2,HalfY=graph.Height/2; octagon=new Point[8]; octagon[0]=new Point(HalfX-50,HalfY+75); octagon[1]=new Point(HalfX-100,HalfY+25); octagon[2]=new Point(octagon[1].X,HalfY-25); octagon[3]=new Point(octagon[0].X,HalfY-75); octagon[4]=new Point(octagon[3].X+50,octagon[3].Y); octagon[5]=new Point(octagon[4].X+50,octagon[4].Y+50); octagon[6]=new Point(octagon[5].X,octagon[5].Y+50); octagon[7]=new Point(octagon[6].X-50,octagon[6].Y+50); ImageCorner=new Point(0, graph.Height-128); CheckPoint=new Point(0,0); MousePoint=new Point(Cursor.Position.X,Cursor.Position.Y); byte[] _type_vertex = new byte[8]; _type_vertex[0] = (byte)PathPointType.Start; for (int i=1; i<=_type_vertex.Length -1; i++) _type_vertex[i] = (byte)PathPointType.Line; OctagonRegion = new Region(new GraphicsPath(octagon, _type_vertex)); ShowGraphic(); } private void graph_MouseClick(object sender, MouseEventArgs e) { MousePoint.X=Cursor.Position.X; MousePoint.Y=Cursor.Position.Y; MousePoint=PointToClient(MousePoint); int x = MousePoint.X-12; int y = MousePoint.Y-12; if(MouseClicked==0) { if((x>=ImageCorner.X && y>=ImageCorner.Y) && (x<=ImageCorner.X+128 && y<=ImageCorner.Y+128)) { MouseClicked=1; XDistance=x-ImageCorner.X; YDistance=y-ImageCorner.Y; graph.MouseMove += MovePicture; } } else MouseClicked=0; } byte CheckImagePoint(int XStart, int XEnd, int YStart, int YEnd) { int i; for(i=XStart; i<XEnd; i++) { CheckPoint.X=i; CheckPoint.Y=YStart; if (OctagonRegion.IsVisible(CheckPoint)) return 1; } for(i=YStart; i<YEnd; i++) { CheckPoint.X=XStart; CheckPoint.Y=i; if (OctagonRegion.IsVisible(CheckPoint)) return 1; } return 0; } private void MovePicture(object sender, MouseEventArgs e) { if(MouseClicked==1) { MousePoint.X=Cursor.Position.X; MousePoint.Y=Cursor.Position.Y; MousePoint=PointToClient(MousePoint); ImageCorner.X=MousePoint.X-XDistance-12; ImageCorner.Y=MousePoint.Y-YDistance-12; CheckPoint.X=ImageCorner.X+128; CheckPoint.Y=ImageCorner.Y; if(CheckImagePoint(ImageCorner.X,ImageCorner.X+128,ImageCorner.Y,ImageCorner.Y)==0 && CheckImagePoint(ImageCorner.X+128,ImageCorner.X+128,ImageCorner.Y,ImageCorner.Y+128)==0 && CheckImagePoint(ImageCorner.X,ImageCorner.X+128,ImageCorner.Y+128,ImageCorner.Y+128)==0 && CheckImagePoint(ImageCorner.X,ImageCorner.X,ImageCorner.Y,ImageCorner.Y+128)==0) ShowGraphic(); } } private void graph_MouseDoubleClick(object sender, MouseEventArgs e) { MousePoint.X=Cursor.Position.X; MousePoint.Y=Cursor.Position.Y; MousePoint=PointToClient(MousePoint); int x = MousePoint.X-12; int y = MousePoint.Y-12; if((x>=ImageCorner.X && y>=ImageCorner.Y) && (x<=ImageCorner.X+128 && y<=ImageCorner.Y+128)) { if(ShowIcon==0) ShowIcon=1; else ShowIcon=0; ShowGraphic(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerCanvas : MonoBehaviour { [Header("Canvas Elements")] [SerializeField] private Text m_leftHelperText; [SerializeField] private Text m_rightHelperText; [SerializeField] private Text m_articleText; [SerializeField] private Text m_timerText; [SerializeField] private Image m_articleBackground; [SerializeField] private Image m_backgroundFade; [SerializeField] private Image m_blackScreen; [Header("Black screen variables")] [SerializeField] private float m_fadeTime = 1.0f; private void Awake() { m_leftHelperText.text = ""; m_rightHelperText.text = ""; m_timerText.text = ""; m_articleBackground.gameObject.SetActive(false); m_backgroundFade.gameObject.SetActive(false); } private void Start() { StartCoroutine(FadeBlackScreenOut()); } public void SetLeftHelperText(string _text) { m_leftHelperText.text = _text; } public void SetRightHelperText(string _text) { m_rightHelperText.text = _text; } public void StartReadingPaper(Text _textElement, Sprite _background = null) { m_articleBackground.gameObject.SetActive(true); m_backgroundFade.gameObject.SetActive(true); if (_background) m_articleBackground.sprite = _background; m_articleText.text = _textElement.text; m_articleText.font = _textElement.font; } public void StopReadingPaper() { m_articleBackground.gameObject.SetActive(false); m_backgroundFade.gameObject.SetActive(false); } public void StartViewingImage(Sprite _image) { m_articleText.text = ""; m_articleBackground.sprite = _image; m_articleBackground.gameObject.SetActive(true); m_backgroundFade.gameObject.SetActive(true); } public void OnPlayerDeath() { // Completely black m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, 1); StartCoroutine(PlayerDeathAnimation()); } public void InstantBlackScreen() { // Completely black m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, 1); } public void FadeOut() { StartCoroutine(FadeBlackScreenIn()); } public void FadeIn() { StartCoroutine(FadeBlackScreenOut()); } public void SetTimerText(string _text) { m_timerText.text = _text; } IEnumerator PlayerDeathAnimation() { yield return new WaitForSeconds(2); StartCoroutine(FadeBlackScreenOut()); } IEnumerator FadeBlackScreenIn() { m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, 0); while (m_blackScreen.color.a < 1) { m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, m_blackScreen.color.a + Time.deltaTime / m_fadeTime); yield return null; } m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, 1); yield return null; } IEnumerator FadeBlackScreenOut() { m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, 1); while (m_blackScreen.color.a > 0) { m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, m_blackScreen.color.a - Time.deltaTime / m_fadeTime); yield return null; } m_blackScreen.color = new Color(m_blackScreen.color.r, m_blackScreen.color.g, m_blackScreen.color.b, 0); yield return null; } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Rsk.AspNetCore.Authentication.Saml2p; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddAuthentication() .AddCookie("cookie") .AddSaml2p("saml2p", options => { options.Licensee = "/* your DEMO Licensee */"; options.LicenseKey = "/* your DEMO LicenseKey */"; options.IdentityProviderOptions = new IdpOptions { EntityId = "https://localhost:5000", SigningCertificates = new List<X509Certificate2> { new X509Certificate2("idsrv3test.cer") }, SingleSignOnEndpoint = new SamlEndpoint("https://localhost:5000/saml/sso", SamlBindingTypes.HttpRedirect), SingleLogoutEndpoint = new SamlEndpoint("https://localhost:5000/saml/slo", SamlBindingTypes.HttpRedirect), }; options.ServiceProviderOptions = new SpOptions { EntityId = "https://localhost:5001/saml", MetadataPath = "/saml/metadata", SignAuthenticationRequests = false }; options.NameIdClaimType = "sub"; options.CallbackPath = "/signin-saml"; options.SignInScheme = "cookie"; // IdP-Initiated SSO options.AllowIdpInitiatedSso = true; options.IdPInitiatedSsoCompletionPath = "/"; }); var app = builder.Build(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapDefaultControllerRoute(); app.Run();
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cognitive_Metier { public class ResultLanguageJson { public List<DocumentLanguageResult> documents { get; set; } public List<Error> errors { get; set; } } }
namespace UniversitySystem.Services.Models.Courses { using System; using System.ComponentModel.DataAnnotations; using System.Linq.Expressions; using UniversitySystem.Models; public class CourseDetailsResponseModel { public static Expression<Func<Course, CourseDetailsResponseModel>> FromModel { get { return c => new CourseDetailsResponseModel { Id = c.Id, Name = c.Name, Description = c.Description }; } } public int Id { get; set; } [Required] [MinLength(3)] [MaxLength(20)] public string Name { get; set; } [MaxLength(1000)] public string Description { get; set; } } }
using HCL.Academy.Model; using System; using System.Web.Mvc; using System.Net.Http; using System.Threading.Tasks; using HCLAcademy.Util; using Microsoft.ApplicationInsights; using System.Diagnostics; namespace HCLAcademy.Controllers { public class ProjectResourceController : BaseController { [Authorize] [SessionExpire] public async Task<ActionResult> ResourceDetails(int projectID) { try { //IDAL dal = (new DALFactory()).GetInstance(); //Resource prjRes = dal.GetResourceDetailsByProjectID(projectID); //Get the resource details of all Projects InitializeServiceClient(); UserProjectRequest userProjectInfo = new UserProjectRequest(); userProjectInfo.ProjectId = projectID; userProjectInfo.ClientInfo = req.ClientInfo; HttpResponseMessage trainingResponse = await client.PostAsJsonAsync("Project/GetResourceDetailsByProjectID", userProjectInfo); Resource prjRes = await trainingResponse.Content.ReadAsAsync<Resource>(); return View(prjRes); } catch (Exception ex) { //UserManager user = (UserManager)Session["CurrentUser"]; //LogHelper.AddLog("ProjectResourceController", ex.Message, ex.StackTrace, "HCL.Academy.Web", user.EmailID); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); return View(); } } } }
 namespace Client { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading; using RSA; using Stock; /// <summary> /// Handles communication between the client and the server. /// Makes sure that all traffic is encrypted. /// </summary> public class Communication { #region Constants and Fields private readonly AesManaged _aes = new AesManaged(); private readonly Dictionary<String, int> _investmentData = new Dictionary<string, int>(); private readonly Dictionary<String, List<StockDataPoint>> _publicStockData = new Dictionary<string, List<StockDataPoint>>(); private readonly Uri _serverUri = new Uri("http://127.0.0.1:80/", UriKind.Absolute); private readonly UTF8Encoding _utf8 = new UTF8Encoding(); private static Communication _instance; private Boolean _hasPublicKey = false; // Initialization vector for aes private byte[] _iv; private byte[] _keyFile; private String _lastErrorMessage = ""; private byte[] _publicKey = null; private List<String> _stockGroupNames = new List<string>(); private String _token = null; private Decimal _totalFunds = 0; private String _username = ""; // number of failed tries to connet to the server // Used for user output only. private uint tries = 0; #endregion #region Constructors and Destructors private Communication() { CreateLocalKeyFiles(); GetPublicKey(); } #endregion #region Public Properties /// <summary> /// The current instance of the Communication class i.e. the login session. /// </summary> public static Communication Instance { get { if (_instance == null) CreateNewInstance(); return _instance; } } /// <summary> /// Returns true if the current session has a token. /// </summary> public Boolean HasToken { get { return _token != null; } } /// <summary> /// Returns a list of available stock group names. /// </summary> public List<String> StockGroups { get { return _stockGroupNames; } } /// <summary> /// Gets the total funds on the users investment account. /// </summary> public Decimal TotalFunds { get { return _totalFunds; } } /// <summary> /// The name of the current logged in user. /// </summary> public String Username { get { return _username; } } #endregion #region Public Methods /// <summary> /// Closes the current session if it exists and creates a new. /// </summary> public static void CreateNewInstance() { Contract.Ensures(!ReferenceEquals(Instance, null)); Contract.Ensures(!Instance.HasToken); Contract.Ensures(Instance.StockGroups.Count == 0); Contract.Ensures(Instance.TotalFunds == 0); Contract.Ensures(Instance.Username.Equals("")); if (_instance != null && _instance.HasToken) { _instance.CloseConnection(); } _instance = new Communication(); } /// <summary> /// Close the connection to the server and reset all local private data. /// </summary> public void CloseConnection() { Contract.Ensures(!HasToken); Contract.Ensures(TotalFunds == 0); Contract.Ensures(Contract.ForAll(StockGroups, sg => Investments(sg) == 0)); GetResponseFromServer(CloseConnectionResponse, KfEncryptAndBase64("logout"), _token); _token = null; _totalFunds = 0; _stockGroupNames.ForEach(sg => _investmentData[sg] = 0); } /// <summary> /// The percentage invested in a specific stock group. /// </summary> /// <param name="stockGroup">The stock group for which information is wanted.</param> /// <returns>The investment percentage for the specified stock group.</returns> public int Investments(String stockGroup) { Contract.Requires(!ReferenceEquals(stockGroup, null)); Contract.Requires(Contract.Exists(StockGroups, name => name.Equals(stockGroup))); return _investmentData[stockGroup]; } /// <summary> /// Sends a login request to the server with the specified username and password. /// </summary> /// <param name="password">The password.</param> /// <param name="username">The username.</param> /// <returns>True if a key file exists for the specified username.</returns> public Boolean Login(String password, String username) { Contract.Requires(!ReferenceEquals(username, null)); Contract.Requires(!ReferenceEquals(password, null)); if (!_hasPublicKey) return false; Boolean canContinue = InitializeAES(username); if (!canContinue) { // username does not exist. return false; } CreateConnection(password, username, LoginResponse); _username = username; return true; } /// <summary> /// Sends a login request to the server with the current username and a specified password. /// </summary> /// <param name="password">The password.</param> public void Relogin(String password) { Contract.Requires(!ReferenceEquals(password, null)); CreateConnection(password, _username, ReloginResponse); } /// <summary> /// Gets a list of data points for a specific stock group. /// </summary> /// <param name="stockGroup">The stock group for which information is wanted.</param> /// <returns>A list of data points for the specified stock group.</returns> public List<StockDataPoint> StockGroupData(String stockGroup) { Contract.Requires(!ReferenceEquals(stockGroup, null)); Contract.Requires(Contract.Exists(StockGroups, name => name.Equals(stockGroup))); return _publicStockData[stockGroup]; } /// <summary> /// Saves a local copy of the investment data and sends a submit request to the server. /// </summary> /// <param name="data">The data to be submitted.</param> /// <returns>True if the data is correctly formatted.</returns> public Boolean SubmitData(Dictionary<String, int> data) { Contract.Requires(!ReferenceEquals(data, null)); Contract.Requires(data.Count == StockGroups.Count); Contract.Requires(Contract.ForAll(StockGroups, sg => data.ContainsKey(sg))); Contract.Requires(StockGroups.Sum(sg => data[sg]) <= 100); Contract.Requires(Contract.ForAll(StockGroups, sg => data[sg] >= 0)); Contract.Ensures(StockGroups.All(sg => data[sg] == Investments(sg))); if (!_stockGroupNames.All(sg => data.ContainsKey(sg)) || _stockGroupNames.Count != data.Count) { _lastErrorMessage = "error incomplete dataset"; return false; } _stockGroupNames.ForEach(sg => _investmentData[sg] = data[sg]); SubmitDataToServer(); return true; } #endregion #region Methods private void CloseConnectionResponse(String response) { if (response.Equals("goodbye") || response.Equals("error session expired")) { _lastErrorMessage = "Your session has been closed!"; } } /// <summary> /// Establishes a connection to the server, logs in, and receives a token. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <returns>True if the username is valid.</returns> private void CreateConnection(String password, String username, Action<String> loginAction) { Contract.Requires(!ReferenceEquals(password, null)); Contract.Requires(!ReferenceEquals(username, null)); SHA256Managed sha = new SHA256Managed(); String pass64 = Convert.ToBase64String(sha.ComputeHash(_utf8.GetBytes(password))); String data = PpEncryptAndBase64("login;" + username + ";" + pass64 + ";" + Convert.ToBase64String(_iv)); GetResponseFromServer(loginAction, data); } /// <summary> /// Create a key file in the local storage with the specified file name. /// </summary> /// <param name="filename">The name of the key file.</param> /// <param name="key">The key as a base64 string.</param> private void CreateKeyFile(String filename, String key) { Contract.Requires(!ReferenceEquals(key, null)); byte[] keyFileContents = Convert.FromBase64String(key); IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); if (!isf.FileExists(filename)) { IsolatedStorageFileStream isfs = isf.CreateFile(filename); isfs.Write(keyFileContents, 0, keyFileContents.Length); isfs.Flush(); isfs.Close(); } } /// <summary> /// Creates three local key files used for testing. /// </summary> private void CreateLocalKeyFiles() { CreateKeyFile("Jannek.key", "Phe6lq4EzTuZhp5W8K2/Om+3TSVVF13MbosJFFeasDY="); CreateKeyFile("Mathias.key", "z9YoC7PHB9uu8nDclQUJbmdr5/ENRtgnuu0nIvu55P4="); CreateKeyFile("AverageJoe.key", "1meHGoWzhqivcnZjp4E3aYGareuzvymJ/QBRxp/k4PU="); } /// <summary> /// Retrieve the server's public key. /// </summary> private void GetPublicKey() { GetResponseFromServer(PublicKeyResponse, "getpublickey"); } /// <summary> /// Sends a request to the server and executes a given delegate with the response as parameter. /// </summary> /// <param name="action">The delegate to be executed.</param> /// <param name="data">The request to be send to the server.</param> /// <param name="token">The current token if required for the request.</param> private void GetResponseFromServer(Action<String> action, String data, String token = "") { WebClient webClient = new WebClient(); // webClient.Headers["token"] = token; // webClient.Headers["data"] = data; // Add delegate method to the event handler webClient.UploadStringCompleted += ReceiveData; // Send login request to the server webClient.UploadStringAsync(_serverUri, "POST", "data=" + data + "&token=" + token, action); Console.WriteLine("Waiting..."); } /// <summary> /// Set the AES key and vector for the specified user. /// </summary> /// <param name="username">The username.</param> /// <returns>True if the username matches a existing key file.</returns> private Boolean InitializeAES(String username) { // Generate an initialization vector and save it. _aes.GenerateIV(); _iv = _aes.IV; String filename = username + ".key"; IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); // Read the local key file to _keyFile try { _keyFile = new byte[32]; IsolatedStorageFileStream fs = isf.OpenFile(filename, FileMode.Open, FileAccess.Read); fs.Read(_keyFile, 0, _keyFile.Length); } catch (IsolatedStorageException e) { // Username does not exist. return false; } return true; } /// <summary> /// Decrypts a previously encrypted string using the private key file. /// </summary> /// <param name="encrypted">The byte array to be decrypted.</param> /// <returns>The decrypted byte array.</returns> private String KfDecrypt(String encrypted) { Contract.Requires(!ReferenceEquals(encrypted, null)); ICryptoTransform aesDecryptor = _aes.CreateDecryptor(_keyFile, _iv); MemoryStream msDecrypt = new MemoryStream(); CryptoStream csDecrypt = new CryptoStream(msDecrypt, aesDecryptor, CryptoStreamMode.Write); try { byte[] encryptedBytes = Convert.FromBase64String(encrypted); csDecrypt.Write(encryptedBytes, 0, encryptedBytes.Length); csDecrypt.FlushFinalBlock(); byte[] data = msDecrypt.ToArray(); return _utf8.GetString(data, 0, data.Length); } catch (Exception) { return "error malformed response"; } } /// <summary> /// Decrypts a previously encrypted string using the private key file and splits the string. /// </summary> /// <param name="encrypted">The byte array to be decrypted.</param> /// <returns>The decrypted byte array as a string array.</returns> private String[] KfDecryptAndSplit(String encrypted) { Contract.Requires(!ReferenceEquals(encrypted, null)); return KfDecrypt(encrypted).Split(';'); } /// <summary> /// Encrypts a string using the private key file. /// </summary> /// <param name="s">The string to be encrypted.</param> /// <returns>The encrypted string as a byte array.</returns> private byte[] KfEncrypt(String s) { Contract.Requires(!ReferenceEquals(s, null)); byte[] data = _utf8.GetBytes(s); ICryptoTransform aesEncryptor = _aes.CreateEncryptor(_keyFile, _iv); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, aesEncryptor, CryptoStreamMode.Write); csEncrypt.Write(data, 0, data.Length); csEncrypt.FlushFinalBlock(); return msEncrypt.ToArray(); } /// <summary> /// Encrypts a string using the private key file and convert it to base64. /// </summary> /// <param name="s">The string to be encrypted.</param> /// <returns>The encrypted string in base64 format.</returns> private String KfEncryptAndBase64(String s) { Contract.Requires(!ReferenceEquals(s, null)); return Convert.ToBase64String(KfEncrypt(s)); } /// <summary> /// The delegate to be called when the server responds to a login request. /// </summary> /// <param name="response">The response frome the server.</param> private void LoginResponse(String response) { if (response.StartsWith("error")) { _token = null; _lastErrorMessage = response; if (_lastErrorMessage.Contains("password")) LoginScreen.Instance.Error("Wrong password!\rPlease retype and try again."); else LoginScreen.Instance.Error("Connection error!\rMake sure your phone is connected to the internet."); LoginScreen.Instance.MayLogin(); } else { _token = KfDecrypt(response); LoginScreen.Instance.SetStatusMessage("Logged in successfully!\rFetching public stock data.."); tries = 0; RequestPublicData(); } } /// <summary> /// Encrypts a string with the server's public key and convert it to base64. /// </summary> /// <param name="s">The string to be encrypted.</param> /// <returns>The encrypted string in base64 format.</returns> private String PpEncryptAndBase64(String s) { Contract.Requires(!ReferenceEquals(s, null)); RSACrypto rsa = new RSACrypto(); rsa.ImportCspBlob(_publicKey); byte[] sEncrypted = rsa.Encrypt(_utf8.GetBytes(s)); return Convert.ToBase64String(sEncrypted); } /// <summary> /// The delegate to be called when the server responds to a private investment data request. /// </summary> /// <param name="response">The response frome the server.</param> private void PrivateDataResponse(String response) { if (response.StartsWith("error")) { tries++; LoginScreen.Instance.Error("Download error!\r" + "Failed to download private investment data.\rIn " + tries + " tries."); RequestPrivateData(); return; } String[] reply = KfDecryptAndSplit(response); // Parse and save investment data. int i = 0; _totalFunds = Convert.ToDecimal(reply[i++]); while (i < reply.Length) { _investmentData.Add(reply[i++], Convert.ToInt32(reply[i++])); } LoginScreen.Instance.SetStatusMessage("Logged in successfully!\rReceived public stock data!\rReceived private investment data!"); LoginScreen.Instance.LoginComplete(); } /// <summary> /// The delegate to be called when the server responds to a public stock data request. /// </summary> /// <param name="response">The response frome the server.</param> private void PublicDataResponse(String response) { if (response.StartsWith("error")) { tries++; LoginScreen.Instance.Error("Download error!\r" + "Failed to download public stock data.In " + tries + " tries."); RequestPublicData(); return; } String[] reply = KfDecryptAndSplit(response); // Parse and save stock group data. int i = 0; while (i < reply.Length) { List<StockDataPoint> dataList = new List<StockDataPoint>(); String stockName = reply[i++]; int numberOfCoords = Convert.ToInt32(reply[i++]); for (int j = 0; j < numberOfCoords; j++) { dataList.Add(new StockDataPoint(Convert.ToUInt32(reply[i++]), Convert.ToInt64(reply[i++]))); } _stockGroupNames.Add(stockName); _publicStockData.Add(stockName, dataList); } LoginScreen.Instance.SetStatusMessage("Logged in successfully!\rReceived public stock data!\rFetching private investment data.."); tries = 0; RequestPrivateData(); } /// <summary> /// The delegate to be called when the server responds to a public key request. /// </summary> /// <param name="response">The response frome the server.</param> private void PublicKeyResponse(String response) { if (response.StartsWith("error")) { tries++; _hasPublicKey = false; LoginScreen.Instance.Error("Failed to fetch public key\rAfter " + tries + " tries"); GetPublicKey(); } else { _publicKey = Convert.FromBase64String(response); _hasPublicKey = true; LoginScreen.Instance.MayLogin(); } } /// <summary> /// The delegate to be called by any server request. /// </summary> /// <param name="args">Contains the response from the server and the delegate to call.</param> private void ReceiveData(object o, UploadStringCompletedEventArgs args) { Action<String> action = args.UserState as Action<String>; if (args.Error != null) { _lastErrorMessage = "error connection " + args.Error.ToString(); action(_lastErrorMessage); } else if (String.IsNullOrEmpty(args.Result)) { _lastErrorMessage = "error empty string"; action(_lastErrorMessage); } else if (args.Result.Equals("error session expired")) { _token = null; _lastErrorMessage = args.Result; action(_lastErrorMessage); } else if (args.Result.StartsWith("error")) { _lastErrorMessage = args.Result; action(_lastErrorMessage); } else { _lastErrorMessage = ""; action(args.Result); } } /// <summary> /// The delegate to be called when the server responds to a relogin request. /// </summary> /// <param name="response">The response frome the server.</param> private void ReloginResponse(String response) { if (response.StartsWith("error")) { _token = null; _lastErrorMessage = response; if (response.Contains("password")) ReloginScreen.Instance.Error("Wrong password!\rPlease retype and try again."); else ReloginScreen.Instance.Error("Connection error!\rMake sure your phone is connected to the internet."); } else { _token = KfDecrypt(response); ReloginScreen.Instance.ReloginComplete(); SubmitDataToServer(); } } /// <summary> /// Request the private investment data from the server. /// </summary> private void RequestPrivateData() { GetResponseFromServer(PrivateDataResponse, KfEncryptAndBase64("getinvestmentdata"), _token); } /// <summary> /// Requests the public stock data from the server. /// </summary> private void RequestPublicData() { GetResponseFromServer(PublicDataResponse, KfEncryptAndBase64("getstockdata"), _token); } /// <summary> /// Sends the local investment data to the server. /// </summary> private void SubmitDataToServer() { // Build the data string StringBuilder sbData = new StringBuilder(); sbData.Append("submitdata"); // Append all pairs to the request string foreach (KeyValuePair<string, int> pair in _investmentData) { sbData.AppendFormat(";{0};{1}", pair.Key, pair.Value); } GetResponseFromServer(SubmitResponse, KfEncryptAndBase64(sbData.ToString()), _token); } /// <summary> /// The delegate to be called when the server responds to a submit request. /// </summary> /// <param name="response">The response frome the server.</param> private void SubmitResponse(String response) { Contract.Requires(!ReferenceEquals(response, null)); InvestmentScreen.Instance.DataHasBeenSubmitted = KfDecrypt(response).Equals("done"); if (response.Contains("expired")) { InvestmentScreen.Instance.ReLogin(); } else if (response.StartsWith("error")) { InvestmentScreen.Instance.ConnectionError(); } InvestmentScreen.Instance.UpdateSynchronizedText(); } #endregion } }
namespace TimPhongTro.Migrations { using global::TimPhongTro.Common; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<global::TimPhongTro.Models.DatabaseContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(global::TimPhongTro.Models.DatabaseContext context) { context.TBADMINs.AddOrUpdate( new Models.TBADMIN() { Ten = "Văn Hoà", TaiKhoan = "vanhoa", Matkhau = StringHash.crypto("12345678") } ); } } }
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 CheckinUserResponse { public DateTime? LastRun; public Boolean AllocationStarted; public Boolean AllocationRunning; } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace NtApiDotNet.Win32.Security.Native { internal enum KERB_LOGON_SUBMIT_TYPE { KerbInteractiveLogon = 2, KerbSmartCardLogon = 6, KerbWorkstationUnlockLogon = 7, KerbSmartCardUnlockLogon = 8, KerbProxyLogon = 9, KerbTicketLogon = 10, KerbTicketUnlockLogon = 11, KerbS4ULogon = 12, KerbCertificateLogon = 13, KerbCertificateS4ULogon = 14, KerbCertificateUnlockLogon = 15, KerbNoElevationLogon = 83, KerbLuidLogon = 84, } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace VideoCtrl { internal class TcpCommunication : IDisposable { private TcpClient client; private char delimiter; private Stream stream; public TcpCommunication(string ipAddress, char messageDelimiter, int port = 5000) { this.client = new TcpClient(ipAddress, port); this.delimiter = messageDelimiter; this.stream = this.client.GetStream(); } public void Write(string message) { var writer = new StreamWriter(stream); writer.Write(message + this.delimiter); writer.Flush(); } public string Read() { var data = new char[20000]; int index = 0; var reader = new StreamReader(stream); do { reader.Read(data, index, 1); index++; } while (data[index - 1] != delimiter && index < data.Length); return new string(data, 0, index - 1); // do not return delimiter } /// <summary> /// Führt anwendungsspezifische Aufgaben aus, die mit dem Freigeben, Zurückgeben oder Zurücksetzen von nicht verwalteten Ressourcen zusammenhängen. /// </summary> public void Dispose() { if (this.client != null) { this.client.Close(); ((IDisposable) this.client).Dispose(); } if (this.stream != null) this.stream.Dispose(); } } }
using System; using System.Collections.Generic; using System.Text; namespace IndexArb.CommonModel { class FutureSPY : IIndexData { public DateTime Date { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public decimal Price { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public decimal Open { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public decimal High { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public decimal Low { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public long Volume { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public decimal PercentChange { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Linq; using System.Text; using System.Xml; namespace ITW.Config { public static class ConfigManager { public interface IParsable<T> { void FromString(string s); } /// <summary> /// Wrapper class of Win32API WritePrivateProfileString, GetPrivateProfileString. /// Must call Initialize() before use. /// </summary> [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string value, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder sb, int length, string filePath); private static Dictionary<string, Dictionary<string, string>> sections; private static string filePath; public const int MAX_LENGTH = 255; public static bool Initialize(string filePath) { if (System.IO.File.Exists(filePath) == false) { return false; } ConfigManager.filePath = Environment.CurrentDirectory + "\\" + filePath; return true; } public static bool Exists<T>(string section, string key) { StringBuilder sb = new StringBuilder(); GetPrivateProfileString(section, key, null, sb, MAX_LENGTH, filePath); return sb.ToString() == null; } public static int GetInt(string section, string key, int defaultValue = 0) { StringBuilder sb = new StringBuilder(); GetPrivateProfileString(section, key, defaultValue.ToString(), sb, MAX_LENGTH, filePath); return int.Parse(sb.ToString()); } public static float GetFloat(string section, string key, float defaultValue = 0f) { StringBuilder sb = new StringBuilder(); GetPrivateProfileString(section, key, defaultValue.ToString(), sb, MAX_LENGTH, filePath); return float.Parse(sb.ToString()); } public static string GetString(string section, string key, string defaultValue = "") { StringBuilder sb = new StringBuilder(); GetPrivateProfileString(section, key, defaultValue.ToString(), sb, MAX_LENGTH, filePath); return sb.ToString(); } /// <summary> /// Get value of T type. /// T must implement interface IParsable, and must have 0 argument constructor. /// </summary> public static T Get<T>(string section, string key, T defaultValue) where T : IParsable<T>, new() { StringBuilder sb = new StringBuilder(); GetPrivateProfileString(section, key, defaultValue.ToString(), sb, MAX_LENGTH, filePath); T t = new T(); t.FromString(sb.ToString()); return t; } public static void SetValue<T>(string section, string key, T value) { WritePrivateProfileString(section, key, value.ToString(), filePath); } } }
using System; using System.ComponentModel; using System.Windows.Input; namespace Caliburn.Light { /// <summary> /// Defines a command that can be data-bound. /// </summary> public abstract class BindableCommand : ICommand, INotifyPropertyChanged { private bool _isExecutableNeedsInvalidation = true; private bool _isExecutable; /// <summary> /// Occurs when changes occur that affect whether or not the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the CanExecuteChanged event. /// </summary> protected void OnCanExecuteChanged() { _isExecutableNeedsInvalidation = true; CanExecuteChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged(nameof(IsExecutable)); } /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the property that changed.</param> protected void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// The implementation of <see cref="ICommand.CanExecute(object)"/>. /// </summary> /// <param name="parameter">The parameter for the command.</param> /// <returns>true if this command can be executed; otherwise, false.</returns> protected virtual bool CanExecuteCore(object parameter) { return true; } /// <summary> /// Determines whether the command can execute in its current state. /// </summary> /// <param name="parameter">The parameter for the command.</param> /// <returns>true if this command can be executed; otherwise, false.</returns> public bool CanExecute(object parameter) { var result = CanExecuteCore(parameter); _isExecutable = result; _isExecutableNeedsInvalidation = false; return result; } /// <summary> /// Determines whether the command can execute in its current state. /// </summary> public bool IsExecutable { get { return (_isExecutableNeedsInvalidation) ? CanExecute(null) : _isExecutable; } } /// <summary> /// Called when the command is invoked. /// </summary> /// <param name="parameter">The parameter for the command.</param> public abstract void Execute(object parameter); /// <summary> /// Defines the method to be called when using x:Bind event binding. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="eventArgs">Event data for the event.</param> public void OnEvent(object sender, object eventArgs) { var parameter = DetermineParameter(sender, eventArgs); Execute(parameter); } private static object DetermineParameter(object sender, object eventArgs) { var resolvedParameter = ViewHelper.GetCommandParameter(sender); if (resolvedParameter is ISpecialValue specialValue) { var context = new CommandExecutionContext { Source = sender, EventArgs = eventArgs, }; resolvedParameter = specialValue.Resolve(context); } return resolvedParameter ?? eventArgs; } /// <summary> /// Raises <see cref="CanExecuteChanged"/> so every command invoker can re-query to check if the command can execute. /// </summary> /// <remarks>Note that this will trigger the execution of <see cref="CanExecute"/> once for each invoker.</remarks> public void RaiseCanExecuteChanged() { OnCanExecuteChanged(); } } }
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using TanoApp.Application.Interfaces; using TanoApp.Application.ViewModels.Common; using TanoApp.Data.Entities; using TanoApp.Data.IRepositories; using TanoApp.Infrastructure.Interfaces; using TeduCoreApp.Utilities.Dtos; namespace TanoApp.Application.Implementation { public class TagService : ITagService { private IMapper _mapper; private IUnitOfWork _unitOfWork; private ITagRepository _tagRepository; public TagService(ITagRepository tagRepository, IMapper mapper, IUnitOfWork unitOfWork) { _tagRepository = tagRepository; _mapper = mapper; _unitOfWork = unitOfWork; } public TagViewModel Add(TagViewModel tag) { _tagRepository.Add(_mapper.Map<TagViewModel, Tag>(tag)); return tag; } public void Delete(string id) { _tagRepository.Remove(id); } public PagedResult<TagViewModel> GetAllPaging(string keyword, int page, int pageSize) { var query = _tagRepository.FindAll(); if (!string.IsNullOrEmpty(keyword)) { query = query.Where(x => x.Name.Contains(keyword)); } int totalRow = query.Count(); query = query.OrderByDescending(x => x.Id).Skip((page - 1) * pageSize).Take(pageSize); var tags = query.ToList(); var data = _mapper.Map<List<Tag>, List<TagViewModel>>(tags); var paginationSet = new PagedResult<TagViewModel>() { Results = data, CurrentPage = page, RowCount = totalRow, PageSize = pageSize }; return paginationSet; } public TagViewModel GetById(string id) { var tags = _tagRepository.FindById(id); return _mapper.Map<Tag, TagViewModel>(tags); } public List<TagViewModel> GetListTag() { var tags = _tagRepository.FindAll().ToList(); return _mapper.Map<List<Tag>, List<TagViewModel>>(tags); } public void Save() { _unitOfWork.Commit(); } public void Update(TagViewModel tag) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MZcms.Core { public class ObjectContainer { private static ObjectContainer current; private static IinjectContainer container; public static void ApplicationStart( IinjectContainer c ) { container = c; current = new ObjectContainer( container ); } public static ObjectContainer Current { get { if( current == null ) { ApplicationStart( container ); } return current; } } protected IinjectContainer Container { get; set; } protected ObjectContainer() { Container = new DefaultContainerForDictionary(); } protected ObjectContainer( IinjectContainer inversion ) { Container = inversion; } public void RegisterType<T>() { Container.RegisterType<T>(); } public T Resolve<T>() { return Container.Resolve<T>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class BoolParameter : Parameter { public List<bool> IntensityDefault { get; set; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Spotzer.Model.Enums { public class OrderConstants { public const string PartnerAMissingWebsite = "Partner A's order should include at least one website product!"; public const string PartnerAIncludePaidProduct = "Partner A can not sell paid products!"; public const string PartnerDMissingPaidProduct = "Partner D's order should include at least one paid product!"; public const string PartnerDIncludeWebsite = "Partner D can not sell websites!"; public const string PartnerBandDCantHaveAdditionalInfo = "Partner B and D can not have additional info!"; public const string PartnerAandCHaveAdditionalInfo = "Partner A and C have to include additional info!"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TimeLineSystem; using System.Data; using System; using System.Reflection; using NetSystem; namespace ResourceSystem { /// <summary> /// 资源管理 /// </summary> public class ResourceSystemFacade : Singleton<ResourceSystemFacade> { public bool IsAB { get; private set; } public bool IsInit { get; private set; } public Dictionary<string, ResourcesData> ResDict = new Dictionary<string, ResourcesData>(); public List<string> LoadedRes = new List<string>(); public static string AbOutPath = Application.dataPath+"/../../AssetBundles/Windows"; public static string FileExtension = "assetbundle"; public bool InitSystem(bool isAb = true) { DisposeSystem(); IsAB = isAb; ResourcesInfo info = Resources.Load<ResourcesInfo>("ScriptableObject/ResourcesInfo"); for (int i = 0; i < info.Data.Count; i++) { ResDict.Add(info.Data[i].Name, info.Data[i]); } IsInit = true; return ResDict.Count > 0; } public void DisposeSystem() { IsInit = false; ResDict.Clear(); } #region Get public string GetTargetResIDByPath(string path) { return ""; } public string GetTargetVersionByResID(string path) { return ""; } #endregion #region Excel读写 public void WriteToExcel(string path ,string sheetName,string[,] content) { ExcelStream stream = new ExcelStream(); ExcelWriteArgs args = new ExcelWriteArgs(); args.Path = path; args.SheetName = sheetName; args.Content = content; stream.WriteResource(args); } public List<IDataTemplete> ReadExcel(Type type,string path,int sheetIndex=0) { ConstructorInfo[] infos= type.GetConstructors(); int index = -1; for(int i = 0; i < infos.Length; i++) { if (infos[i].GetParameters().Length == 0) { index = i; } } List<IDataTemplete> data = new List<IDataTemplete>(); if (index != -1) { ExcelStream stream = new ExcelStream(); DataTableCollection collection = (DataTableCollection)stream.ReadResouce(path); for (int i = 3; i < collection[sheetIndex].Rows.Count; i++) { IDataTemplete temp =(IDataTemplete)infos[index].Invoke(new object[] { }); temp.DeSerialize(collection[sheetIndex].Rows[i].ItemArray); data.Add(temp); } } return data; } public DataTableCollection ReadExcel(string path) { ExcelStream stream = new ExcelStream(); return (DataTableCollection)stream.ReadResouce(path); } #endregion #region 资源加载 public void DownLoadResourcesAndSave(string relativePath) { string path = NetSystemFacade.ResourceURL + "/" + relativePath+"."+ FileExtension; AssetBundleStream abStream = new AssetBundleStream(); abStream.OnLoadFinish += () => { AssetBundleWriteArgs args = new AssetBundleWriteArgs(); args.Bytes = abStream.Bytes; args.Path = path; abStream.WriteResource(args); }; abStream.ReadResouce(path); } /// <summary> /// /// </summary> /// <param name="resName"></param> /// <returns></returns> public object LoadResource(string resName) { object resObj = null; if (ResDict.ContainsKey(resName)) { resObj = Resources.Load(ResDict[resName].Path + ResDict[resName].Name); } return resObj; } public AssetBundleStream LoadResourceFromAB(string resName, Action onLoadFinish = null) { AssetBundleStream abStream= new AssetBundleStream(); abStream.OnLoadFinish += onLoadFinish; if (ResDict.ContainsKey(resName)) { string path = NetSystemFacade.ResourceURL + "/"+ resName+"."+FileExtension; for (int i = 0; i < ResDict[resName].Dependencys.Count; i++) { AssetBundleStream abChildStream = LoadResourceFromAB(ResDict[resName].Dependencys[i]); abChildStream.OnLoadFinish += () => { bool isLoaded=true; LoadedRes.Add(PathUtils.GetFileNameWithoutExtension(abChildStream.Bundle.name)); DebugUtils.DebugRedInfo(abChildStream.Bundle.name); for (int j = 0; j < ResDict[resName].Dependencys.Count; j++) { if (!LoadedRes.Contains(ResDict[resName].Dependencys[j])) { DebugUtils.DebugRedInfo(ResDict[resName].Dependencys[j]); isLoaded = false; } } if (isLoaded) { abStream.ReadResouce(path); } }; string chidResName = ResDict[resName].Dependencys[i]; DebugUtils.DebugRedInfo(chidResName); if (ResDict.ContainsKey(chidResName)) { string childPath = NetSystemFacade.ResourceURL + "/" + chidResName+"."+FileExtension; abChildStream.ReadResouce(childPath); } } } return abStream; } #endregion #region 卸载资源 public bool UnLoadResource() { return true; } #endregion } }
using UnityEngine; namespace ACO.Net.Protocol { public class Connector : MonoBehaviour { } }
#region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using StreakerLibrary; using Microsoft.Xna.Framework.Graphics; #endregion namespace COMP476Proj { public enum PedestrianState { STATIC, WANDER, FLEE, PATH, FALL, GET_UP }; public enum PedestrianBehavior { DEFAULT, AWARE, KNOCKEDUP }; public class Pedestrian : NPC { #region Attributes private bool canSee = false; private bool canReach = false; /// <summary> /// Direction the character is moving /// </summary> private PedestrianState state; private PedestrianBehavior behavior; private string studentType; private int fleePointsTime = 500; private const int fleePointsTimeout = 1000; private bool fleePoints = false; public PedestrianState State { get { return state; } } #endregion #region Constructors public Pedestrian(PhysicsComponent2D phys, MovementAIComponent2D move, DrawComponent draw, PedestrianState pState) { movement = move; physics = phys; this.draw = draw; state = pState; behavior = PedestrianBehavior.DEFAULT; studentType = draw.animation.animationId.Substring(0, 8); this.BoundingRectangle = new COMP476Proj.BoundingRectangle(phys.Position, 16, 6); draw.Play(); } public Pedestrian(PhysicsComponent2D phys, MovementAIComponent2D move, DrawComponent draw, PedestrianState pState, float radius) { movement = move; physics = phys; this.draw = draw; state = pState; behavior = PedestrianBehavior.DEFAULT; detectRadius = radius; studentType = draw.animation.animationId.Substring(0, 8); this.BoundingRectangle = new COMP476Proj.BoundingRectangle(phys.Position, 16, 6); draw.Play(); } #endregion #region Private Methods private void transitionToState(PedestrianState pState) { switch (pState) { case PedestrianState.STATIC: state = PedestrianState.STATIC; draw.animation = SpriteDatabase.GetAnimation(studentType + "_static"); physics.SetSpeed(false); physics.SetAcceleration(false); draw.Reset(); break; case PedestrianState.WANDER: state = PedestrianState.WANDER; draw.animation = SpriteDatabase.GetAnimation(studentType + "_walk"); physics.SetSpeed(false); physics.SetAcceleration(false); draw.Reset(); break; case PedestrianState.FLEE: state = PedestrianState.FLEE; draw.animation = SpriteDatabase.GetAnimation(studentType + "_flee"); physics.SetSpeed(true); physics.SetAcceleration(true); draw.Reset(); break; case PedestrianState.FALL: state = PedestrianState.FALL; draw.animation = SpriteDatabase.GetAnimation(studentType + "_fall"); physics.SetSpeed(false); physics.SetAcceleration(false); draw.Reset(); break; case PedestrianState.GET_UP: state = PedestrianState.GET_UP; draw.animation = SpriteDatabase.GetAnimation(studentType + "_getup"); physics.SetSpeed(false); physics.SetAcceleration(false); draw.Reset(); break; case PedestrianState.PATH: state = PedestrianState.PATH; draw.animation = SpriteDatabase.GetAnimation(studentType + "_walk"); physics.SetSpeed(false); physics.SetAcceleration(false); draw.Reset(); break; } } private void updateState(World w) { IsVisible(Game1.world.streaker.Position, out canSee, out canReach); fleePoints = false; //-------------------------------------------------------------------------- // DEFAULT BEHAVIOR TRANSITIONS --> Before aware of streaker //-------------------------------------------------------------------------- if (behavior == PedestrianBehavior.DEFAULT) { if (Vector2.Distance(w.streaker.Position, pos) < detectRadius && canSee) { playSound("Exclamation"); behavior = PedestrianBehavior.AWARE; transitionToState(PedestrianState.FLEE); } } //-------------------------------------------------------------------------- // AWARE BEHAVIOR TRANSITION --> Knows about streaker //-------------------------------------------------------------------------- else if (behavior == PedestrianBehavior.AWARE) { if (Vector2.Distance(w.streaker.Position, pos) < detectRadius && canSee) fleePoints = true; else fleePoints = false; if (Vector2.Distance(w.streaker.Position, pos) > detectRadius) { behavior = PedestrianBehavior.DEFAULT; transitionToState(PedestrianState.WANDER); } } //-------------------------------------------------------------------------- // COLLIDE BEHAVIOR TRANSITION //-------------------------------------------------------------------------- else if (behavior == PedestrianBehavior.KNOCKEDUP) { switch (state) { case PedestrianState.FALL: if (draw.animComplete) { SoundManager.GetInstance().PlaySound("Common", "Fall", w.streaker.Position, Position); transitionToState(PedestrianState.GET_UP); } break; case PedestrianState.GET_UP: if (draw.animComplete && Vector2.Distance(w.streaker.Position, pos) < detectRadius) { behavior = PedestrianBehavior.AWARE; transitionToState(PedestrianState.FLEE); } else if (draw.animComplete && Vector2.Distance(w.streaker.Position, pos) >= detectRadius) { behavior = PedestrianBehavior.DEFAULT; transitionToState(PedestrianState.WANDER); } break; } } //-------------------------------------------------------------------------- // CHAR STATE --> ACTION //-------------------------------------------------------------------------- switch (state) { case PedestrianState.STATIC: movement.Stop(ref physics); break; case PedestrianState.WANDER: movement.Wander(ref physics); break; case PedestrianState.FLEE: movement.SetTarget(w.streaker.ComponentPhysics.Position); movement.Flee(ref physics); break; case PedestrianState.PATH: //TO DO break; case PedestrianState.FALL: movement.Stop(ref physics); break; case PedestrianState.GET_UP: movement.Stop(ref physics); break; default: break; } if (!fleePoints) fleePointsTime = 500; } private void playSound(string soundName) { if (studentType == "student1") { SoundManager.GetInstance().PlaySound("WhiteBoy", soundName, Game1.world.streaker.Position, Position); } else if (studentType == "student2") { SoundManager.GetInstance().PlaySound("BlackBoy", soundName, Game1.world.streaker.Position, Position); } else if (studentType == "student3") { SoundManager.GetInstance().PlaySound("Girl", soundName, Game1.world.streaker.Position, Position); } } #endregion #region Public Methods /// <summary> /// Update /// </summary> public void Update(GameTime gameTime, World w) { pos = physics.Position; updateState(w); movement.Look(ref physics); physics.UpdatePosition(gameTime.ElapsedGameTime.TotalSeconds, out pos); physics.UpdateOrientation(gameTime.ElapsedGameTime.TotalSeconds); if (physics.Orientation > 0) { draw.SpriteEffect = SpriteEffects.None; } else if (physics.Orientation < 0) { draw.SpriteEffect = SpriteEffects.FlipHorizontally; } draw.Update(gameTime); if (draw.animComplete && (state == PedestrianState.FALL || state == PedestrianState.GET_UP)) { draw.GoToPrevFrame(); } if (fleePoints) { fleePointsTime += gameTime.ElapsedGameTime.Milliseconds; if (fleePointsTime >= fleePointsTimeout) { fleePointsTime = 0; DataManager.GetInstance().IncreaseScore(DataManager.Points.FleeProximity, true, physics.Position.X, physics.Position.Y - 64); } } base.Update(gameTime); } public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) { draw.Draw(gameTime, spriteBatch, physics.Position); base.Draw(gameTime, spriteBatch); } public override void Fall(bool isSuperFlash) { behavior = PedestrianBehavior.KNOCKEDUP; if (state != PedestrianState.FALL) { if (isSuperFlash) { playSound("SuperFlash"); } transitionToState(PedestrianState.FALL); } movement.Stop(ref physics); } #endregion } }
using System; using System.Threading; using System.Threading.Tasks; namespace Shared { public class ConsoleRunner { public static int Run(Func<Task> task) { using (var source = new CancellationTokenSource()) { Console.CancelKeyPress += (s, a) => source.Cancel(); try { task().Wait(source.Token); return 0; } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e); Console.ResetColor(); return -1; } finally { Console.WriteLine("Bye!"); } } } } }
/// <copyright> /// Copyright © Microsoft Corporation 2014. All rights reserved. Microsoft CONFIDENTIAL /// </copyright> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Linq.Expressions; using Common.Extensions; using Common.ObjectHistory; using Common.Wpf.View; using System.Collections; using System.Collections.Specialized; namespace Common.Wpf.ViewModel { [Serializable] public partial class ViewModelBase : INotifyPropertyChanged, IDisposable { public ViewModelBase() { } public IView View { get; set; } #region INotifyPropertyChanged Implementation public void ChangeAndNotify<T>(ref T field, T value, Expression<Func<T>> memberExpression) { PropertyChanged.ChangeAndNotify<T>(this, ref field, value, memberExpression); Dirty = true; } public void ChangeAndNotifyHistory<T>(HistoryableProperty<T> field, T value, Expression<Func<T>> memberExpression) { PropertyChanged.ChangeAndNotifyHistory<T>(this, field, value, memberExpression); Dirty = true; } public void Notify<T>(Expression<Func<T>> memberExpression) { PropertyChanged.Notify<T>(this, memberExpression); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region Dirty private bool dirty = false; public virtual bool Dirty { get { return dirty; } set { if (dirty != value) { dirty = value; Notify<bool>(() => Dirty); if (value) { var p = GetParent(); if (p != null) { p.Dirty = true; } } } } } #endregion #region IDisposable Implemenation private bool disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!disposed) { if (disposing) { ReleaseManagedResource(); } ReleaseUnManagedResource(); disposed = true; } } protected virtual void ReleaseManagedResource() { } protected virtual void ReleaseUnManagedResource() { } ~ViewModelBase() { Dispose(false); } #endregion #region Initialize public virtual void Initialize() { InitializeResource(); InitializeCommand(); } protected virtual void InitializeResource() { } protected virtual void InitializeCommand() { } #endregion #region Operation public virtual void Save() { Dirty = false; } public virtual void Reset() { Dirty = false; } public ViewModelBase GetTopLevelParent() { var p = GetParent(); if (p == null) { return this; } else { return p.GetTopLevelParent(); } } public virtual ViewModelBase GetParent() { return null; } #endregion public void DispatcherInvoker(Action act, bool async = false) { //var disp = System.Windows.Threading.Dispatcher.CurrentDispatcher; var disp = System.Windows.Application.Current.Dispatcher; if (disp != null) { if (async) { disp.BeginInvoke((Action)(() => act())); } else { disp.Invoke((Action)(() => act())); } } else { act(); } } } }
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Lib.Net.Http.WebPush; using Services.Abstractions; namespace Services { internal class PushNotificationsQueue : IPushNotificationsQueue { private readonly ConcurrentQueue<PushMessageWithTeam> _messages = new ConcurrentQueue<PushMessageWithTeam>(); private readonly SemaphoreSlim _messageEnqueuedSignal = new SemaphoreSlim(0); public void Enqueue(PushMessageWithTeam message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } _messages.Enqueue(message); _messageEnqueuedSignal.Release(); } public async Task<PushMessageWithTeam> DequeueAsync(CancellationToken cancellationToken) { await _messageEnqueuedSignal.WaitAsync(cancellationToken); _messages.TryDequeue(out PushMessageWithTeam message); return message; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Juego_v3 { interface ILogica { int comprobar(string jugada1, string jugada2); string[] validas(); } }
// // Copyright 2012 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.Linq; using Carbonfrost.Commons.PropertyTrees; using Carbonfrost.Commons.PropertyTrees.Schema; using Carbonfrost.Commons.Core.Runtime; using Carbonfrost.Commons.Spec; namespace Carbonfrost.UnitTests.PropertyTrees { // TODO test sourcing, test pt:property, // test circular refs (#), test type converters, // test whitespace handling (never trim from attributes) public class ComponentModelIntegrationTests { [Fact] public void should_provide_streaming_source_using_file_extensions() { Assert.IsInstanceOf<PropertyTreeSource>(StreamingSource.Create(typeof(object), (ContentType) null, ".pt")); Assert.IsInstanceOf<PropertyTreeSource>(StreamingSource.Create(typeof(object), (ContentType) null, ".ptx")); } [Fact] public void should_provide_streaming_source_using_content_type() { Assert.IsInstanceOf<PropertyTreeSource>(StreamingSource.Create(typeof(object), ContentType.Parse(ContentTypes.PropertyTrees))); } [Fact] public void should_provide_xmlns() { Assert.Equal(Xmlns.PropertyTrees2010, typeof(PropertyTree).GetQualifiedName().NamespaceName); Assert.Equal(Xmlns.PropertyTreesSchema2010, typeof(PropertyTreeDefinition).GetQualifiedName().NamespaceName); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Activator : MonoBehaviour { public GameObject[] activateOnStart; // On Awake the gameobjects clear, cloudy, and rainy are set active. void Awake() { foreach (GameObject go in activateOnStart) { go.SetActive(true); } } }