text
stringlengths
13
6.01M
 namespace Arch.Data.Common.Vi { class BeanProxy : IBeanProxy { public void Register() { AbstractDALBean.Register(); AbstractHABean.Register(); AbstractMarkDownBean.Register(); AbstractTimeoutMarkDownBean.Register(); } public IDALBean GetDALBean() { return AbstractDALBean.GetInstance(); } public IHABean GetHABean() { return AbstractHABean.GetInstance(); } public IMarkDownBean GetMarkDownBean() { return AbstractMarkDownBean.GetInstance(); } public ITimeoutMarkDownBean GetTimeoutBean() { return AbstractTimeoutMarkDownBean.GetInstance(); } } }
using System; using ApplicationCore.Interfaces; using System.Collections.Generic; //using ApplicationCore.Entities.DoctorAggregate; namespace ApplicationCore.Entities.DoctorAggregate { public class Doctor : IAggregateRoot { public string DoctorId{get; set;} public string DoctorName{get; set;} public Gender Gender{get; set;} public string Phone{get; set;} // private List<DocAppointment> _appointment = new List<DocAppointment>(); // IEnumerable<DocAppointment> appointment => _appointment.AsReadOnly(); public Doctor(){} public Doctor(string id, string name, Gender gender, string phone) { this.DoctorId = id; this.DoctorName = name; this.Gender = gender; this.Phone = phone; } } }
namespace Requestrr.WebApi.RequestrrBot.DownloadClients.Overseerr { public class OverseerrTestSettings { public string Hostname { get; set; } = string.Empty; public int Port { get; set; } = 5055; public bool UseSSL { get; set; } = false; public string ApiKey { get; set; } = string.Empty; public string DefaultApiUserId { get; set; } public string Version { get; set; } = "1"; } }
using System; namespace NLuaTest.Mock { public class TestClassWithOverloadedMethod { public int CallsToStringFunc { get; set; } public int CallsToIntFunc { get; set; } public void Func(string param) { this.CallsToStringFunc++; } public void Func(int param) { this.CallsToIntFunc++; } } }
using Microsoft.AspNet.Identity.EntityFramework; using MyCashFlow.Domains.DataObject; using MyCashFlow.Domains.Identity; using MyCashFlow.Identity.Context; namespace MyCashFlow.Identity.Stores { public class CustomUserStore : UserStore<User, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim> { public CustomUserStore(ApplicationDbContext context) : base(context) { } } }
using UnityEngine; using System.Collections; public class ConfirmationExitToDesktopWindow : GenericWindow { public void OnYes() { Application.Quit(); } }
using CMS_Database.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CMS_Database.Interfaces { public interface IPhanQuyen : IGenericRepository<PhanQuyen> { PhanQuyen GetByName(int? sControlerName,int? IdRole); void DeleteAll(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Controls; using Microsoft.Kinect; using System.Windows.Media.Animation; namespace ArduinoController { public partial class MainWindow : Window { #region Wheel Instance Variables /// <summary>Top of the wheel</summary> private double wheelTop; /// <summary>Left of the wheel</summary> private double wheelLeft; /// <summary>Width of the wheel</summary> private double wheelWidth; /// <summary>Height of the wheel</summary> private double wheelHeight; /// <summary>Center of the wheel</summary> private Point wheelCenter; #endregion #region Wheel Lock Instance Variables /// <summary> /// The wheel lock is the point at which the right hand is bound to the wheel. /// That point is the center of the first quadrant of the wheel. /// </summary> private Point wheelLock; /// <summary> /// The "slope" of the wheel lock is the slope from the wheel lock to the wheel center. /// </summary> private double wheelLockSlope; /// <summary>How far the wheel was rotated in the last frame</summary> private double lastRotation; #endregion /// <summary> True when the wheel has rotated more than 180 degrees; set to false when the wheel crosses back. </summary> private Boolean crossedWallFromRight; /// <summary> True when the wheel has rotated less than -180 degrees; set to false when wheel crosses back. </summary> private Boolean crossedWallFromLeft; /// <summary> /// Initializes components and instance variables for Steering Mode /// </summary> private void initSteeringComponents() { wheelTop = Canvas.GetTop(wheel); wheelLeft = Canvas.GetLeft(wheel); wheelWidth = wheel.Width; wheelHeight = wheel.Height; wheelCenter = new Point(wheelLeft + wheelWidth / 2, wheelTop + wheelHeight / 2); double wheelLockX = wheelCenter.X + wheelWidth / 4; double wheelLockY = wheelCenter.Y - wheelHeight / 4; wheelLock = new Point(wheelLockX, wheelLockY); wheelLockSlope = -1 * (wheelLock.Y - wheelCenter.Y) / (wheelLock.X - wheelCenter.X); } #region Main Behavior and Helpers /// <summary> /// The main Standard Mode function: /// - Updates the internal representation of the hands /// - Signals the Arduino when ready to drive /// - Signals the Arduino when to stop /// - Responsible for calculating the rotation of the wheel and updating the wheel in the GUI /// - Transforms and sends the rotation data to the Arduino and the servos /// </summary> private void steeringBehavior() { updateHandPositions(); if (stopped) { // if hands are in driving position and Arduino is stopped, then begin driving if (IsReadyToDrive()) StartMoving(); // keep arduino stopped if it's stopped and we're not ready to drive else return; } // If Arduino is moving and hands are in stop area, stop driving else if (IsLHandOverObject(kinectHandL, stopButton) || IsRHandOverObject(kinectHand, stopButton)) { StopMoving(); wheel.RenderTransform = new RotateTransform(0); crossedWallFromLeft = false; crossedWallFromRight = false; return; } // send driving data to Arduino and adjust wheel double nextRotation = getRotation(); wheel.RenderTransform = new RotateTransform(nextRotation); TransformAndSendDataToArduino(nextRotation); lastRotation = nextRotation; } /// <summary> /// We are ready to drive if R hand in quadrant I and L hand in quadrant IV /// </summary> /// <returns>A boolean indicating whether we are ready to drive the car (right hand in QI of wheel and left hand in QIV of wheel)</returns> private Boolean IsReadyToDrive() { // is R hand in QI? if (!(_RhandX > wheelCenter.X && _RhandX < wheelCenter.X + wheelWidth / 2 && _RhandY < wheelCenter.Y && _RhandY > wheelCenter.Y - wheelHeight / 2)) return false; // is L hand in QIV if (!(_LhandX > wheelCenter.X - wheelWidth / 2 && _LhandX < wheelCenter.X && _LhandY < wheelCenter.Y && _LhandY > wheelCenter.Y - wheelHeight / 2)) return false; // The R hand is in QI and the L hand is in QIV, so we're ready to drive!!! return true; } /// <summary> /// This method calculates the rotation of the wheel. /// It is calculated by finding the dot product between two vectors: /// a) the vector from the wheel center to the wheel lock and /// b) the vector from the wheel center to the position of the right hand. /// Once we have the dot product, we can easily find the angle between the two vectors, which can be regarded as the wheel rotation. /// </summary> /// <returns>The rotation of the wheel from the original position; negative if the rotation is to the left, positive if to the right</returns> private double getRotation() { // use the dot product method to find the rotation of the wheel double distX = _RhandX - wheelCenter.X; double distY = _RhandY - wheelCenter.Y; double lockdistX = wheelLock.X - wheelCenter.X; double lockdistY = wheelLock.Y - wheelCenter.Y; double dotproduct = distX * lockdistX + distY * lockdistY; double dist = Math.Sqrt(distX * distX + distY * distY); double lockdist = Math.Sqrt(lockdistX * lockdistX + lockdistY * lockdistY); double angle = Math.Acos(dotproduct / (dist * lockdist)) * 180 / Math.PI; // is the angle to the left or to the right? Negative angles are to the left, and positive angles are to the right double y = wheelCenter.Y - _RhandY; double x = _RhandX - wheelCenter.X; angle = (y <= x) ? angle : (-1 * angle); // did the user's hand go more than 180 degrees/did it turn really far right? if (lastRotation > 150 && angle < 0) { crossedWallFromRight = true; angle = 180; } // did the user's hand previously go more than 180 degrees, and did it come back to be less than 180 degrees? else if (crossedWallFromRight && lastRotation == 180 && angle > 150) { crossedWallFromRight = false; } // did the user's hand go less than -180 degrees/did it turn really far left? else if (lastRotation < -150 && angle > 0) { crossedWallFromLeft = true; angle = -180; } // did the user's hand previously go less than -180 degrees, and did it come back to be more than -180 degrees? else if (crossedWallFromLeft && lastRotation == -180 && angle < -150) { crossedWallFromLeft = false; } return angle; } /// <summary> /// Transforms hand positions into servos data and sends that to the Arduino /// </summary> /// <param name="rotation"></param> private void TransformAndSendDataToArduino(double rotation) { // if rotation is negative, move left if (rotation < 0) ArduinoSendLeftRight((float)(180 - (-1 * rotation)), ArduinoRfwd); // if rotation is positive, move right else if (rotation > 0) ArduinoSendLeftRight(ArduinoLfwd, (float)rotation); // otherwise, move forward else ArduinoSendLeftRight(ArduinoLfwd, ArduinoRfwd); } #endregion #region Turn On/Off Steering Mode /// <summary> /// Adds fade in animations (that turn on Standard Mode) to the given storyboard. /// </summary> /// <param name="storyboard">The storyboard on which the animations for fading out/in will be played</param> private void turnOnSteering(Storyboard storyboard) { stopped = true; crossedWallFromLeft = false; crossedWallFromRight = false; kinectHandL.Visibility = System.Windows.Visibility.Visible; kinectHandL.IsEnabled = true; stopButton.Opacity = 0.0; stopButton.Visibility = System.Windows.Visibility.Visible; stopButton.IsEnabled = true; storyboard.Children.Add(newAnimation(stopButton, 0, 1.0, fadeIn, fadeOut)); wheel.Opacity = 0.0; wheel.Visibility = System.Windows.Visibility.Visible; wheel.IsEnabled = true; storyboard.Children.Add(newImageAnimation(wheel, 0, 1.0, fadeIn, fadeOut)); foreach (TextBox box in textBoxes) { box.Visibility = System.Windows.Visibility.Visible; storyboard.Children.Add(newAnimation(box, 0, 1.0, fadeIn, fadeOut)); } foreach (Label label in labels) { label.Visibility = System.Windows.Visibility.Visible; storyboard.Children.Add(newAnimation(label, 0, 1.0, fadeIn, fadeOut)); } storyboard.Children.Add(newBackgroundAnimation(ViewerCanvas, 0, 1, fadeIn, fadeOut)); shiftViewerTo(60, 200); storyboard.Children.Add(newBackgroundAnimation(mainCanvas, 0.0, 1.0, fadeIn, fadeOut)); currentMode = Mode.STEERING; } /// <summary> /// Adds fade out animations (that turn off Standard Mode) to the given storyboard. /// </summary> /// <param name="storyboard">The storyboard on which the animations for fading out/in will be played</param> private void turnOffSteering(Storyboard storyboard) { StopMoving(); wheel.RenderTransform = new RotateTransform(0); crossedWallFromLeft = false; crossedWallFromRight = false; kinectHandL.Visibility = System.Windows.Visibility.Hidden; kinectHandL.IsEnabled = false; stopButton.IsEnabled = false; storyboard.Children.Add(newAnimation(stopButton, 1.0, 0, fadeOut, timeZero)); wheel.IsEnabled = false; storyboard.Children.Add(newImageAnimation(wheel, 1.0, 0, fadeOut, timeZero)); foreach (TextBox box in textBoxes) { storyboard.Children.Add(newAnimation(box, 1.0, 0.0, fadeOut, timeZero)); } foreach (Label label in labels) { storyboard.Children.Add(newAnimation(label, 1.0, 0.0, fadeOut, timeZero)); } storyboard.Children.Add(newBackgroundAnimation(mainCanvas, 0, 0, fadeOut, timeZero)); storyboard.Children.Add(newBackgroundAnimation(ViewerCanvas, 0, 0, fadeOut, timeZero)); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace GomokuEngine { public class GameInformation { public int Evaluation; //public int BlackScore; //public int WhiteScore; //public List<BoardSquare> gameMoveList; //public List<BoardSquare> playedMoves; public List<ABMove> possibleMoves; public BoardSquare nextMove; public BoardSquare GainSquare; public GameInformation() { } } }
using System.Collections.Generic; namespace DryRunTempBackend.API.Controllers { public class Wallet { public decimal Balance { get; set; } public IEnumerable<Transaction> Transactions{ get; set; } } }
using System; namespace ConsoleProcessRedirection { using System.IO; /// <summary> /// Summary description for ConsoleTerminal. /// </summary> public class ConsoleTerminal : ITerminal { #region ITerminal Members public void WriteTo(System.Text.StringBuilder OutputText, ConsoleProcessRedirection.OutputType OutType) { TextWriter outStream = null; if ( OutputType.StandardError == OutType ) { outStream = Console.Out; } else { outStream = Console.Error; } outStream.Write( OutputText.ToString() ); } void ConsoleProcessRedirection.ITerminal.WriteTo(System.Text.StringBuilder OutputText, System.Drawing.Color OutputColor, ConsoleProcessRedirection.OutputType OutType) { WriteTo( OutputText, OutType ); } #endregion } }
using Ghost.Utils; using System; using System.IO; using UnityEngine; namespace RO.Config { [CustomLuaClass] public static class BuildBundleEnvInfo { public static string Env { get { return AppEnvConfig.Instance.channelEnv; } } public static string CdnWithEnv { get { string path = "http://ro-xdcdn.b0.upaiyun.com/res/"; path = PathUnity.Combine(path, BuildBundleEnvInfo.Env); return PathUnity.Combine(path, ApplicationHelper.platformFolder + "/"); } } public static void SetEnv(string env, string sdk = "None") { string text = Path.Combine(Application.get_dataPath(), "Resources/ChannelEnv.xml"); AppEnvConfig appEnvConfig = XMLSerializedClass<AppEnvConfig>.CreateByFile(text); if (appEnvConfig == null) { appEnvConfig = new AppEnvConfig(); } if (appEnvConfig.channelEnv != env || appEnvConfig.sdk != sdk) { appEnvConfig.channelEnv = env; appEnvConfig.sdk = sdk; appEnvConfig.SaveToFile(text); } } } }
namespace TwitSystem.Services { using System.Linq; using Data.Models; public interface ITagService { IQueryable<Tag> GetAll(); } }
#region Copyright, Author Details and Related Context //<notice lastUpdateOn="12/20/2015"> // <solution>KozasAnt</solution> // <assembly>KozasAnt.Engine</assembly> // <description>A modern take on Koza's connonical "Ant Foraging for Food on a Grid" problem that leverages Roslyn</description> // <copyright> // Copyright (C) 2015 Louis S. Berman // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <author> // <fullName>Louis S. Berman</fullName> // <email>louis@squideyes.com</email> // <website>http://squideyes.com</website> // </author> //</notice> #endregion using KozasAnt.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; using System.Text; namespace KozasAnt.Engine { public class Entity<S, G, R> : IComparable<Entity<S, G, R>> where S : SettingsBase where G : GenomeBase<S, R> where R : ReportBase<R>, new() { public Entity(KnownAs knownAs, CodeTree<S, G, R> codeTree) { Contract.Requires(knownAs != null, nameof(knownAs)); Contract.Requires(codeTree != null, nameof(codeTree)); KnownAs = knownAs; CodeTree = codeTree; } public Entity(KnownAs knownAs, KnownAs parent1, KnownAs parent2, CodeTree<S, G, R> codeTree) : this(knownAs, codeTree) { Contract.Requires(parent1 != null, nameof(parent1)); Contract.Requires(parent2 != null, nameof(parent2)); Parent1 = parent1; Parent2 = parent2; } public KnownAs KnownAs { get; } public KnownAs Parent1 { get; } public KnownAs Parent2 { get; } public CodeTree<S, G, R> CodeTree { get; } public R Report { get; set; } public int CompareTo(Entity<S, G, R> other) { return Report.CompareTo(other.Report); } public string ToCode() { var sb = new StringBuilder(); sb.Append($"using {typeof(S).Namespace};"); sb.Append($"using {typeof(Cohort).Namespace};"); sb.Append($"namespace {(Cohort)KnownAs}"); sb.Append("{"); sb.Append(BuildClass(this)); sb.Append("}"); var tree = CSharpSyntaxTree.ParseText(sb.ToString()); var root = (CSharpSyntaxNode)tree.GetRoot(); return root.NormalizeWhitespace().ToFullString(); } public override string ToString() { return $"{KnownAs} {Report}"; } internal static string BuildClass(Entity<S, G, R> entity) { var sb = new StringBuilder(); sb.Append($"public class {entity.KnownAs}: {typeof(G).Name}{{"); sb.Append($"public {entity.KnownAs}(KnownAs knownAs, Settings settings)"); sb.Append(": base(knownAs, settings){}"); sb.Append("public override void DoWork(){"); sb.Append("while(Status == WorkStatus.GoalsNotMet){"); AddStatements(sb, entity.CodeTree); sb.Append("}}}"); return sb.ToString(); } private static void AddStatements(StringBuilder sb, CodeTree<S, G, R> codeTree) { switch (codeTree.Node.Kind) { case NodeKind.Function: sb.Append($"if({codeTree.Node.Method.Name}()){{"); AddStatements(sb, codeTree.Children[0]); sb.Append("}else{"); AddStatements(sb, codeTree.Children[1]); sb.Append("}"); break; case NodeKind.ChildCount: foreach (var child in codeTree.Children) AddStatements(sb, child); break; case NodeKind.Terminal: sb.Append("if (Status == WorkStatus.GoalsNotMet){"); sb.Append(codeTree.Node.Method.Name); sb.Append("();Report.IncrementStepCount();}"); break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PO.Types.Attributes { [AttributeUsage (AttributeTargets.Class)] public class DefaultDatabaseAttribute : Attribute { public string mDatabaseName; public DefaultDatabaseAttribute(string pDatabaseName) { mDatabaseName = pDatabaseName; } } }
using EmployeeManagementApp.Models; using System.Linq; using System.Web.Mvc; using System.Web.Security; namespace EmployeeManagementApp.Controllers { [Authorize] public class LoginController : Controller { private DatabaseEntities db = new DatabaseEntities(); [AllowAnonymous] public ActionResult Index() { if (Request.IsAuthenticated) { return View("Menu"); } return View(); } [AllowAnonymous] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index([Bind(Include = "name, password")] loginuser model) { if (ModelState.IsValid && model.name != null && model.password != null) { if (ValidateUser(model)) { FormsAuthentication.SetAuthCookie(userName: model.name, createPersistentCookie: false); return RedirectToAction(actionName: "Menu"); } } ViewBag.Message = "ユーザ名かパスワードが間違っています。"; return View(model); } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToAction(actionName: "Index"); } public ActionResult Menu() { return View(); } private bool ValidateUser(loginuser model) { var hash = loginuser.GeneratePasswordHash(model.name, model.password); var user = db.loginusers .Where(u => u.name == model.name && u.password == hash) .FirstOrDefault(); if (model.name == "admin" && model.password == "pass") return true; return user != null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FuelLevelSystem.Model { class FuelStatRecord { public String FuelName { get; set; } public UInt64 Capacity { get; set; } public UInt64 FuelPumpTotal { get; set; } } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class SysBenutzer { public SysBenutzer() { GpBelegRechte = new HashSet<GpBelegRechte>(); GpBelegVerweis = new HashSet<GpBelegVerweis>(); SysBenutzerGruppeBenutzer = new HashSet<SysBenutzerGruppe>(); SysBenutzerGruppeGruppe = new HashSet<SysBenutzerGruppe>(); SysRecht = new HashSet<SysRecht>(); } public int BenutzerId { get; set; } public int? PersonId { get; set; } public bool Gruppe { get; set; } public byte? StandardSichtRecht { get; set; } public byte? StandardDruckRecht { get; set; } public virtual SysMitarbeiter Person { get; set; } public virtual ICollection<GpBelegRechte> GpBelegRechte { get; set; } public virtual ICollection<GpBelegVerweis> GpBelegVerweis { get; set; } public virtual ICollection<SysBenutzerGruppe> SysBenutzerGruppeBenutzer { get; set; } public virtual ICollection<SysBenutzerGruppe> SysBenutzerGruppeGruppe { get; set; } public virtual ICollection<SysRecht> SysRecht { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Framework.Remote.Mobile { [DataContract(Name = "CxClientDashboardData", Namespace = "http://schemas.datacontract.org/2004/07/FulcrumWeb")] public class CxClientDashboardData { [DataMember] public CxClientDashboardItem[] DashboardItems; [DataMember] public string Text; [DataMember] public CxExceptionDetails Error { get; set; } } }
using UnityEngine; public class ShardController : MonoBehaviour { public GameObject crystalPrefab; public void SpawnCrystal() { foreach (Transform shard in transform) { Destroy(shard.gameObject); } var pos = transform.position; Debug.Log(pos); Instantiate(crystalPrefab, transform); } }
namespace Clubber.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class KeysInJoinTab : DbMigration { public override void Up() { CreateIndex("dbo.StudentAndClub", "StudentID"); CreateIndex("dbo.StudentAndClub", "ClubID"); AddForeignKey("dbo.StudentAndClub", "ClubID", "dbo.Club", "ClubId", cascadeDelete: true); AddForeignKey("dbo.StudentAndClub", "StudentID", "dbo.Student", "StudentId", cascadeDelete: true); } public override void Down() { DropForeignKey("dbo.StudentAndClub", "StudentID", "dbo.Student"); DropForeignKey("dbo.StudentAndClub", "ClubID", "dbo.Club"); DropIndex("dbo.StudentAndClub", new[] { "ClubID" }); DropIndex("dbo.StudentAndClub", new[] { "StudentID" }); } } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System.Collections.Generic; using System.Runtime.Serialization; using Framework.Utils; namespace Framework.Remote { /// <summary> /// Container which contains parameters for server queries. /// </summary> [DataContract] public class CxQueryParams { /// <summary> /// Entity Usage Id. /// </summary> [DataMember] public string EntityUsageId; //---------------------------------------------------------------------------- /// <summary> /// Join condition values for query. /// </summary> [DataMember] public Dictionary<string, object> JoinValues; //---------------------------------------------------------------------------- /// <summary> /// Where clause values for query. /// </summary> [DataMember] public Dictionary<string, object> WhereValues; //---------------------------------------------------------------------------- /// <summary> /// Primary keys values for query. /// </summary> [DataMember] public Dictionary<string, object> PrimaryKeysValues; //---------------------------------------------------------------------------- /// <summary> /// Filter values values for query. /// </summary> [DataMember] public CxFilterItem[] FilterItems; //---------------------------------------------------------------------------- /// <summary> /// The fields to sort by. /// </summary> [DataMember] public CxSortDescription[] SortDescriptions; //---------------------------------------------------------------------------- /// <summary> /// Values of current entity. /// </summary> [DataMember] public Dictionary<string, object> EntityValues; //---------------------------------------------------------------------------- /// <summary> /// Parent entity primary keys. /// </summary> [DataMember] public Dictionary<string, object> ParentPks; //---------------------------------------------------------------------------- /// <summary> /// Parent entity usage id. /// </summary> [DataMember] public string ParentEntityUsageId; //---------------------------------------------------------------------------- /// <summary> /// Attribute Id that had changed. /// </summary> [DataMember] public string ChangedAttributeId { get; set; } //---------------------------------------------------------------------------- /// <summary> /// The starting index of the record to get. /// </summary> [DataMember] public int StartRecordIndex { get; set; } //---------------------------------------------------------------------------- /// <summary> /// The max amount of the records to get (page size, in our circumstances). /// </summary> [DataMember] public int RecordsAmount { get; set; } //---------------------------------------------------------------------------- /// <summary> /// Defines server method that will be used to get model. /// (Workaround. Because WCF with Silverligh do not supports Enums.) /// </summary> [DataMember] public string QueryType = CxQueryTypes.ENTITY_LIST; //---------------------------------------------------------------------------- /// <summary> /// Entity open mode /// </summary> [DataMember] public string OpenMode{ get; set;} //---------------------------------------------------------------------------- /// <summary> /// Creates instance of IxValueProvider that contains values for query. /// </summary> /// <param name="names">List of parameters names.</param> /// <param name="values">List of parameters values.</param> /// <returns>Created instance of IxValueProvider that contains values for query.</returns> public static IxValueProvider CreateValueProvider(Dictionary<string, object> whereValues) { CxHashtable provider = new CxHashtable(); foreach (KeyValuePair<string, object> wherePair in whereValues) { provider.Add(wherePair.Key, wherePair.Value); } return provider; } //---------------------------------------------------------------------------- /// <summary> /// Creates instance of IxValueProvider that contains values for query. /// </summary> /// <param name="entityValues"></param> /// <returns></returns> public static IxValueProvider CreateValueProvider(IDictionary<string, object> entityValues) { CxHashtable provider = new CxHashtable(); foreach (KeyValuePair<string, object> pair in entityValues) { provider.Add(pair.Key, pair.Value); } return provider; } } //---------------------------------------------------------------------------- /// <summary> /// Contains constants to define server method that will be used to get model. /// (Workaround. Because WCF with Silverligh do not supports Enums.) /// </summary> public static class CxQueryTypes { /// <summary> /// GetEntityList mthod. /// </summary> public static string ENTITY_LIST = "EntityList"; //---------------------------------------------------------------------------- /// <summary> /// GetChildEntityList method. /// </summary> public static string CHILD_ENTITY_LIST = "ChildEntityList"; //---------------------------------------------------------------------------- /// <summary> /// Get EntityFromPk method. /// </summary> public static string ENTITY_FROM_PK = "EntityFromPk"; //---------------------------------------------------------------------------- /// <summary> /// Redirect posted Entity back. /// </summary> public static string DIRECT_BACK_ENTITY = "DirectBackEntity"; } }
using System; using System.Data; using System.Data.SqlClient; namespace CamadaDados { public class DPrograma { // Criacao das variáveis private int _Codigo; private string _Audio; private string _Duracao; private string _DataCadastro; private string _Sintese; private string _TextBusca; // Codigo public int Codigo { get { return _Codigo; } set { _Codigo = value; } } // Audio public string Audio { get { return _Audio; } set { _Audio = value; } } // Duracao public string Duracao { get { return _Duracao; } set { _Duracao = value; } } // Data Cadastro public string DataCadastro { get { return _DataCadastro; } set { _DataCadastro = value; } } // Sintese public string Sintese { get { return _Sintese; } set { _Sintese = value; } } // Texto de busca public string TextBusca { get { return _TextBusca; } set { _TextBusca = value; } } //Cosntrutor vazio public DPrograma() { } //Construtor com parametros public DPrograma(int codigo,string audio, string duracao, string dataCadastro, string sintese, string textBusca) { this.Codigo = codigo; this.Audio = audio; this.Duracao = duracao; this.DataCadastro = dataCadastro; this.Sintese = sintese; this.TextBusca = textBusca; } //Método Inserir public string Inserir(DPrograma Programa) { string resp = ""; SqlConnection SqlCon = new SqlConnection(); try { //codigo SqlCon.ConnectionString = Conexao.Cn; SqlCon.Open(); SqlCommand SqlCmd = new SqlCommand(); SqlCmd.Connection = SqlCon; SqlCmd.CommandText = "spinserir_programa"; SqlCmd.CommandType = CommandType.StoredProcedure; SqlParameter ParCodigo = new SqlParameter(); ParCodigo.ParameterName = "@codigo"; ParCodigo.SqlDbType = SqlDbType.Int; ParCodigo.Direction = ParameterDirection.Output; SqlCmd.Parameters.Add(ParCodigo); SqlParameter ParAudio = new SqlParameter(); ParAudio.ParameterName = "@audio"; ParAudio.SqlDbType = SqlDbType.VarChar; ParAudio.Size = 100; ParAudio.Value = Programa.Audio; SqlCmd.Parameters.Add(ParAudio); SqlParameter ParDuracao = new SqlParameter(); ParDuracao.ParameterName = "@duracao"; ParDuracao.SqlDbType = SqlDbType.VarChar; ParDuracao.Size = 5; ParDuracao.Value = Programa.Duracao; SqlCmd.Parameters.Add(ParDuracao); SqlParameter ParDataCadastro = new SqlParameter(); ParDataCadastro.ParameterName = "@dataCadastro"; ParDataCadastro.SqlDbType = SqlDbType.DateTime; ParDataCadastro.Size = 10; ParDataCadastro.Value = Programa.DataCadastro; SqlCmd.Parameters.Add(ParDataCadastro); SqlParameter ParSintese = new SqlParameter(); ParSintese.ParameterName = "@sintese"; ParSintese.SqlDbType = SqlDbType.VarChar; ParSintese.Size = 1000; ParSintese.Value = Programa.Sintese; SqlCmd.Parameters.Add(ParSintese); //Executar o comando resp = SqlCmd.ExecuteNonQuery() == 1 ? "OK" : "Registro não foi inserido"; } catch (Exception ex) { resp = ex.Message; } finally { if (SqlCon.State == ConnectionState.Open) SqlCon.Close(); } return resp; } //Método Editar public string Editar(DPrograma Programa) { string resp = ""; SqlConnection SqlCon = new SqlConnection(); try { //codigo SqlCon.ConnectionString = Conexao.Cn; SqlCon.Open(); SqlCommand SqlCmd = new SqlCommand(); SqlCmd.Connection = SqlCon; SqlCmd.CommandText = "speditar_programa"; SqlCmd.CommandType = CommandType.StoredProcedure; SqlParameter ParCodigo = new SqlParameter(); ParCodigo.ParameterName = "@codigo"; ParCodigo.SqlDbType = SqlDbType.Int; ParCodigo.Value = Programa.Codigo; SqlCmd.Parameters.Add(ParCodigo); SqlParameter ParAudio = new SqlParameter(); ParAudio.ParameterName = "@audio"; ParAudio.SqlDbType = SqlDbType.VarChar; ParAudio.Size = 100; ParAudio.Value = Programa.Audio; SqlCmd.Parameters.Add(ParAudio); SqlParameter ParDuracao = new SqlParameter(); ParDuracao.ParameterName = "@duracao"; ParDuracao.SqlDbType = SqlDbType.VarChar; ParDuracao.Size = 5; ParDuracao.Value = Programa.Duracao; SqlCmd.Parameters.Add(ParDuracao); SqlParameter ParDataCadastro = new SqlParameter(); ParDataCadastro.ParameterName = "@dataCadastro"; ParDataCadastro.SqlDbType = SqlDbType.DateTime; ParDataCadastro.Size = 5; ParDataCadastro.Value = Programa.DataCadastro; SqlCmd.Parameters.Add(ParDataCadastro); SqlParameter ParSintese = new SqlParameter(); ParSintese.ParameterName = "@sintese"; ParSintese.SqlDbType = SqlDbType.VarChar; ParSintese.Size = 1000; ParSintese.Value = Programa.Sintese; SqlCmd.Parameters.Add(ParSintese); resp = SqlCmd.ExecuteNonQuery() == 1 ? "OK" : "A Edição não foi feita."; } catch (Exception ex) { resp = ex.Message; } finally { if (SqlCon.State == ConnectionState.Open) SqlCon.Close(); } return resp; } //Método Excluir public string Excluir(DPrograma Programa) { string resp = ""; SqlConnection SqlCon = new SqlConnection(); try { //codigo SqlCon.ConnectionString = Conexao.Cn; SqlCon.Open(); SqlCommand SqlCmd = new SqlCommand(); SqlCmd.Connection = SqlCon; SqlCmd.CommandText = "spdeletar_programa"; SqlCmd.CommandType = CommandType.StoredProcedure; SqlParameter ParCodigo = new SqlParameter(); ParCodigo.ParameterName = "@Codigo"; ParCodigo.SqlDbType = SqlDbType.Int; ParCodigo.Value = Programa.Codigo; SqlCmd.Parameters.Add(ParCodigo); resp = SqlCmd.ExecuteNonQuery() == 1 ? "OK" : "A exclusão não foi feita."; } catch (Exception ex) { resp = ex.Message; } finally { if (SqlCon.State == ConnectionState.Open) SqlCon.Close(); } return resp; } //Método Mostrar public DataTable Mostrar() { string resp = ""; DataTable DtResultado = new DataTable("Programa"); SqlConnection SqlCon = new SqlConnection(); try { SqlCon.ConnectionString = Conexao.Cn; SqlCommand SqlCmd = new SqlCommand(); SqlCmd.Connection = SqlCon; SqlCmd.CommandText = "spmostrar_programa"; SqlCmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter SqlDat = new SqlDataAdapter(SqlCmd); SqlDat.Fill(DtResultado); } catch (Exception ex) { DtResultado = null; resp = ex.Message; } return DtResultado; } //Método Buscar Nome public DataTable BuscarNome(DPrograma Programa) { string resp = ""; DataTable DtResultado = new DataTable("Programa"); SqlConnection SqlCon = new SqlConnection(); try { SqlCon.ConnectionString = Conexao.Cn; SqlCommand SqlCmd = new SqlCommand(); SqlCmd.Connection = SqlCon; SqlCmd.CommandText = "spbuscar_nome"; SqlCmd.CommandType = CommandType.StoredProcedure; SqlParameter ParTextBuscar = new SqlParameter(); ParTextBuscar.ParameterName = "@textbuscar"; ParTextBuscar.SqlDbType = SqlDbType.VarChar; ParTextBuscar.Size = 100; ParTextBuscar.Value = Programa.TextBusca; SqlCmd.Parameters.Add(ParTextBuscar); SqlDataAdapter SqlDat = new SqlDataAdapter(SqlCmd); SqlDat.Fill(DtResultado); } catch (Exception ex) { DtResultado = null; resp = ex.Message; } return DtResultado; } } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_ForceMode2D : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.ForceMode2D"); LuaObject.addMember(l, 0, "Force"); LuaObject.addMember(l, 1, "Impulse"); LuaDLL.lua_pop(l, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CRM.UI.ViewModel { public class OrderViewModel { public Guid Id { get; set; } public string FullName { get; set; } public DateTime RequiredDate { get; set; } public decimal SellingPrice { get; set; } } }
using Mccole.Geodesy.Calculator; using System; namespace Mccole.Geodesy.Formatter { /// <summary> /// Provides culture-specific information for formatting and parsing numeric values to a Degree-Minute-Second format. /// </summary> public class DegreeMinuteSecondFormatInfo : IFormatProvider, ICustomFormatter { /* * Scale Value Distance (m) * ------- --------- ----------- * 1 0.1000000 11,057.43 11 km * 2 0.0100000 1,105.74 1.1 km * 3 0.0010000 110.57 110 m * 4 0.0001000 11.06 10 m * 5 0.0000100 1.11 1.1 m * 6 0.0000010 0.11 11 cm * 7 0.0000001 0.01 1 cm */ /// <summary> /// Format string for formatting a floating point value to have 2 whole numbers. /// </summary> protected const string DegreeFormatString2 = "{0:00.#########}"; /// <summary> /// Format string for formatting a floating point value to have 3 whole numbers. /// </summary> protected const string DegreeFormatString3 = "{0:000.#########}"; /// <summary> /// The default value used to separate the Degrees-Minutes-Seconds value, a single space. /// </summary> protected readonly static string DefaultSeparator = new string((char)32, 1); /// <summary> /// The default symbol used for the Degrees part of a Degrees-Minutes-Seconds value. /// </summary> public const string DefaultDegreeSymbol = "°"; /// <summary> /// The default symbol used for the Minutes part of a Degrees-Minutes-Seconds value. /// </summary> public const string DefaultMinuteSymbol = "'"; /// <summary> /// The default scale used for the last numeric component of a Degrees-Minutes-Seconds value. /// </summary> public const int DefaultScale = 0; /// <summary> /// The default symbol used for the Seconds part of a Degrees-Minutes-Seconds value. /// </summary> public const string DefaultSecondSymbol = "''"; /// <summary> /// Provides culture-specific information for formatting and parsing numeric values to a Degree-Minute-Second format. /// </summary> public DegreeMinuteSecondFormatInfo() : this(DefaultScale) { } /// <summary> /// Provides culture-specific information for formatting and parsing numeric values to a Degree-Minute-Second format. /// </summary> /// <param name="scale">Number of decimal places to use of the last part of.</param> public DegreeMinuteSecondFormatInfo(int scale) : this(scale, DefaultSeparator) { } /// <summary> /// Provides culture-specific information for formatting and parsing numeric values to a Degree-Minute-Second format. /// </summary> /// <param name="scale">Number of decimal places used for the last value displayed.</param> /// <param name="separator">The character (usually a space) used to separate the degree, minute and second values.</param> public DegreeMinuteSecondFormatInfo(int scale, string separator) { if (scale < 0) { throw new ArgumentOutOfRangeException(nameof(scale), "The argument must be greater than or equal to zero."); } this.Scale = scale; this.Separator = separator; this.DegreeSymbol = DefaultDegreeSymbol; this.MinuteSymbol = DefaultMinuteSymbol; this.SecondSymbol = DefaultSecondSymbol; } /// <summary> /// The format string used to format the degrees value. /// </summary> protected virtual string DegreeFormatString { get { return DegreeFormatString3; } } /// <summary> /// The symbol used to signify a degrees value. /// </summary> public string DegreeSymbol { get; set; } /// <summary> /// The symbol used to signify a minutes value. /// </summary> public string MinuteSymbol { get; set; } /// <summary> /// The number of decimal places to display for the last part of a Degrees-Minutes-Seconds value. /// </summary> public int Scale { get; set; } /// <summary> /// The symbol used to signify a seconds value. /// </summary> public string SecondSymbol { get; set; } /// <summary> /// The space character(s) to insert between the Degrees, Minutes and Seconds values after each symbol. /// </summary> public string Separator { get; set; } private string ToDegree(DegreeMinuteSecond dms) { string d = string.Format(this.DegreeFormatString, Math.Round(dms.Degrees, this.Scale)); return string.Format("{0}{1}", d, this.DegreeSymbol); } private string ToDegreeMinute(DegreeMinuteSecond dms) { string d = string.Format(this.DegreeFormatString, dms.Degree); string m = string.Format("{0:00.#########}", Math.Round(dms.Minutes, this.Scale)); return string.Format("{1}{2}{0}{3}{4}", this.Separator, d, this.DegreeSymbol, m, this.MinuteSymbol); } private string ToDegreeMinuteSecond(DegreeMinuteSecond dms) { string d = string.Format(this.DegreeFormatString, dms.Degree); string m = string.Format("{0:00.#########}", dms.Minute); string s = string.Format("{0:00.#########}", Math.Round(dms.Seconds, this.Scale)); return string.Format("{1}{2}{0}{3}{4}{0}{5}{6}", this.Separator, d, this.DegreeSymbol, m, this.MinuteSymbol, s, this.SecondSymbol); } /// <summary> /// Format the argument when the data type is not one of the expected types. /// </summary> /// <param name="format"></param> /// <param name="arg"></param> /// <returns></returns> protected static string FormatUnexpectedDataType(string format, object arg) { try { IFormattable formattable = arg as IFormattable; if (formattable != null) { return formattable.ToString(format, System.Globalization.CultureInfo.CurrentCulture); } else if (arg != null) { return arg.ToString(); } else { return string.Empty; } } catch (FormatException ex) { throw new FormatException(string.Format("The format of '{0}' is invalid, use 'D', 'DM', or 'DMS' optionally suffixed with a scale value.", format), ex); } } /// <summary> /// Attempt to parse the argument to a DegreeMinuteSecond object. /// </summary> /// <param name="arg"></param> /// <param name="result"></param> /// <returns></returns> protected static bool TryParse(object arg, out DegreeMinuteSecond result) { DegreeMinuteSecond dms = arg as DegreeMinuteSecond; if (dms == null && arg is double == false) { result = null; return false; } else if (dms == null) { result = new DegreeMinuteSecond((double)arg); return true; } else { result = dms; return true; } } /// <summary> /// Format this object to a Degrees-Minutes-Seconds string. /// </summary> /// <param name="format"></param> /// <param name="arg"></param> /// <param name="formatProvider"></param> /// <returns></returns> protected virtual string DoFormat(string format, object arg, IFormatProvider formatProvider) { if (arg == null) { throw new ArgumentNullException(nameof(arg), "The argument cannot be null."); } DegreeMinuteSecond dms = null; if (!DegreeMinuteSecondFormatInfo.TryParse(arg, out dms)) { // Provide default formatting if the argument is not as expected (Double or DegreeMinuteSecond). return FormatUnexpectedDataType(format, arg); } // Adjust for missing format. #pragma warning disable S3900 string f = string.Empty; if (string.IsNullOrWhiteSpace(format)) { // Default to everything. f = "DMS"; } else { f = format.ToUpper(System.Globalization.CultureInfo.CurrentCulture); } #pragma warning restore S3900 UpdateScaleFromFormatString(format); string secondsFormat = "S"; string minutesFormat = "M"; if (f.Contains(secondsFormat)) { return ToDegreeMinuteSecond(dms); } else if (f.Contains(minutesFormat)) { return ToDegreeMinute(dms); } else { return ToDegree(dms); } } /// <summary> /// Attempt to read a scale value from the format string, expects the last character to be numeric. /// </summary> /// <param name="format"></param> protected void UpdateScaleFromFormatString(string format) { #pragma warning disable S3900 int scale; if (string.IsNullOrEmpty(format) || format.Trim().Length == 1) { // Do nothing. } else if (int.TryParse(format.Substring(format.Length - 1), out scale)) { this.Scale = scale; } #pragma warning restore S3900 } /// <summary> /// Converts the value of a specified object to an equivalent string representation using specified format and culture-specific formatting information. /// </summary> /// <param name="format"></param> /// <param name="arg"></param> /// <param name="formatProvider"></param> /// <returns></returns> public string Format(string format, object arg, IFormatProvider formatProvider) { return DoFormat(format, arg, formatProvider); } /// <summary> /// Returns an object that provides formatting services for the specified type. /// </summary> /// <param name="formatType"></param> /// <returns></returns> [System.Diagnostics.DebuggerStepThrough] public object GetFormat(Type formatType) { return formatType == typeof(ICustomFormatter) ? this : null; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ICommandLineArgumentsFactoryService), LanguageNames.CSharp), Shared] internal sealed class CSharpCommandLineParserFactory : ICommandLineArgumentsFactoryService { public CommandLineArguments CreateCommandLineArguments(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { #if SCRIPTING var parser = isInteractive ? CSharpCommandLineParser.Interactive : CSharpCommandLineParser.Default; #else var parser = CSharpCommandLineParser.Default; #endif return parser.Parse(arguments, baseDirectory, sdkDirectory); } } [ExportLanguageService(typeof(IHostBuildDataFactory), LanguageNames.CSharp), Shared] internal sealed class CSharpHostBuildDataFactory : IHostBuildDataFactory { public HostBuildData Create(HostBuildOptions options) { var parseOptions = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6, documentationMode: DocumentationMode.Parse); var compilationOptions = new CSharpCompilationOptions( OutputKind.ConsoleApplication, xmlReferenceResolver: new XmlFileResolver(options.ProjectDirectory), sourceReferenceResolver: new SourceFileResolver(ImmutableArray<string>.Empty, options.ProjectDirectory), metadataReferenceResolver: new AssemblyReferenceResolver( new MetadataFileReferenceResolver(ImmutableArray<string>.Empty, options.ProjectDirectory), MetadataFileReferenceProvider.Default), strongNameProvider: new DesktopStrongNameProvider(ImmutableArray.Create(options.ProjectDirectory, options.OutputDirectory)), assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default); var warnings = new List<KeyValuePair<string, ReportDiagnostic>>(options.Warnings); if (options.OutputKind.HasValue) { var kind = options.OutputKind.Value; compilationOptions = compilationOptions.WithOutputKind(kind); if (compilationOptions.Platform == Platform.AnyCpu32BitPreferred && (kind == OutputKind.DynamicallyLinkedLibrary || kind == OutputKind.NetModule || kind == OutputKind.WindowsRuntimeMetadata)) { compilationOptions = compilationOptions.WithPlatform(Platform.AnyCpu); } } if (!string.IsNullOrEmpty(options.DefineConstants)) { IEnumerable<Diagnostic> diagnostics; parseOptions = parseOptions.WithPreprocessorSymbols(CSharpCommandLineParser.ParseConditionalCompilationSymbols(options.DefineConstants, out diagnostics)); } if (options.DocumentationFile != null) { parseOptions = parseOptions.WithDocumentationMode(!string.IsNullOrEmpty(options.DocumentationFile) ? DocumentationMode.Diagnose : DocumentationMode.Parse); } if (options.LanguageVersion != null) { var languageVersion = CompilationOptionsConversion.GetLanguageVersion(options.LanguageVersion); if (languageVersion.HasValue) { parseOptions = parseOptions.WithLanguageVersion(languageVersion.Value); } } if (!string.IsNullOrEmpty(options.PlatformWith32BitPreference)) { Platform platform; if (Enum.TryParse<Platform>(options.PlatformWith32BitPreference, true, out platform)) { if (platform == Platform.AnyCpu && compilationOptions.OutputKind != OutputKind.DynamicallyLinkedLibrary && compilationOptions.OutputKind != OutputKind.NetModule && compilationOptions.OutputKind != OutputKind.WindowsRuntimeMetadata) { platform = Platform.AnyCpu32BitPreferred; } compilationOptions = compilationOptions.WithPlatform(platform); } } if (options.AllowUnsafeBlocks.HasValue) { compilationOptions = compilationOptions.WithAllowUnsafe(options.AllowUnsafeBlocks.Value); } if (options.CheckForOverflowUnderflow.HasValue) { compilationOptions = compilationOptions.WithOverflowChecks(options.CheckForOverflowUnderflow.Value); } if (options.DelaySign != null) { bool delaySignExplicitlySet = options.DelaySign.Item1; bool delaySign = options.DelaySign.Item2; compilationOptions = compilationOptions.WithDelaySign(delaySignExplicitlySet ? delaySign : (bool?)null); } if (!string.IsNullOrEmpty(options.ApplicationConfiguration)) { var appConfigPath = FileUtilities.ResolveRelativePath(options.ApplicationConfiguration, options.ProjectDirectory); try { using (var appConfigStream = PortableShim.FileStream.Create(appConfigPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read)) { compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream)); } } catch (Exception) { } } if (!string.IsNullOrEmpty(options.KeyContainer)) { compilationOptions = compilationOptions.WithCryptoKeyContainer(options.KeyContainer); } if (!string.IsNullOrEmpty(options.KeyFile)) { var fullPath = FileUtilities.ResolveRelativePath(options.KeyFile, options.ProjectDirectory); compilationOptions = compilationOptions.WithCryptoKeyFile(fullPath); } if (!string.IsNullOrEmpty(options.MainEntryPoint)) { compilationOptions = compilationOptions.WithMainTypeName(options.MainEntryPoint); } if (!string.IsNullOrEmpty(options.ModuleAssemblyName)) { compilationOptions = compilationOptions.WithModuleName(options.ModuleAssemblyName); } if (options.Optimize.HasValue) { compilationOptions = compilationOptions.WithOptimizationLevel(options.Optimize.Value ? OptimizationLevel.Release : OptimizationLevel.Debug); } if (!string.IsNullOrEmpty(options.Platform)) { Platform plat; if (Enum.TryParse<Platform>(options.Platform, ignoreCase: true, result: out plat)) { compilationOptions = compilationOptions.WithPlatform(plat); } } // Get options from the ruleset file, if any. if (!string.IsNullOrEmpty(options.RuleSetFile)) { var fullPath = FileUtilities.ResolveRelativePath(options.RuleSetFile, options.ProjectDirectory); Dictionary<string, ReportDiagnostic> specificDiagnosticOptions; var generalDiagnosticOption = RuleSet.GetDiagnosticOptionsFromRulesetFile(fullPath, out specificDiagnosticOptions); compilationOptions = compilationOptions.WithGeneralDiagnosticOption(generalDiagnosticOption); warnings.AddRange(specificDiagnosticOptions); } if (options.WarningsAsErrors.HasValue) { compilationOptions = compilationOptions.WithGeneralDiagnosticOption(options.WarningsAsErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default); } if (options.WarningLevel.HasValue) { compilationOptions = compilationOptions.WithWarningLevel(options.WarningLevel.Value); } compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(warnings); return new HostBuildData( parseOptions, compilationOptions); } } }
#region Copyright Syncfusion Inc. 2001-2019. // Copyright Syncfusion Inc. 2001-2019. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using Xamarin.Forms; namespace SmartRecord.Views.Controls { /// <summary> /// We have inherited from Entry, since we have used custom renderer to remove border for Entry in Android platform. /// </summary> public class BorderlessEntry : Entry { } }
using Umbraco.Core.Models; using Umbraco.Web; namespace AgeBaseTemplate.Core.Wrappers { public interface IUmbracoContext { UmbracoContext Current { get; } IPublishedContent CurrentPublishedContent { get; } void EnsureContext(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Contoso.XPlatform.Utils { internal static class BusyIndicatorHelpers { public async static Task<TResult> ExecuteRequestWithBusyIndicator<TResult>(Func<Task<TResult>> action) where TResult : class { Task delay; Task<TResult> getResponse; TResult? response = null; List<Task> tasks = new() { (delay = Task.Delay(400)), (getResponse = action()) }; bool activityIndicatorRunning = false; /*Tak.ConfigureAwait(true) for all tasks seems to proevent issue of the Busy Indicator window not closing.*/ while (tasks.Any()) { Task finishedTask = await Task.WhenAny(tasks).ConfigureAwait(true); if (object.ReferenceEquals(finishedTask, delay) && response == null) await ShowBusyIndaicator().ConfigureAwait(true); else if (object.ReferenceEquals(finishedTask, getResponse)) response = getResponse.Result; tasks.Remove(finishedTask); } await RemoveBusyIndaicator().ConfigureAwait(true); return response ?? throw new ArgumentException($"{nameof(response)}: {{189D9682-88D9-440C-BEEB-7B77E345FCA3}}"); Task ShowBusyIndaicator() { activityIndicatorRunning = true; return Xamarin.Essentials.MainThread.InvokeOnMainThreadAsync (/*App.Current.MainPage is not null at this point*/ async () => await App.Current!.MainPage!.Navigation.PushModalAsync ( new Views.BusyIndicator(), false ).ConfigureAwait(true) ); } Task RemoveBusyIndaicator() { if (!activityIndicatorRunning) { return Task.CompletedTask; } return Xamarin.Essentials.MainThread.InvokeOnMainThreadAsync (/*App.Current.MainPage is not null at this point*/ async () => await App.Current!.MainPage!.Navigation.PopModalAsync(false).ConfigureAwait(true) ); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameCenter { class Mjesecna : Registracija { public override decimal DajPopust() { return 20; } } }
using System.Threading.Tasks; namespace AquaServiceSPA.Services { public interface IVisitService { Task<string> AddAsync(); } }
using AutoMapper; using CMS.Core.Model; using CMS.Service.Dtos.RestrictedAccessTime; using CMS.Service.Dtos.RestrictedIP; using CMS.Service.Dtos.UserLog; namespace CMS.Service.Infrastructure { public class MappingProfile : Profile { public MappingProfile() { #region UserLog CreateMap<UserLog, UserLogDto>() .ForMember(dest => dest.UserName , opt => opt.MapFrom(src => src.User.UserName)) .ForMember(dest => dest.Date , opt => opt.MapFrom(src => src.Date.ToShortDateString())); #endregion #region RestrictedIP CreateMap<RestrictedIP, RestrictedIPDto>(); #endregion #region RestrictedAccessTime CreateMap<RestrictedAccessTime, RestrictedAccessTimeDto>() .ForMember(dest => dest.Date, opt => opt.MapFrom(src => src.Date.HasValue ? src.Date.Value.ToShortDateString() : "No Restriction")) .ForMember(dest => dest.FromTime, opt => opt.MapFrom(src => src.FromTime.ToString("hh\\:mm\\:ss"))) .ForMember(dest => dest.ToTime, opt => opt.MapFrom(src => src.ToTime.ToString("hh\\:mm\\:ss"))); #endregion } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Threading.Tasks; using static PuddingWolfLoader.Framework.Util.PluginLoader; namespace XQSimulator.Model { [PropertyChanged.AddINotifyPropertyChangedInterface] public class Plugin { public string PluginName { get; set; } = ""; public string PluginVersion { get; set; } = ""; public string PluginAuthor { get; set; } = ""; public string PluginDesc { get; set; } = ""; internal IntPtr ProcessPtr; public bool Enable { get; set; } = false; } }
using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using stottle_shop_api.Shop.Repositories; namespace stottle_shop_api.Shop { public static class ShopModule { public static void AddShopModule(this IServiceCollection services, string connectionString) { var mongoUrl = new MongoUrl(connectionString); services.AddTransient(ctx => new MongoClient(mongoUrl).GetDatabase(mongoUrl.DatabaseName)); services.AddTransient<IReadShops, MongoRepository>(); services.AddTransient<IWriteShops, MongoRepository>(); } } }
using CheckMySymptoms.Flow.ScreenSettings.Views; using CheckMySymptoms.Forms.View; namespace CheckMySymptoms.Flow.Requests { public class DefaultRequest : RequestBase { public override ViewType ViewType { get; set; } public override ViewBase View => throw new System.NotImplementedException(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SignalR.Client.Hubs; using SignalRConsole.SignalR.MessengerHub; using SignalR.Hosting.Self; using SignalR; using System.Threading.Tasks; namespace SignalRConsole { class Program { static void Main(string[] args) { //var connection = new HubConnection("http://192.168.1.180:7001/"); //var connection = new HubConnection("http://192.168.1.180:8003/"); var connection = new HubConnection("http://localhost:9616/"); SignalRConsole.SignalR.MessengerHub.Message message = new SignalR.MessengerHub.Message() { Content = "Moo", Duration = 500, Title = "Hello Title" }; var myHub = connection.CreateProxy("messenger"); connection.Start().Wait(); Object[] myData = { (Object)message, "sourcing" }; myHub.Invoke("broadCastMessage", myData); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericScale { class Scale<T> where T : IComparable { public T Left { get; set; } public T Right { get; set; } public Scale(T left, T right) { Left = left; Right = right; } public T GetHeavier() { T value = default(T); int a = Left.CompareTo(Right); if (a == 0) value = default(T); else if (a == -1) value = Right; else if (a == 1) value = Left; return value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using PowerShapeDotNet.Enums; using PowerShapeDotNet.Macros; namespace PowerShapeDotNet.Objects { /// <summary> /// class for Solid Torus /// </summary> public class PSDNObjectSolidTorus : PSDNObjectSolid { #region PROPIERTIES /// <summary> /// Gets or sets the major radius of a torus /// </summary> /// <value> /// The major radius of a torus /// </value> public float MajorRadius { get { return psMacros.Solid_MajorRadius(ObjectName); } set { this.Select(true); psMacros.SendMacro("MODIFY", "MAJOR_RADIUS " + value.ToString(), "ACCEPT"); } } /// <summary> /// Gets or sets the minor radius of a torus /// </summary> /// <value> /// The minor radius of a torus /// </value> public float MinorRadius { get { return psMacros.Solid_MinorRadius(ObjectName); } set { this.Select(true); psMacros.SendMacro("MODIFY", "MINOR_RADIUS " + value.ToString(), "ACCEPT"); } } #endregion #region CONSTRUCTORS /// <summary> /// Initializes a new instance of the <see cref="PSDNObjectSolidTorus"/> class. /// </summary> /// <param name="state">The state.</param> /// <param name="index">The index.</param> public PSDNObjectSolidTorus(ObjectState state, int index) : base(state, index) { } /// <summary> /// Initializes a new instance of the <see cref="PSDNObjectSolidTorus"/> class. /// </summary> /// <param name="typeObject">The type object.</param> /// <param name="nameObject">The name object.</param> public PSDNObjectSolidTorus(TypeObject typeObject, string nameObject) : base (typeObject, nameObject) { } /// <summary> /// Initializes a new instance of the <see cref="PSDNObjectSolidTorus"/> class. /// </summary> /// <param name="typeObject">The type object.</param> /// <param name="idObject">The identifier object.</param> public PSDNObjectSolidTorus(TypeObject typeObject, int idObject) : base(typeObject, idObject) { } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using TestApplicationDomain.DTO; namespace TestApplicationInterface.Service { public interface IBookingService { Task<bool> SaveBooking(BookingDto booking); } }
using System; using System.IO; using FluentAssertions; using NUnit.Framework; using VH.Core.Configuration.AKSKeyVaultFileProvider; namespace VH.Core.Configuration.UnitTests.AKSKeyVaultFileProvider.TheTheAksKeyVaultSecretDirectoryInfo { public class when_given_DirectoryInfo_that_does_not_exist { private AksKeyVaultSecretDirectoryInfo _sut; private DirectoryInfo _directoryInfo; [SetUp] public void SetUp() { var existingTempFolder = TempFolderFactory.CreateNonExistingTempFolder(); _directoryInfo = new DirectoryInfo(existingTempFolder); _sut = new AksKeyVaultSecretDirectoryInfo(_directoryInfo); } [Test] public void should_map_DirectoryInfo_correctly() { _sut.Exists.Should().Be(_directoryInfo.Exists); _sut.Length.Should().Be(-1); _sut.PhysicalPath.Should().Be(_directoryInfo.FullName); _sut.Name.Should().Be(_directoryInfo.Name); _sut.LastModified.Should().Be(_directoryInfo.LastWriteTimeUtc); _sut.IsDirectory.Should().BeTrue(); } [Test] public void should_throw_InvalidOperationException_upon_calling_CreateReadStream() { var action = new Action(() => _sut.CreateReadStream()); action.Should().Throw<InvalidOperationException>(); } } }
using Ghost.Extensions; using System; using UnityEngine; namespace RO { [Serializable] public class CameraPointLinkInfo { public float angle; public CameraPoint cp1; public CameraPoint cp2; public Vector3 expand = Vector3.get_zero(); public bool weightOnX; public bool weightOnZ; public int priority; public CameraPoint tempCP { get; private set; } public bool valid { get { return null != this.cp1 && !this.cp1.invalidate && null != this.cp2 && !this.cp2.invalidate && (this.weightOnX || this.weightOnZ); } } private void InitTempCP(Transform parent) { if (null == this.tempCP) { this.tempCP = new GameObject("cp_link").AddComponent<CameraPoint>(); this.tempCP.get_transform().set_parent(parent); this.tempCP.get_transform().set_position((this.cp1.position + this.cp2.position) / 2f); this.tempCP.get_transform().set_eulerAngles(new Vector3(0f, this.angle, 0f)); this.tempCP.type = AreaTrigger.Type.RECTANGE; this.tempCP.size = new Vector2(Mathf.Abs(this.cp1.position.x - this.cp2.position.x) + this.expand.x, Mathf.Abs(this.cp1.position.z - this.cp2.position.z) + this.expand.z); this.tempCP.info = new CameraController.Info(); this.tempCP.focusViewPortValid = (this.cp1.focusViewPortValid || this.cp2.focusViewPortValid); this.tempCP.rotationValid = (this.cp1.rotationValid || this.cp2.rotationValid); this.tempCP.priority = this.priority; this.tempCP.forLink = true; } } public bool Check(Transform t, Transform parent = null) { if (!this.valid) { return false; } this.InitTempCP(parent); return this.tempCP.Check(t); } public void UpdateTempCameraPoint(CameraController.Info originalDefaultInfo, Transform t, Transform parent = null) { this.InitTempCP(parent); float t2 = 0.5f; if (this.weightOnX && this.weightOnZ) { float num = Vector2.Distance(t.get_position().XZ(), this.cp1.position.XZ()); float num2 = Vector2.Distance(t.get_position().XZ(), this.cp2.position.XZ()); t2 = num / (num + num2); } else if (this.weightOnX) { float num3; if (this.angle == 0f) { t2 = Mathf.Abs(t.get_position().x - this.cp1.position.x) / Mathf.Abs(this.cp2.position.x - this.cp1.position.x); } else if (this.tempCP.TryGetDistanceInRectX1(t.get_position(), out num3)) { t2 = num3 / this.tempCP.size.x; } } else if (this.weightOnZ) { float num4; if (this.angle == 0f) { t2 = Mathf.Abs(t.get_position().z - this.cp1.position.z) / Mathf.Abs(this.cp2.position.z - this.cp1.position.z); } else if (this.tempCP.TryGetDistanceInRectZ1(t.get_position(), out num4)) { t2 = num4 / this.tempCP.size.y; } } CameraController.Info info = this.cp1.info; CameraController.Info info2 = this.cp2.info; if (!this.cp1.focusViewPortValid || !this.cp1.rotationValid) { info = info.CloneSelf(); if (!this.cp1.focusViewPortValid) { info.focus = originalDefaultInfo.focus; info.focusOffset = originalDefaultInfo.focusOffset; info.focusViewPort = originalDefaultInfo.focusViewPort; } if (!this.cp1.rotationValid) { info.rotation = originalDefaultInfo.rotation; } } if (!this.cp2.focusViewPortValid || !this.cp2.rotationValid) { info2 = info2.CloneSelf(); if (!this.cp2.focusViewPortValid) { info2.focus = originalDefaultInfo.focus; info2.focusOffset = originalDefaultInfo.focusOffset; info2.focusViewPort = originalDefaultInfo.focusViewPort; } if (!this.cp2.rotationValid) { info2.rotation = originalDefaultInfo.rotation; } } CameraController.Info.Lerp(info, info2, this.tempCP.info, t2); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //Written by Mason Eastman public class CameraFollow : MonoBehaviour { //allows for the correct gameobject that the camera should follow to be set from the inspector public Transform trackedObject; //Camera's position is tied to the center of the player's position //updates every frame void Update() { transform.position = new Vector3(trackedObject.position.x, trackedObject.position.y, transform.position.z); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class ScreenFader : MonoBehaviour { [SerializeField] private CanvasGroup faderCanvasGroup; [SerializeField] private float fadeDuration = 1f; private bool isFading = false; private Coroutine fadeCoroutine; public void StartFadeOut(Action fadeInFinishedCallback = null) { fadeCoroutine = StartCoroutine(Fade(1, fadeInFinishedCallback)); } public void StartFadeIn(Action fadeInFinishedCallback = null) { fadeCoroutine = StartCoroutine(Fade(0, fadeInFinishedCallback)); } private IEnumerator Fade(float finalAlpha, Action fadeFinishedCallback = null) { isFading = true; // Make sure the CanvasGroup blocks raycasts into the scene so no more input can be accepted. faderCanvasGroup.blocksRaycasts = true; // Calculate how fast the CanvasGroup should fade based on it's current alpha, it's final alpha and how long it has to change between the two. float fadeSpeed = Mathf.Abs(faderCanvasGroup.alpha - finalAlpha) / fadeDuration; // While the CanvasGroup hasn't reached the final alpha yet... while (!Mathf.Approximately(faderCanvasGroup.alpha, finalAlpha)) { // ... move the alpha towards it's target alpha. faderCanvasGroup.alpha = Mathf.MoveTowards(faderCanvasGroup.alpha, finalAlpha, fadeSpeed * Time.unscaledDeltaTime); // Wait for a frame then continue. yield return null; } // Set the flag to false since the fade has finished. isFading = false; // Stop the CanvasGroup from blocking raycasts so input is no longer ignored. faderCanvasGroup.blocksRaycasts = false; if (fadeFinishedCallback != null) fadeFinishedCallback.Invoke(); } }
namespace EnterpriseRequests.Models { public class CachedUser { public CachedUser() { } public CachedUser(string login) { SAPId = login; DisplayName = login; } public string SAPId { get; set; } public string DisplayName { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using CompareAttribute = System.ComponentModel.DataAnnotations.CompareAttribute; namespace MVC.Samples.Web.Areas.Ravi.Models { [Serializable] public class RaviUserModel { [Required] public string EmployeeCode { get; set; } [Required] [MinLength(4)] public string Name { get; set; } [Required(ErrorMessage ="Password is requierd")] [DataType(DataType.Password)] public string Password { get; set; } [Required(ErrorMessage ="Conform Password is requierd")] [DataType(DataType.Password)] [Compare("Password")] public string ConformPassword { get; set; } [Required(ErrorMessage = "The Age value must be 18 to 100")] [Range(18, 100)] public int Age { get; set; } [Required(ErrorMessage = "Email is required")] [EmailAddress(ErrorMessage = "Invalid Email Address")] public string Email { get; set; } public string Marital { get; set; } } }
using Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using ZrSoft; namespace mvcProject.ashx { /// <summary> /// upload 的摘要说明 /// </summary> public class upload1 : IHttpHandler { public void ProcessRequest(HttpContext context) { try { string fileId = ""; context.Response.ContentType = "text/plain"; // context.Response.Write("Hello World"); foreach (string f in context.Request.Files.AllKeys) { HttpPostedFile pfile = context.Request.Files[f]; string photoName = Utils.GenerateCheckCode(6) + pfile.FileName; //若文件夹不存在则新建文件夹 if (!Directory.Exists(context.Server.MapPath("~/Content/upload/" + DateTime.Now.Year.ToString()))) { Directory.CreateDirectory(context.Server.MapPath("~/Content/upload/" + DateTime.Now.Year.ToString())); //新建文件夹 } //若文件夹不存在则新建文件夹 if (!Directory.Exists(context.Server.MapPath("~/Content/upload/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.ToString("MM-dd")))) { Directory.CreateDirectory(context.Server.MapPath("~/Content/upload/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.ToString("MM-dd"))); //新建文件夹 } string lujing = context.Server.MapPath("~/Content/upload/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.ToString("MM-dd")) + "/" + photoName; pfile.SaveAs(lujing); ///*保存入数据库*/ //Basics_Attachment a = new Basics_Attachment(); //a.Id = Utils.GetNewDateID(); //a.AdminId = ""; //a.PubDate = DateTime.Now; //a.Name = pfile.FileName; //a.Url = "/Content/upload/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.ToString("MM-dd") + "/" + photoName; //a.OutId = context.Request["OutId"]; //if (!string.IsNullOrEmpty(context.Request["ProjectId"])) //{ // a.Type = context.Request["ProjectId"]; //} //a.Save(); //fileId += a.Id + ","; } context.Response.Write(fileId.Substring(0, fileId.Length - 1)); } catch (Exception e) { context.Response.Write("false"); } } public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.AppServices.DataContracts.DomesticTicket { public class CoordinationDto : OrderDto { /// <summary> /// 协调信息 /// </summary> public virtual IList<CoordinationLogDto> CoordinationLogs { get; set; } } }
using System; namespace PreserveSpaceReverseString.Classes { public class PreservingSpaceClass { public string ReverseInputStr(string input) { char[] inputArr = input.ToCharArray(); char[] result = new char[inputArr.Length]; for (int i = 0; i < inputArr.Length; i++) { if(inputArr[i] == '$') { result[i] = '$'; } } int j = result.Length - 1; for (int i = 0; i < inputArr.Length; i++) { if(inputArr[i] != '$') { if(result[j] == '$') { j--; } result[j] = inputArr[i]; j--; } } string sendResults = new string(result); return sendResults; } } }
using System; namespace Attributes { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class AuthorAttribute : Attribute { public String Name { get; set; } public String Version { get; set; } public AuthorAttribute(String name): this(name, ""){} public AuthorAttribute(String name, String version) { Name = name; Version = version; } public override String ToString() { return $"{Name} {Version}"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace UrTLibrary.Bsp.Elements { public class Plane : BspElement { public float[] Normal; public float Distance; public Plane() { base.ElementSize = 16; } internal override void Read(BinaryReader reader) { this.Normal = new float[3]; for (int i = 0; i < 3; i++) this.Normal[i] = reader.ReadSingle(); this.Distance = reader.ReadSingle(); } internal override void Write(BinaryWriter writer) { foreach (float f in this.Normal) writer.Write(f); writer.Write(this.Distance); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Diagnostics; using System.Web.UI.WebControls; using ASPBinding.Services; using Binding.Services; using Binding.ControlWrappers; using ASPBinding.ControlWrappers; using System.Reflection; using System.Web.Configuration; using Binding.Interfaces; using Binding; namespace Binding { //TODO: These extensions are useful across platforms and shouldn't be asp specific. Going with this approach temporarily //whilst I sort out the service injection to the binders. public static class BindingContainerExtensions { /// <summary> /// Create and execute a programmatic binding /// </summary> /// <param name="bindingContainer"></param> /// <param name="control">The control that should be bound</param> /// <param name="targetProperty">The property on the control to which to bind</param> /// <param name="path">Path to the source data</param> public static void CreateBinding(this IBindingContainer bindingContainer, Control control, string targetProperty, string path) { CreateBinding(bindingContainer, control, targetProperty, new Options { Path = path }); } /// <summary> /// Create and execute a programmatic binding /// </summary> /// <param name="bindingContainer"></param> /// <param name="control">The control that should be bound</param> /// <param name="targetProperty">The property on the control to which to bind</param> /// <param name="bindingOptions">Binding options including the path to the data source</param> public static void CreateBinding(this IBindingContainer bindingContainer, Control control, string targetProperty, Options bindingOptions) { object value = BindingHelpers.Bind(control, bindingOptions, targetProperty); PropertyInfo pInfo = control.GetType().GetProperty(targetProperty); pInfo.SetValue(control, value, null); } public static StateBag GetStateBag(this IBindingContainer bindingContainer) { StateBag viewState = (StateBag)bindingContainer.GetType().GetProperty("ViewState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(bindingContainer, null); return viewState; } public static void RegisterForBinding(this IBindingContainer bindingContainer, StateMode stateMode) { BinderBase binder = BindingHelpers.CreateBinder(bindingContainer, stateMode); } public static void RegisterForBinding(this IBindingContainer bindingContainer) { BinderBase binder = BindingHelpers.CreateBinder(bindingContainer); } /// <summary> /// Call this to initiate Unbind /// </summary> /// <remarks> /// Only required if UpdateSourceTrigger is Explicit. /// DO NOT CALL BEFORE LOAD in the PLC /// </remarks> /// <param name="bindingContainer"></param> public static void Unbind(this IBindingContainer bindingContainer) { BinderBase binder = BindingHelpers.CreateBinder(bindingContainer); binder.ExecuteUnbind(); } } public static class BindingHelpers { private const string STATE_MODE_KEY = "BindingStateMode"; private const string UPDATE_SOURCE_TRIGGER_KEY = "UpdateSourceTrigger"; private const StateMode DEFAULT_STATE_MODE = StateMode.Persist; private const string NEED_BINDING_OPTIONS_CONTROL = "BindR requires a BindingOptionsControl on the page. The BindingOptions must appear before any controls that need it."; private const string NEED_BINDING_OPTIONS_RESOURCES = "BindR requires a BindingOptionsControl on the page and requires the binding options to have a Resources collection. The BindingOptions must appear before any controls that need it."; private const string NEED_BINDING_RESOURCE = "BindR requires a BindingOptionsControl on the page and requires the binding options to have a Resources collection with a Resource that matches the ID specified by BindR. The BindingOptions must appear before any controls that need it."; #region Commands #region Shortcuts /// <summary> /// Shorthand call for BindCommand /// </summary> /// <param name="control"></param> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> public static string BindC(this object control, string sourcePath) { return BindCommand(control,sourcePath); } /// <summary> /// Shorthand call for BindCommand /// </summary> /// <param name="control"></param> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> public static string BindC(this object control, object bindingOptions) { return BindCommand(control, bindingOptions); } /// <summary> /// Shorthand call for BindCommand /// </summary> /// <param name="control"></param> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> public static string BindC(this object control, Options bindingOptions) { return BindCommand(control, bindingOptions.Path); } #endregion /// <summary> /// Bind to a command /// <remarks>Allows the use of the slower but more succinct binding syntax</remarks> /// </summary> /// <param name="control"></param> /// <param name="bindingOptions">Options for binding. Only the Path property is utilised for command bindings</param> public static string BindCommand(this object control, object bindingOptions) { Options options = new Options(); options.Load(bindingOptions); return BindCommand(control, options.Path); } /// <summary> /// Bind to a command /// </summary> /// <param name="control"></param> /// <param name="sourcePath"></param> /// <param name="targetPath"></param> public static string BindCommand(this object control, string sourcePath) { return BindCommand(control, new Options { Path = sourcePath }); } /// <summary> /// Bind to a command /// </summary> /// <remarks> /// Binding via an options object is supported to allow for a more natural syntax between data and command bindings /// </remarks> /// <param name="control"></param> /// <param name="bindingOptions">Options for binding. Only the Path property is utilised for command bindings. /// </param> public static string BindCommand(this object control, Options bindingOptions) { Control ctrl = control as Control; IBindingContainer bindingContainer = ctrl.Page as IBindingContainer; BinderBase binder = CreateBinder(bindingContainer); binder.ExecuteCommandBind(new WebformControl(ctrl), bindingOptions); return "return true"; } #endregion #region Resource Binding /// <summary> /// Shorthand call for BindResource /// </summary> /// <param name="control"></param> /// <param name="resourceID"></param> /// <returns></returns> public static object BindR(this object control, string resourceID) { return BindResource(control, resourceID); } /// <summary> /// Bind using a global Resource binding /// </summary> /// <param name="control"></param> /// <param name="resourceID">The id of the binding which should be used</param> /// <returns></returns> public static object BindResource(this object control, string resourceID) { Control ctrl = control as Control; IControlService service = new WebformsControlService(); IBindingTarget target = new WebformControl(ctrl.Page); WebformControl webFormControl = service.FindControlRecursive(target, typeof(BindingOptionsControl)) as WebformControl; BindingOptionsControl bindingOptions = webFormControl.Control as BindingOptionsControl; if (bindingOptions == null) throw new InvalidOperationException(NEED_BINDING_OPTIONS_CONTROL); if (bindingOptions.Resources == null) throw new InvalidOperationException(NEED_BINDING_OPTIONS_RESOURCES); Options options = bindingOptions.Resources.Where(r => r.ID == resourceID).FirstOrDefault(); if (options == null) if (bindingOptions.Resources == null) throw new InvalidOperationException(NEED_BINDING_RESOURCE); if (options.Mode == BindingMode.Command) { BindCommand(control, options); return null; } else return Bind(control, options); } #endregion #region Data Binding /// <summary> /// Bind with the default options /// </summary> /// <param name="control"></param> /// <param name="sourcePath"></param> /// <returns></returns> public static object Bind(this object control, string sourcePath) { return Bind(control, new Options { Path=sourcePath }); } /// <summary> /// Bind and specify options for the bind. Allows for a cleaner binding syntax by taking advantages of anonymous types and reflection /// </summary> /// <remarks> /// Slower than explicitly creating a Options object or using a binding resource /// </remarks> /// <param name="control"></param> /// <param name="bindingOptions"></param> /// <returns></returns> public static object Bind(this object control, object bindingOptions) { Options options = new Options(); options.Load(bindingOptions); return Bind(control, options); } /// <summary> /// Bind and specify options for the bind. /// </summary> /// <param name="control"></param> /// <param name="bindingOptions"></param> /// <returns></returns> public static object Bind(object control, Options bindingOptions) { return Bind(control, bindingOptions, null); } /// <summary> /// Bind and specify options for the bind. /// </summary> /// <param name="control"></param> /// <param name="bindingOptions"></param> /// <returns></returns> public static object Bind(object control, Options bindingOptions, string propertyName) { Control ctrl = control as Control; WebformControl wrappedControl = new WebformControl(ctrl); IBindingContainer bindingContainer = ctrl.Page as IBindingContainer; BinderBase binder = CreateBinder(bindingContainer); object bindingResult = null; if (ctrl != null && bindingContainer != null) { IDataItemContainer dataItemContainer = ctrl.NamingContainer as IDataItemContainer; if (dataItemContainer != null) { WebformControl<IDataItemContainer> wrappedContainer = new WebformControl<IDataItemContainer>((Control)dataItemContainer); if (string.IsNullOrEmpty(propertyName)) bindingResult = binder.ExecuteBind(wrappedControl, wrappedContainer, bindingOptions); else bindingResult = binder.ExecuteBind(wrappedControl, wrappedContainer, bindingOptions, propertyName); } else { if (string.IsNullOrEmpty(propertyName)) bindingResult = binder.ExecuteBind(wrappedControl, bindingOptions); else bindingResult = binder.ExecuteBind(wrappedControl, bindingOptions, propertyName); } } return bindingResult; } #endregion /// <summary> /// Create a Binder /// </summary> /// <remarks> /// Specifying which binder to use can be acheived by placing a BindingOptionsControl on the page or /// using the BindingStateMode config key. BindingOptionsControl takes precedence. A default ViewStateBinder /// is used in the absence of the above. /// </remarks> /// <param name="bindingContainer"></param> /// <returns></returns> public static BinderBase CreateBinder(IBindingContainer bindingContainer) { //Create a binder based on: //A) The binder specified by a binding options control BinderBase binder = null; if (!TryGetBinderFromOptionsControl(bindingContainer, out binder)) { //B) The binder specified in the config if (!TryGetBinderFromConfig(bindingContainer, out binder)) { //C) the default binder is created. binder = CreateBinder(bindingContainer, DEFAULT_STATE_MODE); } } //Set the update source trigger on: UpdateSourceTrigger updateSourceTrigger = UpdateSourceTrigger.PostBack; //A) The updateSourceTrigger specified by a binding options control if (!TryGetUpdateSourceTriggerOptionsControl(bindingContainer, out updateSourceTrigger)) { //B) The updateSourceTrigger specified in the config TryGetUpdateSourceTriggerFromConfig(bindingContainer, out updateSourceTrigger); } binder.UpdateSourceTrigger = updateSourceTrigger; return binder; } /// <summary> /// Create a binder and explicitly specify the StateMode /// </summary> /// <param name="bindingContainer"></param> /// <param name="stateMode"></param> /// <returns></returns> public static BinderBase CreateBinder(IBindingContainer bindingContainer, StateMode stateMode) { BinderBase binder = null; IDataStorageService dataStorageService = GetDataStorageService(bindingContainer); if (stateMode == StateMode.Recreate) binder = new StatelessBinder(bindingContainer, dataStorageService, new WebformsControlService()); else binder = new ViewStateBinder(bindingContainer, new ViewStateStorageService(bindingContainer.GetStateBag()), new WebformsControlService()); return binder; } private static IDataStorageService GetDataStorageService(IBindingContainer bindingContainer) { IDataStorageService dataStorageService = null; IBindingServicesProvider serviceProvider = bindingContainer as IBindingServicesProvider; if (serviceProvider != null) dataStorageService = serviceProvider.DataStorageService; else dataStorageService = new ViewStateStorageService(bindingContainer.GetStateBag()); return dataStorageService; } private static IControlService GetControlService(IBindingContainer bindingContainer) { IControlService controlService = null; IBindingServicesProvider serviceProvider = bindingContainer as IBindingServicesProvider; if (serviceProvider != null) controlService = serviceProvider.ControlService; else controlService = new WebformsControlService(); return controlService; } private static bool TryGetBinderFromConfig(IBindingContainer bindingContainer, out BinderBase binder) { bool result = false; binder = null; string stateModeStr = WebConfigurationManager.AppSettings[STATE_MODE_KEY]; if (!string.IsNullOrEmpty(stateModeStr)) { StateMode stateModeEnum = StateMode.Persist; if (stateModeEnum.TryParse(stateModeStr)) { binder = CreateBinder(bindingContainer, stateModeEnum); result = true; } } return result; } private static bool TryGetUpdateSourceTriggerFromConfig(IBindingContainer bindingContainer, out UpdateSourceTrigger updateSourceTrigger) { bool result = false; updateSourceTrigger = UpdateSourceTrigger.PostBack; string updateSourceTriggerStr = WebConfigurationManager.AppSettings[UPDATE_SOURCE_TRIGGER_KEY]; if (!string.IsNullOrEmpty(updateSourceTriggerStr)) { if (updateSourceTrigger.TryParse(updateSourceTriggerStr)) { result = true; } } return result; } private static bool TryGetUpdateSourceTriggerOptionsControl(IBindingContainer bindingContainer, out UpdateSourceTrigger updateSourceTrigger) { bool result = false; updateSourceTrigger = UpdateSourceTrigger.PostBack; BindingOptionsControl bindingOptionsControl = null; if (TryGetBindingOptionsControl(bindingContainer, out bindingOptionsControl)) { updateSourceTrigger = bindingOptionsControl.UpdateSourceTrigger; result = true; } return result; } private static bool TryGetBinderFromOptionsControl(IBindingContainer bindingContainer, out BinderBase binder) { bool result = false; binder = null; BindingOptionsControl bindingOptionsControl = null; if (TryGetBindingOptionsControl(bindingContainer, out bindingOptionsControl)) { binder = CreateBinder(bindingContainer, bindingOptionsControl.StateMode); result = true; } return result; } private static bool TryGetBindingOptionsControl(IBindingContainer bindingContainer, out BindingOptionsControl bindingOptionsControl) { bool result = false; bindingOptionsControl = null; Page page = bindingContainer as Page; if (page == null) throw new InvalidOperationException("This method binding extension can only be used within the context of an asp.net page"); IBindingTarget target = new WebformControl(page); IControlService controlService = GetControlService(bindingContainer); WebformControl wrappedOptionsControl = controlService.FindControlRecursive(target, typeof(BindingOptionsControl)) as WebformControl; if (wrappedOptionsControl != null) { bindingOptionsControl = wrappedOptionsControl.Control as BindingOptionsControl; if (bindingOptionsControl != null) { result = true; } } return result; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using LinqToDB.Data; using LinqToDB.Mapping; namespace Core.Services { public interface IDataConnection { int CommandTimeout { get; set; } void QueryHint(string hint); DataConnectionTransaction BeginTransaction(); DataConnectionTransaction BeginTransaction(IsolationLevel isolationLevel); BulkCopyRowsCopied BulkCopy<T>(BulkCopyOptions options, IEnumerable<T> source) where T: class; BulkCopyRowsCopied BulkCopy<T>(IEnumerable<T> source) where T: class; BulkCopyRowsCopied BulkCopy<T>(int maxBatchSize, IEnumerable<T> source) where T : class; void CommitTransaction(); int Delete<T>(T obj); void Dispose(); int Execute(string sql); int Execute(string sql, object parameters); int Execute(string sql, params DataParameter[] parameters); T Execute<T>(string sql); T Execute<T>(string sql, DataParameter parameter); T Execute<T>(string sql, object parameters); T Execute<T>(string sql, params DataParameter[] parameters); int ExecuteProc(string sql, params DataParameter[] parameters); T ExecuteProc<T>(string sql, params DataParameter[] parameters); DataReader ExecuteReader(string sql); DataReader ExecuteReader(string sql, CommandType commandType, CommandBehavior commandBehavior, params DataParameter[] parameters); DataReader ExecuteReader(string sql, DataParameter parameter); DataReader ExecuteReader(string sql, object parameters); DataReader ExecuteReader(string sql, params DataParameter[] parameters); IQueryable<T> GetTable<T>() where T : class; int Insert<T>(T obj, string tableName = null, string databaseName = null, string schemaName = null); int InsertOrReplace<T>(T obj); object InsertWithIdentity<T>(T obj); int Merge<T>(bool delete, IEnumerable<T> source, string tableName = null, string databaseName = null, string schemaName = null) where T : class; int Merge<T>(IEnumerable<T> source, string tableName = null, string databaseName = null, string schemaName = null) where T : class; int Merge<T>(IQueryable<T> source, Expression<Func<T, bool>> predicate, string tableName = null, string databaseName = null, string schemaName = null) where T : class; IEnumerable<T> Query<T>(Func<IDataReader, T> objectReader, string sql); IEnumerable<T> Query<T>(Func<IDataReader, T> objectReader, string sql, object parameters); IEnumerable<T> Query<T>(Func<IDataReader, T> objectReader, string sql, params DataParameter[] parameters); IEnumerable<T> Query<T>(string sql); IEnumerable<T> Query<T>(string sql, DataParameter parameter); IEnumerable<T> Query<T>(string sql, object parameters); IEnumerable<T> Query<T>(string sql, params DataParameter[] parameters); IEnumerable<T> Query<T>(T template, string sql, object parameters); IEnumerable<T> Query<T>(T template, string sql, params DataParameter[] parameters); IEnumerable<T> QueryProc<T>(Func<IDataReader, T> objectReader, string sql, params DataParameter[] parameters); IEnumerable<T> QueryProc<T>(string sql, params DataParameter[] parameters); void RollbackTransaction(); CommandInfo SetCommand(string commandText, object parameters); int Update<T>(T obj); } }
using Microsoft.Dynamics365.UIAutomation.Browser; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using TechTalk.SpecFlow; using Vantage.Automation.VaultUITest.Context; using Vantage.Automation.VaultUITest.Helpers; namespace Vantage.Automation.VaultUITest.Steps { [Binding] public class FamilyTreeTabSteps : BaseSteps { private readonly UIContext _uiContext; private const string _XpathFamilyTreeFrameId = "//*[@id='WebResource_Hierarchy']"; private const string _XpathFamilyTreeRecord = "//tr[@aria-level={0}]//div[text()='{1}']"; private const string _XpathFamilyTreeRecordExpandButton = "//tr//div[text()='{0}']//ancestor::tr//div[contains(@class,'dx-treelist-collapsed')]"; private const string _XpathFamilyTreeRecordDragArea = "//tr//div[text()='{0}']//ancestor::tr/td[contains(@class,'dx-command-drag')]"; private const string _XpathFamilyTreeRecordRow = "//tr//div[text()='{0}']//ancestor::tr"; private const string _XpathFamilyTreeRecordSelectBox = "//tr//div[text()='{0}']//ancestor::tr//div[contains(@class,'dx-select-checkbox')]"; private const string _XpathDownloadFilesButton = "//div[contains(@aria-label,'Download Selected Files')]"; public FamilyTreeTabSteps(UIContext context, ScenarioContext scenarioContext) : base(scenarioContext) { _uiContext = context; } [Then("the Family Tree contains record with name '(.*)' at level (.*)")] public void VerifyFamilyTree(string recordName, int level) { var frameElement = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(_XpathFamilyTreeFrameId)); _uiContext.WebClient.Browser.Driver.SwitchTo().Frame(frameElement); recordName = TransformString(recordName); string recordXpath = string.Format(_XpathFamilyTreeRecord, level, recordName); var element = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(recordXpath)); _uiContext.WebClient.Browser.Driver.SwitchTo().ParentFrame(); if (element == null) { Assert.Fail($"Could not find a record with name '{recordName}' at level {level}"); } } [When("I expand the Family Tree record with name '(.*)'")] public void ExpandFamilyTreeRecord(string recordName) { var frameElement = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(_XpathFamilyTreeFrameId)); _uiContext.WebClient.Browser.Driver.SwitchTo().Frame(frameElement); recordName = TransformString(recordName); string recordXpath = string.Format(_XpathFamilyTreeRecordExpandButton, recordName); var expandButton = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(recordXpath)); if (expandButton == null) { Assert.Fail($"Could not find a record with name '{recordName}'"); } expandButton.Click(); _uiContext.WebClient.Browser.Driver.SwitchTo().ParentFrame(); } [Then("I select record with name '(.*)' and Download Files")] public void DownloadFile(string recordName) { var frameElement = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(_XpathFamilyTreeFrameId)); _uiContext.WebClient.Browser.Driver.SwitchTo().Frame(frameElement); recordName = TransformString(recordName); string recordXpath = string.Format(_XpathFamilyTreeRecordSelectBox, recordName); var checkBox = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(recordXpath)); if (checkBox == null) { Assert.Fail($"Could not find a record with name '{recordName}'"); } checkBox.Click(); BrowserFileHelper browserFileHelper = new BrowserFileHelper(); int oldFileCount = browserFileHelper.GetDownloadFolderFileCount(); var downloadFilesButton = _uiContext.WebClient.Browser.Driver.WaitUntilClickable(By.XPath(_XpathDownloadFilesButton)); downloadFilesButton.Click(); _uiContext.XrmApp.ThinkTime(5000); Assert.IsTrue(browserFileHelper.GetDownloadFolderFileCount() > oldFileCount, "File was not downloaded"); _uiContext.WebClient.Browser.Driver.SwitchTo().ParentFrame(); } [When("I drag the Family Tree record with name '(.*)' to the record with name '(.*)'")] public void DragRecord(string recordName, string targetName) { var frameElement = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(_XpathFamilyTreeFrameId)); _uiContext.WebClient.Browser.Driver.SwitchTo().Frame(frameElement); recordName = TransformString(recordName); targetName = TransformString(targetName); string dragAreaXpath = string.Format(_XpathFamilyTreeRecordDragArea, recordName); string dragToXpath = string.Format(_XpathFamilyTreeRecordRow, targetName); try { var dragArea = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(dragAreaXpath)); var targetArea = _uiContext.WebClient.Browser.Driver.WaitUntilAvailable(By.XPath(dragToXpath)); var action = new Actions(_uiContext.WebClient.Browser.Driver); action.MoveToElement(dragArea).ClickAndHold(dragArea).MoveToElement(targetArea).Release(targetArea).Build().Perform(); } catch { Assert.Fail($"Could not find a record with name '{recordName}' or '{targetName}'"); } finally { _uiContext.WebClient.Browser.Driver.SwitchTo().ParentFrame(); } } private string TransformString(string input) { if (input.StartsWith("[") && input.Length > 2 && ScenarioContext.ContainsKey(input.Substring(1, input.Length - 2))) { input = ScenarioContext[input.Substring(1, input.Length - 2)].ToString(); } else { input = new StringTransformer().Transform(input); } return input; } } }
//------------------------------------------------------------------------------ // // CosmosEngine - The Lightweight Unity3D Game Develop Framework // // Version 0.8 (20140904) // Copyright © 2011-2014 // MrKelly <23110388@qq.com> // https://github.com/mr-kelly/CosmosEngine // //------------------------------------------------------------------------------ using System; using UnityEngine; using UnityEditor; using System.IO; using System.Reflection; using System.Collections; using System.Collections.Generic; public partial class CBuild_UI : CBuild_Base { string UIName; //UIPanel PanelRoot; GameObject AnchorObject; GameObject WindowObject; GameObject TempPanelObject; string UIScenePath; // 判断本次是否全局打包,是否剔除没用的UIlabel string public bool IsBuildAll = false; public override string GetDirectory() { return "UI"; } public override string GetExtention() { return "*.unity"; } public static event Action<CBuild_UI> BeginExportEvent; public static event Action<CBuild_UI, string, string, GameObject> ExportCurrentUIEvent; public static event Action ExportUIMenuEvent; public static event Action<CBuild_UI> EndExportEvent; public static string GetBuildRelPath(string uiName) { return string.Format("UI/{0}_UI{1}", uiName, CCosmosEngine.GetConfig("AssetBundleExt")); } public void ExportCurrentUI() { CreateTempPrefab(); if (ExportCurrentUIEvent != null) { ExportCurrentUIEvent(this, UIScenePath, UIName, TempPanelObject); } else { CBuildTools.BuildAssetBundle(TempPanelObject, GetBuildRelPath(UIName)); } DestroyTempPrefab(); } public override void BeginExport() { if (BeginExportEvent != null) { BeginExportEvent(this); } } public override void Export(string path) { UIScenePath = path; EditorApplication.OpenScene(path); if (!CheckUI(false)) return; ExportCurrentUI(); } public override void EndExport() { if (EndExportEvent != null) { EndExportEvent(this); } } void CreateTempPrefab() { TempPanelObject = (GameObject)GameObject.Instantiate(WindowObject); //if (WindowObject.GetComponent<UIPanel>() == null) //{ // // 读取UIPanel的depth, 遍历所有UI控件,将其depth加上UIPanel Depth, 以此设置层级关系 // // 如PanelRoot Depth填10, 子控件填0,1,2 打包后,子控件层级为 10 << 5 | 1 = 320, 321, 322 // foreach (UIWidget uiWidget in TempPanelObject.GetComponentsInChildren<UIWidget>(true)) // { // uiWidget.depth = (PanelRoot.depth + 15) << 5 | (uiWidget.depth + 15); // + 15是为了杜绝负数!不要填-15以上的 // } //} foreach (UIButton go in TempPanelObject.GetComponentsInChildren<UIButton>(true)) { if (go.tweenTarget != null && go.transform.FindChild(go.tweenTarget.name) != null && go.tweenTarget != go.transform.FindChild(go.tweenTarget.name).gameObject) { Debug.LogWarning(UIName + " " + go.name + " UIButton 的Target 目标不是当前UIButton 子节点 "); } } } void DestroyTempPrefab() { GameObject.DestroyImmediate(TempPanelObject); UIName = null; AnchorObject = null; WindowObject = null; TempPanelObject = null; } public bool CheckUI(bool showMsg) { //PanelRoot = GameObject.Find("UIRoot/PanelRoot").GetComponent<UIPanel>(); AnchorObject = (GameObject)GameObject.Find("UIRoot/PanelRoot/Anchor"); if (AnchorObject == null) { if (showMsg) CBuildTools.ShowDialog("找不到UIRoot/PanelRoot/Anchor"); else Debug.Log("找不到UIRoot/PanelRoot/Anchor"); return false; } if (AnchorObject.transform.childCount != 1) { if (showMsg) CBuildTools.ShowDialog("UI结构错误,Ahchor下应该只有一个节点"); else Debug.Log("UI结构错误,Ahchor下应该只有一个节点"); return false; } WindowObject = AnchorObject.transform.GetChild(0).gameObject; UIName = EditorApplication.currentScene.Substring(EditorApplication.currentScene.LastIndexOf('/') + 1); UIName = UIName.Substring(0, UIName.LastIndexOf('.')); // 確保Layer正確 bool changeLayer = false; foreach (Transform loopTrans in GameObject.FindObjectsOfType<Transform>()) { if (loopTrans.gameObject.layer != (int)CLayerDef.UI) { NGUITools.SetLayer(loopTrans.gameObject, (int)CLayerDef.UI); changeLayer = true; } } foreach (Camera cam in GameObject.FindObjectsOfType<Camera>()) { NGUITools.SetLayer(cam.gameObject, (int)CLayerDef.UI); if (cam.cullingMask != 1 << (int)CLayerDef.UI) { cam.cullingMask = 1 << (int)CLayerDef.UI; changeLayer = true; } } if (changeLayer) { EditorApplication.SaveScene(); } return true; } public static void CreateNewUI() { GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) GameObject.DestroyImmediate(mainCamera); GameObject uiRootObj = new GameObject("UIRoot"); uiRootObj.layer = (int)CLayerDef.UI; UIRoot uiRoot = uiRootObj.AddComponent<UIRoot>(); uiRoot.scalingStyle = UIRoot.Scaling.ConstrainedOnMobiles; uiRoot.manualHeight = 1920; uiRoot.manualWidth = 1080; uiRoot.fitHeight = true; uiRoot.fitWidth = true; GameObject cameraObj = new GameObject("Camera"); cameraObj.layer = (int)CLayerDef.UI; Camera camera = cameraObj.AddComponent<Camera>(); camera.clearFlags = CameraClearFlags.Skybox; camera.depth = 0; camera.backgroundColor = Color.grey; camera.cullingMask = 1 << (int)CLayerDef.UI; camera.orthographicSize = 1f; camera.orthographic = true; camera.nearClipPlane = -2f; camera.farClipPlane = 2f; camera.gameObject.AddComponent<AudioListener>(); camera.gameObject.AddComponent<UICamera>(); UIPanel uiPanel = NGUITools.AddChild<UIPanel>(uiRootObj); uiPanel.gameObject.name = "PanelRoot"; UIAnchor uiAnchor = NGUITools.AddChild<UIAnchor>(uiPanel.gameObject); GameObject windowObj = NGUITools.AddChild(uiAnchor.gameObject); windowObj.name = "Window"; Selection.activeGameObject = windowObj; } [MenuItem("CosmosEngine/UI/Create UI %&N")] public static void CreateUI() { CBuild_UI.CreateNewUI(); } [MenuItem("CosmosEngine/UI/Export Current UI %&U")] public static void ExportUIMenu() { if (ExportUIMenuEvent != null) ExportUIMenuEvent(); CBuild_UI uiBuild = new CBuild_UI(); uiBuild.IsBuildAll = false; if (!uiBuild.CheckUI(true)) return; uiBuild.BeginExport(); uiBuild.ExportCurrentUI(); uiBuild.EndExport(); } /// <summary> /// Buidl All UI Scene under Assets/_ResourcesBuild_s/ folder /// </summary> [MenuItem("CosmosEngine/UI/Export All UI")] public static void ExportAllUI() { var buildUI = new CBuild_UI(); buildUI.IsBuildAll = true; CAutoResourceBuilder.ProductExport(buildUI); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnviarDados : MonoBehaviour { public GameObject loading; public void Start() { loading.gameObject.transform.localScale = new Vector3(0, 0, 0); } public IEnumerator enviarDados() { yield return new WaitForSeconds(1); GameObject.FindGameObjectWithTag("ControladorInicial").GetComponent<ControllerCaptura>().converterParaJson(); loading.gameObject.transform.localScale = new Vector3(0, 0, 0); } public void abrirLoading() { loading.gameObject.transform.localScale = new Vector3(1, 1, 1); StartCoroutine(enviarDados()); } }
using bot_backEnd.Models; using bot_backEnd.Models.ViewModels.Statistic; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.BL.Interfaces { public interface ICategoryBL { Task<ActionResult<IEnumerable<Category>>> GetAllCategories(); List<CategoryStats> GetAllCategoryStats(); } }
using System; namespace TNBase.Objects { public static class DateTimeExtensions { public const string DEFAULT_FORMAT = "dd/MM/yyyy"; public const string BIRTHDAY_FORMAT = "dd/MM"; // No year /// <summary> /// Convert a nullable datetime to a nice format string /// </summary> /// <param name="dateTime">The nullable datetime</param> /// <param name="format">Optional format. Default: dd/MM/yyyy</param> /// <returns>the formatted date or N/a if its null</returns> public static string ToNullableNaString(this Nullable<DateTime> dateTime, string format = DEFAULT_FORMAT) { if (dateTime.HasValue) { return dateTime.Value.ToString(format); } else { return "N/a"; } } } }
using System; using Controle.Domain.Entities.Interfaces; namespace Controle.Domain.Entities { public class Entrada : IAggregateRoot<int> { public virtual int Codigo { get; set; } public virtual string Nome { get; set; } public virtual DateTime Data { get; set; } public virtual DateTime DataPrevista { get; set; } public virtual long Valor { get; set; } public virtual Usuario Usuario { get; set; } } }
using System; //using static Usings.ExampleClasses.StaticClassExample; using NonStatic = Usings.ExampleClasses.NonStaticClassExample; namespace Usings { public class Class1 { public void KindaMain() { new NonStatic().DoSmth(); //DoSmthStatic(); } } }
namespace Tookan.NET.Core { public class Agent : IAgent { public int FleetId { get; set; } public string FleetThumbImage { get; set; } public string FleetImage { get; set; } public TaskStatus Status { get; set; } public string Username { get; set; } public string Email { get; set; } public string Phone { get; set; } public int RegistrationStatus { get; set; } public string Latitude { get; set; } public int IsAvailable { get; set; } public string Longitude { get; set; } public string LastUpdatedLocationTime { get; set; } public string FleetStatusColor { get; set; } public int PendingTasks { get; set; } } }
using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Store/Store")] public class AStore : ScriptableObject { public Object Item; public List<Object> Purchased; public int ItemValue; public AIntData Cash; public void Purchase() { if (Cash.Value < ItemValue) return; Purchased.Add(Item); Cash.Value -= ItemValue; } public void AddObjectToGame() { // if (Purchased.Contains(Item)) if (Purchased.Count <= 0) return; Instantiate(Purchased[0]); Purchased.RemoveAt(0); } }
using System; namespace Instruction { public class Instructions : Instruction { public Instructions() { this.instruction = INSTRUCTION.NULL; } public override bool nextValid() { return true; } } }
using UnityEngine; using System.Collections; public class EnemyBehaviour : MonoBehaviour { public ScoreKeeper scoreKeeper; public GameObject laserPrefab; public float health = 150f; public int killPoint = 10; public float laserSpeed; [Range (0.001f, 0.06f)] public float firingRate; public AudioClip laserSound; public AudioClip destroyedSound; void Start () { scoreKeeper = GameObject.Find ("Score").GetComponent<ScoreKeeper> (); } void Update () { if (!ScoreKeeper.isGameOver && Random.value < firingRate) FireLaser (); } void OnTriggerEnter2D (Collider2D collider) { Projectile missile = collider.GetComponent<Projectile> (); if (missile) { missile.Hit (); health -= missile.GetDamage (); if (health <= 0) { Die (); } } } void Die () { AudioSource.PlayClipAtPoint (destroyedSound, this.transform.position); Destroy (gameObject); scoreKeeper.Score (killPoint); } void FireLaser () { GameObject laser = Instantiate (laserPrefab, transform.position, Quaternion.identity) as GameObject; laser.GetComponent<Rigidbody2D> ().velocity = new Vector2 (0f, -laserSpeed); AudioSource.PlayClipAtPoint (laserSound, this.transform.position); } }
using EWF.Util; using EWF.Util.Page; using System; using System.Collections.Generic; using System.Text; namespace EWF.IServices { public interface IRiverService : IDependency { Page<dynamic> GetReadData(int pageIndex,int pageSize,string STNM); /// <summary> /// 返回最新水情数据 /// add by SUN /// Date:2019-05-23 13:00 /// </summary> /// <returns></returns> List<dynamic> GetLatestRiverData(string addvcd,string type); /// <summary> /// 返回水情信息 /// add by SUN /// Date:2019-05-23 14:00 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="stcds"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="addvcd"></param> /// <param name="type"></param> /// <returns></returns> Page<dynamic> GetRiverData(int pageIndex, int pageSize, string stcds, string startDate, string endDate,string addvcd,string type); /// <summary> /// 查询分块单站水情信息 /// </summary> /// <param name="unit">所属单位</param> /// <returns></returns> IEnumerable<dynamic> GetRiverData(string unit, string stnm); /// <summary> /// 查询单站水情历史同期对比数据 /// </summary> /// <param name="stcd">站码</param> /// <param name="sdate">开始时间</param> /// <param name="edate">结束时间</param> /// <param name="compareYear">对比年份</param> /// <returns></returns> List<dynamic> GetDataForSingleRiverCompare(string stcd, string sdate, string edate, string compareYear); /// <summary> /// 获取水情信息-未分页 /// add by SUN /// Date:2019-05-24 00:00 /// </summary> /// <param name="stcd"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> IEnumerable<dynamic> GetRiverData(string stcd, string startDate, string endDate); /// <summary> /// 查询水情均值 /// add by SUN /// Date:2019-05-24 10:00 /// </summary> /// <param name="stcd"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> List<dynamic> GetRvavData(string stcd, string startDate, string endDate); /// <summary> /// 查询多站水位对比数据,列标题为站码 /// add by SUN /// Date:2019-05-24 11:00 /// </summary> /// <param name="stcds"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> string GetZDataByMultiStcds(string stcds, string startDate, string endDate); /// <summary> /// 多站流量对比数据,列标题位站码 /// add by SUN /// Date:2019-06-11 16:00 /// </summary> /// <param name="stcds"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> string GetQDataByMultiStcds(string stcds, string startDate, string endDate); /// <summary> /// 查询历史多站水情数据-未分页 /// add by JinJianping /// Date:2019-05-30 11:00 /// </summary> /// <param name="stcds"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> IEnumerable<dynamic> GetHistoryRiverByMultiStcds(string stcds, string startDate, string endDate, int year, int type); /// <summary> /// 水流沙过程对照 /// create by zhujun on 2019-05-31 11:40 /// </summary> /// <param name="stcds">测站名称</param> /// <param name="stime">开始时间</param> /// <param name="etime">结束时间</param> /// <returns>{data.zqlist:水位流量,data.slist:含沙量}</returns> dynamic GetMutliStationZQS(string stcds, string stime, string etime); /// <summary> /// 获取多站水情数据(水位、流量) /// add by SUN /// Date:2019-06-11 16:00 /// </summary> /// <param name="stcds">站码列表,eg:"40100150,40100160"</param> /// <param name="startDate">起始时间</param> /// <param name="endDate">结束时间</param> /// <returns></returns> List<dynamic> GetRiverDataMultiSta(string stcds, string startDate, string endDate); /// <summary> /// 首页水位流量过程线 /// </summary> /// <param name="stcd"></param> /// <param name="endDate"></param> /// <param name="stype">0表示实时水情只取八点数据,1表示在线水位时间不过滤</param> /// <returns></returns> IEnumerable<dynamic> GetRiverChartData(string stcd, string endDate, int stype); /// <summary> /// 断面水位数据 /// add by SUN /// Date:2019-07-10 11:00 /// </summary> /// <param name="stcd"></param> /// <param name="stnm"></param> /// <param name="tm"></param> /// <param name="sDt"></param> /// <returns></returns> string GetSectionZ(string stcd, string stnm, string tm, string sDt); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace C_SharpWorkshop { class Program { static void Main(string[] args) { Triangle obj = new Triangle(5, 10); obj.DisplayArea(); obj.displayDimensions(); obj.DisplayPerimeter(); Console.WriteLine(); Console.WriteLine(); Rectangle recObj = new Rectangle(10, 15); recObj.DisplayArea(); recObj.displayDimensions(); recObj.DisplayPerimeter(); Console.WriteLine(); Console.WriteLine(); RightAngledTriangle rightObj = new RightAngledTriangle(4, 5, 10); rightObj.DisplayArea(); rightObj.displayDimensions(); rightObj.DisplayPerimeter(); List<Shapes> listObj = new List<Shapes>(); listObj.Add(recObj); listObj.Add(obj); listObj.Add(rightObj); Console.WriteLine("********************************"); foreach(Shapes element in listObj) { element.DisplayArea(); element.DisplayPerimeter(); element.displayDimensions(); element.DisplayType(); } Stack stackObj = new Stack(); stackObj.Push(obj); stackObj.Push(recObj); stackObj.Push(rightObj); Console.WriteLine(); Console.WriteLine("*************************************"); Console.WriteLine("Removing from the stack"); while(stackObj.Count >0) { Console.WriteLine("Removed:" + stackObj.Pop()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaskMan.Domains.Constants { public static class CacheConstants { public const string StatusCache = nameof(StatusCache); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using vega.API.Core; using vega.API.Core.Models; using vega.API.Extensions; namespace vega.API.Persistence { public class VehicleRepository : IVehicleRepository { private readonly VegaDbContext _context; public VehicleRepository(VegaDbContext context) { _context = context; } public async Task<Vehicle> GetVehicle(int id, bool includeRelated = true) { if (!includeRelated) { return await _context.Vehicles.FindAsync(id); } return await _context.Vehicles .Include(x => x.VehicleFeatures) .ThenInclude(x => x.Feature) .Include(x => x.Model) .ThenInclude(x => x.Make) .SingleOrDefaultAsync(x => x.Id == id); } public async Task<Vehicle> GetVehicleWithMake(int id) { return await _context.Vehicles .Include(x => x.Model) .ThenInclude(x => x.Make) .SingleOrDefaultAsync(x => x.Id == id); } public void Add(Vehicle vehicle) { _context.Vehicles.Add(vehicle); } public void Remove(Vehicle vehicle) { _context.Remove(vehicle); } public async Task<QueryResult<Vehicle>> GetVehicles(VehicleQuery queryObj) { var result = new QueryResult<Vehicle>(); var query = _context.Vehicles .Include(x => x.Model) .ThenInclude(x => x.Make) .Include(x => x.VehicleFeatures) .ThenInclude(x => x.Feature) .AsQueryable(); if (queryObj.MakeId.HasValue) query = query.Where(x => x.Model.MakeId == queryObj.MakeId); if (queryObj.ModelId.HasValue) query = query.Where(x => x.Model.Id == queryObj.ModelId); var columnsMap = new Dictionary<string, Expression<Func<Vehicle, object>>>() { ["make"] = vehicle => vehicle.Model.Make.Name, ["model"] = vehicle => vehicle.Model.Name, ["contactName"] = vehicle => vehicle.ContactName, }; query = query.ApplyOrdering(queryObj, columnsMap); result.TotalItems = await query.CountAsync(); query = query.ApplyPaging(queryObj); result.Items = await query.ToListAsync(); return result; } } }
using Mercado.Model; using System.Collections.Generic; using System.Linq; namespace Mercado.Dao { public class GrupoDao { public List<Grupo> Listar() { using (var ctx = new MercadoContext()) { return ctx.Grupo.ToList(); } } public int Incluir(Grupo Grupo) { using (var ctx = new MercadoContext()) { ctx.Grupo.Add(Grupo); ctx.SaveChanges(); return Grupo.Id; } } public void Excluir(Grupo Grupo) { using (var ctx = new MercadoContext()) { Grupo = ctx.Grupo.Find(Grupo.Id); ctx.Grupo.Remove(Grupo); ctx.SaveChanges(); } } public void VincularUsuario(int grupoId, int usuarioId) { using (var ctx = new MercadoContext()) { var u = new Usuario() { Id = usuarioId }; ctx.Usuario.Add(u); ctx.Usuario.Attach(u); var g = new Grupo() { Id = grupoId }; ctx.Grupo.Add(g); ctx.Grupo.Attach(g); u.Grupos.Add(g); ctx.SaveChanges(); } } public void VincularFuncionalidade(int grupoId, int funcionalidadeId) { using (var ctx = new MercadoContext()) { var p = new Funcionalidade() { Id = funcionalidadeId }; ctx.Funcionalidade.Add(p); ctx.Funcionalidade.Attach(p); var g = new Grupo() { Id = grupoId }; ctx.Grupo.Add(g); ctx.Grupo.Attach(g); p.Grupos.Add(g); ctx.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Kers.Models.Contexts; using Kers.Models.Entities.KERScore; using Kers.Models.Repositories; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Kers.Tasks { public class SnapAgentCommunityEventDetailTask : TaskBase, IScheduledTask { IServiceProvider serviceProvider; public SnapAgentCommunityEventDetailTask( IServiceProvider serviceProvider ){ this.serviceProvider = serviceProvider; } public string Schedule => "12 1 * * *"; public async Task ExecuteAsync(CancellationToken cancellationToken) { var serviceScopeFactory = this.serviceProvider.GetRequiredService<IServiceScopeFactory>(); using (var scope = serviceScopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetService<KERScoreContext>(); try{ var cache = scope.ServiceProvider.GetService<IDistributedCache>(); var memoryCache = scope.ServiceProvider.GetService<IMemoryCache>(); var fiscalYearRepo = new FiscalYearRepository( context ); var repo = new SnapPolicyRepository(context, cache, memoryCache); var startTime = DateTime.Now; var str = repo.AgentCommunityEventDetail(fiscalYearRepo.currentFiscalYear(FiscalYearType.SnapEd), true); Random rnd = new Random(); int RndInt = rnd.Next(1, 53); if( RndInt == 2 ){ str = repo.AgentCommunityEventDetail(fiscalYearRepo.previoiusFiscalYear(FiscalYearType.SnapEd), true); } var endTime = DateTime.Now; await LogComplete(context, "SnapAgentCommunityEventDetailTask", str, "SnapAgent Community Event Detail Task executed for " + (endTime - startTime).TotalSeconds + " seconds" ); }catch( Exception e){ await LogError(context, "SnapAgentCommunityEventDetailTask", e, "SnapAgent Community Event Detail Task failed" ); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TheWayLearnPSO.PSOAlogirthm { class Particle { public double x { get; set; } public double v { get; set; } public double y { get; set; } public double previousBest { get; private set; } private delegate double DelegateFitness(double _x); DelegateFitness CalFitness= new DelegateFitness(Algorithm.CalFitness); public Particle(double _x = 0.0) { x = _x; v = x / 2 + 1; previousBest = -9999999; } public void Fitness(ref double GlobleBest,ref double GlobleBestX) { this.y = this.CalFitness(this.x); if (this.y > this.previousBest) { this.previousBest = this.y; } if (this.previousBest > GlobleBest) { GlobleBest = this.previousBest; GlobleBestX = this.x; } } public bool UpdataSpeed(double GlobleBestX) { double w = 0.758; double c1 = 2.0; double c2 = 2.0; v = w * v + c1 * this.RandomNum() * (previousBest - x) + c2 * this.RandomNum() * (GlobleBestX - x); return true; } public bool UpdataPostion() { x = v + x; if (x > 100 || x < -100) { Random ra = new Random(); x = ra.Next(-100,100); } return true; } private double RandomNum() { Random ra = new Random(); double ans = (double)(ra.Next(0, 1000)); return ans; } } }
using System; using System.Collections.Generic; using System.Linq; namespace StringCalculatorDay13 { public class StringCalculator { public int Add(string numbers) { if (NullOrWhiteSpace(numbers)) { return 0; } var numberStorage = SplitNumbers(numbers); var negativeNumbers = numberStorage.Where(x => int.Parse(x) < 0); if (NumbersAre(negativeNumbers)) { throw new Exception($"Negatives Not Allowed {JoinNegativeNumbers(negativeNumbers)}"); } var sum = GetSum(numberStorage); return sum; } private int GetSum(string[] numberStorage) { return numberStorage.Where( x => int.Parse(x) <= 1000).Sum(x => int.Parse(x)); } private string[] SplitNumbers(string numbers) { return numbers.Split(new char[] { ',', '\n', ';', '/','*','[',']','%'}, StringSplitOptions.RemoveEmptyEntries); } private string JoinNegativeNumbers(IEnumerable<string> negativeNumbers) { return string.Join(" ", negativeNumbers); } private bool NumbersAre(IEnumerable<string> negativeNumbers) { return negativeNumbers.Any(); } private bool NullOrWhiteSpace(string number) { return string.IsNullOrWhiteSpace(number); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; namespace Cognitive_Metier { /// <summary> /// This is a class for testing purpose only /// to delete /// </summary> class Program { static void Main(string[] args) { #region calendar testing /* var test = EmotionLogs.GetEmotionLogs(); foreach(var calendarItem in test.calendar.calendarItemsList) { Console.WriteLine(calendarItem.date + " -> " + calendarItem.nbCalls); } Console.WriteLine("-----------"); test.calendar.AddCall(); foreach (var calendarItem in test.calendar.calendarItemsList) { Console.WriteLine(calendarItem.date + " -> " + calendarItem.nbCalls); } Console.WriteLine("-----------"); test.calendar.AddCall(); foreach (var calendarItem in test.calendar.calendarItemsList) { Console.WriteLine(calendarItem.date + " -> " + calendarItem.nbCalls); } */ #endregion calendar testing var textAnalysis = new TextAnalysisAPI(); /*var test = textAnalysis.MakeRequests("Hello! How are you doing bud ?").Result; Console.WriteLine(test.ToString()); Console.WriteLine(textAnalysis.textAnalysisResult.language); Console.WriteLine(textAnalysis.textAnalysisResult.sentiment); foreach(var blop in textAnalysis.textAnalysisResult.keyphrases) { Console.WriteLine(blop); }*/ textAnalysis.MakeRequests("1234"); Console.ReadLine(); } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_Gradient : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { Gradient o = new Gradient(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Evaluate(IntPtr l) { int result; try { Gradient gradient = (Gradient)LuaObject.checkSelf(l); float num; LuaObject.checkType(l, 2, out num); Color o = gradient.Evaluate(num); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int SetKeys(IntPtr l) { int result; try { Gradient gradient = (Gradient)LuaObject.checkSelf(l); GradientColorKey[] array; LuaObject.checkArray<GradientColorKey>(l, 2, out array); GradientAlphaKey[] array2; LuaObject.checkArray<GradientAlphaKey>(l, 3, out array2); gradient.SetKeys(array, array2); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_colorKeys(IntPtr l) { int result; try { Gradient gradient = (Gradient)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, gradient.get_colorKeys()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_colorKeys(IntPtr l) { int result; try { Gradient gradient = (Gradient)LuaObject.checkSelf(l); GradientColorKey[] colorKeys; LuaObject.checkArray<GradientColorKey>(l, 2, out colorKeys); gradient.set_colorKeys(colorKeys); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_alphaKeys(IntPtr l) { int result; try { Gradient gradient = (Gradient)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, gradient.get_alphaKeys()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_alphaKeys(IntPtr l) { int result; try { Gradient gradient = (Gradient)LuaObject.checkSelf(l); GradientAlphaKey[] alphaKeys; LuaObject.checkArray<GradientAlphaKey>(l, 2, out alphaKeys); gradient.set_alphaKeys(alphaKeys); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.Gradient"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Gradient.Evaluate)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Gradient.SetKeys)); LuaObject.addMember(l, "colorKeys", new LuaCSFunction(Lua_UnityEngine_Gradient.get_colorKeys), new LuaCSFunction(Lua_UnityEngine_Gradient.set_colorKeys), true); LuaObject.addMember(l, "alphaKeys", new LuaCSFunction(Lua_UnityEngine_Gradient.get_alphaKeys), new LuaCSFunction(Lua_UnityEngine_Gradient.set_alphaKeys), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Gradient.constructor), typeof(Gradient)); } }
namespace _1.StudentsResults { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main(string[] args) { var dict = new Dictionary<string, List<double>>(); var n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { var arguments = Console.ReadLine() .Trim() .Split(new[] {" - ", ", "}, StringSplitOptions.RemoveEmptyEntries) .ToArray(); List<double> grates = new List<double>(); grates.Add(double.Parse(arguments[1])); grates.Add(double.Parse(arguments[2])); grates.Add(double.Parse(arguments[3])); if (!dict.ContainsKey(arguments[0])) { dict[arguments[0]] = grates; } } Console.WriteLine(string.Format($"{"Name",-10}|{"CAdv",7}|{"COOP",7}|{"AdvOOP",7}|{"Average",7}|")); foreach (var e in dict) { Console.WriteLine(string.Format($"{e.Key,-10}|{e.Value[0],7:f2}|{e.Value[1],7:f2}|{e.Value[2],7:f2}|{e.Value.Average(),7:f4}|")); } } } }
using Entidades; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PetShopForms.Vistas.Productos { public partial class Listado : Form { public Listado() { InitializeComponent(); } private void Listado_Load(object sender, EventArgs e) { CargarProductos(); } private void btnAdd_Click(object sender, EventArgs e) { Form form = new Agregar(); DialogResult dialogRes = form.ShowDialog(); if (dialogRes != DialogResult.None) { CargarProductos(); } } private void btnEdit_Click(object sender, EventArgs e) { if (dgvProductos.SelectedCells.Count > 0) { Form form = new Editar((Producto)dgvProductos.CurrentRow.DataBoundItem); DialogResult dialogRes = form.ShowDialog(); if (dialogRes != DialogResult.None) { CargarProductos(); } } } private void btnDelete_Click(object sender, EventArgs e) { if (dgvProductos.SelectedCells.Count > 0) { int selectedRowIndex = this.dgvProductos.SelectedCells[0].RowIndex; int selectedId = (int)dgvProductos.Rows[selectedRowIndex].Cells["Id"].Value; if (MessageBox.Show($"Seguro que desea eliminar el producto de id: {selectedId}?", "Confirmacion", MessageBoxButtons.YesNo) == DialogResult.No) { return; } else { foreach (Producto prdt in Producto.ListaProductos) { if (prdt.Id == selectedId) { if (Producto.ListaProductos - prdt) { MessageBox.Show("Producto eliminado", "Operacion exitosa", MessageBoxButtons.OK); break; } else { MessageBox.Show("Producto no eliminado", "Error", MessageBoxButtons.OK); break; } } } CargarProductos(); } } } void CargarProductos() { if (Producto.ListaProductos.Count > 0) { dgvProductos.DataSource = new List<Entidades.Producto>(Producto.ListaProductos); } } private void Listado_Paint(object sender, PaintEventArgs e) { Inicio.ResetTimeOutTime(); } } }
using LaserMaze.Enums; using LaserMaze.Models; using Xunit; namespace LaserMaze.Tests { public class RightAngleMirrorRoomTests { private RightAngleMirrorRoom GetMirrorRoom(MirrorType mirrorType) { var coords = new GridCoordinates(1, 1); var mirror = new Mirror { Coordinates = coords, MirrorOrientation = MirrorOrientation.Right, MirrorType = mirrorType }; return new RightAngleMirrorRoom(mirror); } [Fact] public void GetNextLaserPosition_ReturnsRight_WithTwoWayAndLaserFromBottom() { var mirrorRoom = GetMirrorRoom(MirrorType.TwoWay); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Up); Assert.Equal(LaserDirection.Right, nextPosition.Direction); Assert.Equal(new GridCoordinates(2, 1), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsUp_WithTwoWayandLaserFromLeft() { var mirrorRoom = GetMirrorRoom(MirrorType.TwoWay); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Right); Assert.Equal(LaserDirection.Up, nextPosition.Direction); Assert.Equal(new GridCoordinates(1, 2), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsDown_WithTwoWayAndLaserFromRight() { var mirrorRoom = GetMirrorRoom(MirrorType.TwoWay); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Left); Assert.Equal(LaserDirection.Down, nextPosition.Direction); Assert.Equal(new GridCoordinates(1, 0), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsLeft_WithTwoWayAndLaserFromTop() { var mirrorRoom = GetMirrorRoom(MirrorType.TwoWay); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Down); Assert.Equal(LaserDirection.Left, nextPosition.Direction); Assert.Equal(new GridCoordinates(0, 1), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsDown_WithOneWayLeftAndLaserFromRight() { var mirrorRoom = GetMirrorRoom(MirrorType.OneWayReflectOnLeft); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Left); Assert.Equal(LaserDirection.Left, nextPosition.Direction); Assert.Equal(new GridCoordinates(0, 1), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsLeft_WithOneWayLeftAndLaserFromTop() { var mirrorRoom = GetMirrorRoom(MirrorType.OneWayReflectOnLeft); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Down); Assert.Equal(LaserDirection.Left, nextPosition.Direction); Assert.Equal(new GridCoordinates(0, 1), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsUp_WithOneWayLeftAndLaserFromBottom() { var mirrorRoom = GetMirrorRoom(MirrorType.OneWayReflectOnLeft); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Up); Assert.Equal(LaserDirection.Up, nextPosition.Direction); Assert.Equal(new GridCoordinates(1, 2), nextPosition.Coordinates); } [Fact] public void GetNextLaserPosition_ReturnsUp_WithOneWayLeftAndLaserFromLeft() { var mirrorRoom = GetMirrorRoom(MirrorType.OneWayReflectOnLeft); var nextPosition = mirrorRoom.GetNextLaserPosition(LaserDirection.Right); Assert.Equal(LaserDirection.Up, nextPosition.Direction); Assert.Equal(new GridCoordinates(1, 2), nextPosition.Coordinates); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Negozio.DataAccess.DbModel { public class Cliente { [Key] public int ClienteId { get; set; } public string Nome { get; set; } public string Cognome { get; set; } } }
using System.Xml.Linq; using PlatformRacing3.Common.Stamp; using PlatformRacing3.Web.Controllers.DataAccess2.Procedures.Exceptions; using PlatformRacing3.Web.Extensions; using PlatformRacing3.Web.Responses; using PlatformRacing3.Web.Responses.Procedures.Stamps; namespace PlatformRacing3.Web.Controllers.DataAccess2.Procedures.Stamps; public class GetMyStampsProcedure : IProcedure { public async Task<IDataAccessDataResponse> GetResponseAsync(HttpContext httpContext, XDocument xml) { uint userId = httpContext.IsAuthenicatedPr3User(); if (userId > 0) { XElement data = xml.Element("Params"); if (data != null) { uint start = (uint?)data.Element("p_start") ?? throw new DataAccessProcedureMissingData(); uint count = (uint?)data.Element("p_count") ?? throw new DataAccessProcedureMissingData(); string category = (string)data.Element("p_category") ?? throw new DataAccessProcedureMissingData(); DataAccessGetMyStampsResponse response = new(category); foreach(uint stamp in await StampManager.GetMyStampsAsync(userId, category, start, count)) { response.AddStamp(stamp); } return response; } else { throw new DataAccessProcedureMissingData(); } } else { return new DataAccessErrorResponse("You are not logged in!"); } } }
// ----------------------------------------------------------------------- // <copyright file="MainViewModel.cs"> // Copyright (c) 2015 Andrew Zavgorodniy. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace MyStudio.ViewModels { using Catel.MVVM; public class MainViewModel : ViewModelBase { } }
using System; using UnityEngine; [CustomLuaClass] public class SLuaTest : MonoBehaviour { public FloatEvent intevent; }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MyPage.Areas.Treinamento.Data.DAL; using MyPage.Areas.Treinamento.Models; namespace MyPage.Areas.Treinamento.Controllers { [Authorize] [Area("Treinamento")] public class TreinoSemanaController : Controller { private readonly TreinoSemanaDAL treinoSemanaDAL; public TreinoSemanaController(Contexto contexto) { treinoSemanaDAL = new TreinoSemanaDAL(contexto); } public async Task<IActionResult> Index() { return View(await treinoSemanaDAL.GetTreinos()); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(TreinoSemana treinoSemana) { if (ModelState.IsValid) { try { await treinoSemanaDAL.SetTreinoSemana(treinoSemana); return RedirectToAction("Create", "Treino",new { id = treinoSemana.Id}); } catch (DbUpdateException) { ModelState.AddModelError("", "Ocorreu um problema ao tentar adicionar esse treino ao sistema"); } } return View(treinoSemana); } public async Task<IActionResult> Edit(long? id) { return await GetSemanaTreinoViewById(id); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(TreinoSemana treinoSemana) { if (ModelState.IsValid) { try { await treinoSemanaDAL.SetTreinoSemana(treinoSemana); return RedirectToAction(nameof(Index)); } catch (DbUpdateException) { ModelState.AddModelError("", "Não foi possivel editar o treino"); } } return View(treinoSemana); } public async Task<IActionResult> Details(long? id) { return await GetSemanaTreinoViewById(id); } public async Task<IActionResult> Delete(long? id) { return await GetSemanaTreinoViewById(id); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> ConfirmDelete(long? id) { TreinoSemana treinoSemana = await treinoSemanaDAL.RemoveTreinoSemana((long)id); return RedirectToAction(nameof(Index)); } public async Task<IActionResult> GetSemanaTreinoViewById(long? id) { if(id == null) { return NotFound(); } TreinoSemana treinoSemana = await treinoSemanaDAL.GetTreinoSemanaById((long)id); if(treinoSemana == null) { return NotFound(); } return View(treinoSemana); } } }
/* * Copyright 2014 Technische Universität Darmstadt * * 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.Linq; using KaVE.Commons.Model.Naming.CodeElements; using KaVE.Commons.Model.TypeShapes; using KaVE.Commons.Utils.Collections; using KaVE.Commons.Utils.Naming; namespace KaVE.VS.FeedbackGenerator.SessionManager.Anonymize.CompletionEvents { public class TypeShapeAnonymizer { public ITypeShape Anonymize(ITypeShape typeShape) { return new TypeShape { TypeHierarchy = AnonymizeCodeNames(typeShape.TypeHierarchy), NestedTypes = Sets.NewHashSetFrom(typeShape.NestedTypes.Select(tn => tn.ToAnonymousName())), Delegates = Sets.NewHashSetFrom(typeShape.Delegates.Select(n => n.ToAnonymousName())), EventHierarchies = Sets.NewHashSetFrom(typeShape.EventHierarchies.Select(AnonymizeCodeNames)), Fields = Sets.NewHashSetFrom(typeShape.Fields.Select(n => n.ToAnonymousName())), MethodHierarchies = Sets.NewHashSetFrom(typeShape.MethodHierarchies.Select(AnonymizeCodeNames)), PropertyHierarchies = Sets.NewHashSetFrom(typeShape.PropertyHierarchies.Select(AnonymizeCodeNames)) }; } private static ITypeHierarchy AnonymizeCodeNames(ITypeHierarchy raw) { if (raw == null) { return null; } return new TypeHierarchy { Element = raw.Element.ToAnonymousName(), Extends = AnonymizeCodeNames(raw.Extends), Implements = Sets.NewHashSetFrom(raw.Implements.Select(AnonymizeCodeNames)) }; } private static IMemberHierarchy<IEventName> AnonymizeCodeNames(IMemberHierarchy<IEventName> raw) { return new EventHierarchy { Element = raw.Element.ToAnonymousName(), Super = raw.Super.ToAnonymousName(), First = raw.First.ToAnonymousName() }; } private static IMemberHierarchy<IMethodName> AnonymizeCodeNames(IMemberHierarchy<IMethodName> raw) { return new MethodHierarchy { Element = raw.Element.ToAnonymousName(), Super = raw.Super.ToAnonymousName(), First = raw.First.ToAnonymousName() }; } private static IMemberHierarchy<IPropertyName> AnonymizeCodeNames(IMemberHierarchy<IPropertyName> raw) { return new PropertyHierarchy { Element = raw.Element.ToAnonymousName(), Super = raw.Super.ToAnonymousName(), First = raw.First.ToAnonymousName() }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MGL_API.Model.Saida.GameDetail { public class RetornoObterMemoria : Retorno { public int CodigoMemoria { get; set; } public string NomeMemoria { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IndicatorArrowToggler : MonoBehaviour { public string Button; void Update () { if (Input.GetButtonDown(Button)) { IndicatorArrow.ShowArrows = !IndicatorArrow.ShowArrows; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum BULLET_TYPE { PLAYER, ENEMY } public class Bullet : MonoBehaviour { static float DISTANCE = 100f; public int damage; public float speed; public MainWeapon owner; public BULLET_TYPE bulletType; private float travelTime; private Vector3 from; private Vector3 to; private float time = 0; public Bullet(int damage, float speed, BULLET_TYPE bulletType) { this.damage = damage; this.speed = speed; this.bulletType = bulletType; } // Start is called before the first frame update void Start() { from = transform.position; float angle = transform.rotation.eulerAngles.z; var vForce = Quaternion.AngleAxis(angle, Vector3.forward) * Vector3.right; to = from + (vForce.normalized * DISTANCE); } // Update is called once per frame void Update() { travelTime = DISTANCE / speed; time += Time.deltaTime; transform.position = Vector3.Lerp(from, to, time / travelTime); if (time >= travelTime) { DestroyBullet(); } } public void OnTriggerEnter2D(Collider2D collider) { IDamageable damageable = collider.gameObject.GetComponent(typeof(IDamageable)) as IDamageable; if ( damageable != null && (collider.gameObject.tag == "Player" && bulletType == BULLET_TYPE.ENEMY) || (collider.gameObject.tag == "Enemy" && bulletType == BULLET_TYPE.PLAYER) ) { damageable.Hit(damage); DestroyBullet(); } else if (damageable == null) { DestroyBullet(); } } private void DestroyBullet() { owner.OnDestroyBullet(gameObject); Destroy(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CT.Data { [CreateAssetMenu(fileName = "New Mine", menuName = "Faction/Building/Mine")] public class MineData : BuildingData { public override BuildingType Type => BuildingType.Mine; public ResourceType resourceType; public VersionData original; public VersionData[] upgrades; public override BaseVersionData Original => original; public override BaseVersionData[] Upgrades => upgrades; [System.Serializable] public class VersionData : BaseVersionData { public GameTime yieldTime; public int capacity; public GameTime fillTime; public int YieldEachTime => (int)(capacity * (yieldTime.TotalSeconds / fillTime.TotalSeconds)); public int HourlyYield => YieldEachTime * (GameTime.Hour / yieldTime); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Tooltip Interaction", menuName = "Custom/Interaction/Tooltip Interaction")] public class TooltipInteraction : Interaction { [SerializeField] private string m_Text; [SerializeField] private float m_Duration; [SerializeField] private AudioClip m_AudioClip; public override bool Interact(InteractableObject thisObject, InteractableObject otherObject) { string display = ""; if (otherObject == null) display = string.Format(m_Text, thisObject.Data.DisplayName); else display = string.Format(m_Text, thisObject.Data.DisplayName, otherObject.Data.DisplayName); //Debug.Log(display); thisObject.SetTooltip(display, m_Duration); thisObject.PlaySound(m_AudioClip); return false; } }
using System; using ChatServer; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Linq; namespace ChatServer.Test { [TestClass] public class UnitTest1 { IMessenger messenger; [TestInitialize] public void Init() { messenger = new Messenger(100); } [TestMethod] public void TestMethod1() { string expectedMessage = "Hello"; byte[] byteMessage = NetHelper.ConvertMessage(expectedMessage); byte[] buffer = new byte[100]; Stream stream = new MemoryStream(NetHelper.ConvertMessage("Hello")); StreamWriter writer = new StreamWriter(stream); StreamReader reader = new StreamReader(stream); writer.AutoFlush = true; //writer.WriteLine("Hello"); string actual = reader.ReadLine(); stream.Write(byteMessage, 0, byteMessage.Count()); stream.Flush(); int bi = stream.Read(buffer, 0, buffer.Count()); string actualMessage = messenger.GetMessage(stream); Assert.AreEqual(expectedMessage, actualMessage); StringAssert.Equals(expectedMessage, actualMessage); } } }
namespace Liddup.Droid.Services { internal class NapsterApiAndroid { //public Napster Napster { get; set; } public NapsterApiAndroid() { //Napster = Napster.Register(Forms.Context, ApiConstants.NapsterApiKey, ApiConstants.NapsterApiSecret); } public void Login() { //var loginUrl = Napster.GetLoginUrl(ApiConstants.NapsterRedirectUri); } } }
using System.ComponentModel.DataAnnotations; namespace BagBag.Models { [MetadataType(typeof(Category.CatagoryMetaData))] public partial class Category { internal sealed class CatagoryMetaData { public int CategoryId { get; set; } [Display(Name ="Danh Mục Sản Phẩm")] [Required(ErrorMessage = "Không được rỗng")] public string CategoryName { get; set; } [Display(Name = "Mô tả")] [Required(ErrorMessage = "Không được rỗng")] [DataType(DataType.MultilineText)] public string CategoryDetails { get; set; } } } }
using GraphQLSampleSplitAPI.Models; namespace GraphQLSampleSplitAPI.MutationResolvers { public class CountryMutationResolver { public string SaveCountry(CountryModel model) { return model.Name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net; namespace MvvmTest.HtmlAgility { public class XWebClient : WebClient { public CookieContainer Cookies { get; private set; } public XWebClient() { Cookies = new CookieContainer(); //path一般为“/”,domain为url,上图中的Cookie按分号分割,等号左边的就是name,右边的就是 value //Cookies.Add(new Cookie(string name, string value, string path, string domain)); } /// <summary> /// 携带Cookie /// </summary> /// <param name="address"></param> /// <returns></returns> protected override WebRequest GetWebRequest(Uri address) { var request = base.GetWebRequest(address) as HttpWebRequest; //解压缩 request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; if (request.CookieContainer == null) request.CookieContainer = Cookies; return request; } } }
using UnityEngine; using System.Collections; public class DebugCombatController : CombatController { int oldHealth = 0; void OnDrawGizmos() { if (oldHealth > health) { Gizmos.DrawCube(transform.position, transform.localScale); } oldHealth = health; } }
using BPiaoBao.AppServices.DataContracts.Cashbag; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; namespace BPiaoBao.AppServices.Contracts.Cashbag { [ServiceContract] public interface IFinancialService { /// <summary> /// 取理财产品列表 /// </summary> /// <returns></returns> [OperationContract] List<FinancialProductDto> GetAllProduct(); /// <summary> /// 购买理财产品(现金账户) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="FinancialID"></param> /// <param name="money"></param> [OperationContract] void BuyFinancialProductByCashAccount(string productID, decimal money, string pwd); /// <summary> /// 购买理财产品(银行卡) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="FinancialID"></param> /// <param name="money"></param> [OperationContract] string BuyFinancialProductByBank(string productID, decimal money, string bankName); /// <summary> /// 购买理财产品(第三方) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="FinancialID"></param> /// <param name="money"></param> [OperationContract] string BuyFinancialProductByPlatform(string productID, decimal money, string payPlatform); /// <summary> /// 中止某个理财产品 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="tradeID"></param> /// <param name="pwd"></param> [OperationContract] void AbortFinancial(string tradeID, string pwd); /// <summary> /// 查看收益 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="tradeID"></param> /// <returns></returns> [OperationContract] ExpectProfitDto GetExpectProfit(string tradeID); /// <summary> /// 获取理财产品详情 /// </summary> /// <param name="productID"></param> /// <returns></returns> [OperationContract] FinancialProductDto GetSingleProductInfo(string productID); /// <summary> /// 获取下架产品信息 /// </summary> /// <param name="quantity">数量</param> /// <returns></returns> [OperationContract] IEnumerable<FinancialProductDto> GetShelfProducts(string quantity); /// <summary> /// 获取可购买产品信息 /// </summary> /// <param name="quantity">数量</param> /// <returns></returns> [OperationContract] IEnumerable<FinancialProductDto> GetActiveProduct(string quantity); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class bullet : MonoBehaviour { private float rotationSpeed = 1f; private float minY = -60f; private float maxY = 60f; private float rotationY = 10f; private float rotationX = 0f; public GameObject bulletPrefab; public Transform bulletSpawn; void Start () { } // Update is called once per frame void Update () { if(Input.GetKey (KeyCode.Mouse0)) { Fire(); } } void Fire() { var bullet = (GameObject)Instantiate( bulletPrefab, bulletSpawn.position, bulletSpawn.rotation); bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6; Destroy(bullet, 2.0f); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FixyNet { public partial class Loading : Form { public Loading() { InitializeComponent(); } private void Loading_Load(object sender, EventArgs e) { } public void setTitle(string title) { this.Text = title; } public void setProgress(int max, int min) { progressBarLoading.Maximum = max; progressBarLoading.Minimum = min; } public void statusProgress(int valor) { progressBarLoading.Value = valor; lblIp.Text = valor.ToString(); } } }
 using System.ServiceModel; namespace Service { /// <summary> /// Represents the service contract for queries. /// </summary> [ServiceContract(CallbackContract = typeof(IQueryCallbackContract), Namespace = ServiceConstants.QueryNamespace)] public interface IQueryContract { /// <summary> /// Occurs when a new query is submitted. /// </summary> event QueryEventHandler QuerySubmitted; /// <summary> /// Executes a direct query which does not utilize callbacks. /// </summary> /// <param name="queryType">The query type.</param> /// <param name="queryDef">The query definition.</param> /// <returns> /// The query response of the specified query type. /// </returns> [OperationContract] IQueryResponse DirectQuery(string queryType, IQueryDef queryDef); /// <summary> /// Executes a query using callbacks. /// </summary> /// <param name="queryType">The query type.</param> /// <param name="queryDef">The query definition.</param> [OperationContract(IsOneWay = true)] void Query(string queryType, IQueryDef queryDef); } }
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 Entities.Models { public class Audit { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int AuditId { get; set; } public int FiveStarsLevel { get; set; } public int Note { get; set; } public String TypeAudit { get; set; } public bool isInProgress { get; set; } public bool isCompleted { get; set; } [Display(Name = "Date de l’Audit ")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dddd dd MMMM yyyy}")] public DateTime? AuditDay { get; set; } [DataType(DataType.Date)] public DateTime? DateOfCompletion { get; set; } public virtual List<Resultat> resultats { get; set; } public virtual Semaine semaine { get; set; } public virtual Auditeur auditeur { get; set; } public virtual Zone zone { get; set; } } }
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI; public class ScreenshotController : MonoBehaviour { public Button button; // Use this for initialization void Start () { Button btn = button.GetComponent<Button>(); btn.onClick.AddListener(TaskOnClick); } // Update is called once per frame void Update () { } void TaskOnClick() { GameObject[] ARObjects = GameObject.FindGameObjectsWithTag("ARObject"); foreach (GameObject ARObject in ARObjects) { ARObject.SetActive(false); } string filename = "Screenshot" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg"; ScreenCapture.CaptureScreenshot(filename); foreach (GameObject ARObject in ARObjects) { ARObject.SetActive(true); } } }