text
stringlengths
13
6.01M
///////////////////////////////////////////////////////////////////////////////// // // vp_NGUISimpleHUDMobile.cs // © VisionPunk. All Rights Reserved. // https://twitter.com/VisionPunk // http://www.visionpunk.com // // description: a very primitive HUD displaying health, clips and ammo, along // with a soft red full screen flash for when taking damage // ///////////////////////////////////////////////////////////////////////////////// using UnityEngine; [RequireComponent(typeof(AudioSource))] public class vp_NGUISimpleHUDMobile : vp_SimpleHUDMobile { protected UILabel m_AmmoLabelSprite = null; protected UILabel m_HealthLabelSprite = null; protected UILabel m_HintsLabelSprite = null; /// <summary> /// /// </summary> protected override void Awake() { base.Awake(); if(AmmoLabel != null) m_AmmoLabelSprite = AmmoLabel.GetComponentInChildren<UILabel>(); if(HealthLabel != null) m_HealthLabelSprite = HealthLabel.GetComponentInChildren<UILabel>(); if(HintsLabel != null) m_HintsLabelSprite = HintsLabel.GetComponentInChildren<UILabel>(); if(m_HintsLabelSprite != null) { m_HintsLabelSprite.text = ""; m_HintsLabelSprite.color = Color.clear; } } /// <summary> /// this draws a primitive HUD and also renders the current /// message, fading out in the middle of the screen /// </summary> protected override void OnGUI() { // show a red glow along the screen edges when damaged if (DamageFlashTexture != null && m_DamageFlashColorMobile.a > 0.01f) { m_DamageFlashColorMobile = Color.Lerp(m_DamageFlashColorMobile, m_DamageFlashInvisibleColorMobile, Time.deltaTime * 0.4f); GUI.color = m_DamageFlashColorMobile; GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), DamageFlashTexture); GUI.color = Color.white; } } /// <summary> /// /// </summary> protected override void Update() { int maxAmmmo = 0; if(m_Inventory.CurrentWeaponStatus != null) maxAmmmo = m_Inventory.CurrentWeaponStatus.MaxAmmo; if(m_AmmoLabelSprite != null) m_AmmoLabelSprite.text = m_PlayerEventHandler.CurrentWeaponAmmoCount.Get() + " / " + (maxAmmmo * (m_PlayerEventHandler.CurrentWeaponClipCount.Get())).ToString(); if(m_HealthLabelSprite != null) m_HealthLabelSprite.text = m_Health + "%"; } /// <summary> /// updates the HUD message text and makes it fully visible /// </summary> protected override void OnMessage_HUDText(string message) { if(!ShowTips || m_HintsLabelSprite == null) return; m_PickupMessageMobile = (string)message; m_HintsLabelSprite.text = m_PickupMessageMobile; vp_NGUITween.ColorTo(m_HintsLabelSprite, Color.white, .25f, m_HUDTextTweenHandle, delegate { vp_NGUITween.ColorTo(m_HintsLabelSprite, m_InvisibleColorMobile, FadeDuration, m_HUDTextTweenHandle); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Task3 { class Program { static void Main(string[] args) { Queue q = new Queue(); Queue sorted = new Queue(); q.Enqueue("Nigel"); q.Enqueue("Makuini"); q.Enqueue("Jerome"); q.Enqueue("Makaio"); q.Enqueue("Zane"); string[] names = new string[q.Count]; q.CopyTo(names, 0); Array.Sort(names); foreach(string s in names) { sorted.Enqueue(s); } Console.WriteLine("Sorted"); while (sorted.Count != 0) { Console.WriteLine(sorted.Dequeue()); } } } }
using System; using Nancy; using Cqrsdemo.Queries; using System.Collections.Generic; namespace Cqrsdemo { public class ScheduledEventModule : NancyModule { public ScheduledEventModule () : base("/api/scheduledevents/{id}/participants") { Get["/"] = parameters => { return Negotiate.WithStatusCode(HttpStatusCode.OK) .WithModel(new List<Participant>(){ new Participant("Annelies","De Meyere", new EmailAddress("annelies.demeyere@gmail.com")), new Participant("Erik", "Talboom", new EmailAddress("talboomerik@gmail.com")) }); }; } } }
 namespace Task1 { using System; using System.Linq; class MainProgram { static void Main(string[] args) { } /* * The outer for loop is executed n times, on every iteration the inner while loop is executed again n times * every time start-end difference is -1 until is equal to 0. * So the comlexity is 0(n*n) */ long Compute(int[] arr) { long count = 0; for (int i = 0; i < arr.Length; i++) { int start = 0, end = arr.Length - 1; while (start < end) if (arr[start] < arr[end]) { start++; count++; } else end--; } return count; } } }
// Copyright (c) 2017 Gwaredd Mountain, https://opensource.org/licenses/MIT using System; namespace gw.proto.http { //////////////////////////////////////////////////////////////////////////////// public enum ResponseCode { SwitchingProtocols = 101, OK = 200, MovedPermanently = 301, BadRequest = 400, NotFound = 404, MethodNotAllowed = 405, RequestTimeout = 408, LengthRequired = 411, EntityTooLarge = 413, ImATeaPot = 418, UpgradeRequired = 426, InternalServerError = 500, Unimplemented = 501, } //////////////////////////////////////////////////////////////////////////////// [Serializable()] public class HttpResponseException : Exception { public ResponseCode Code; public HttpResponseException() { Code = ResponseCode.InternalServerError; } public HttpResponseException( ResponseCode code ) { Code = code; } } //////////////////////////////////////////////////////////////////////////////// public class HttpUtils { public static string CodeToString( ResponseCode code ) { switch( code ) { case ResponseCode.OK: return "OK"; case ResponseCode.SwitchingProtocols: return "Switching Protocols"; case ResponseCode.MovedPermanently: return "Moved Permanently"; case ResponseCode.BadRequest: return "Bad Request"; case ResponseCode.NotFound: return "Not Found"; case ResponseCode.MethodNotAllowed: return "Method Not Allowed"; case ResponseCode.RequestTimeout: return "Request Timeout"; case ResponseCode.LengthRequired: return "Length Required"; case ResponseCode.EntityTooLarge: return "Entity Too Large"; case ResponseCode.ImATeaPot: return "I'm a teapot"; case ResponseCode.UpgradeRequired: return "Upgrade Required"; case ResponseCode.InternalServerError: return "Internal Server Error"; case ResponseCode.Unimplemented: return "Unimplemented"; } return "Unknown Error"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class TankMovement : NetworkBehaviour { // Prefab for the projectile public GameObject projectilePrefab; public GameObject invincibleRoundPrefeb; // ============ Private Variables ============ // Tank Health private int health; // Variables for basic projectile private GameObject projectile; private float tankSpeed = 3.0f; // Variable for Invincible Tank Rounds private int invincibleRoundCount; private int maxInvincibleRound; private bool isInvincibleTankRoundActivated; // Variables for Basic Shooting Mechanic private float shootingTimer; private float shootingInterval; // Variables for Unlimited Shots Power Up private bool isUnlimitedShotActivated; private float unlimitedShotTimer; private float unlimitedShotCount; // Use this for initialization void Start () { // Tank Health health = 3; // Shooting Interval Timer shootingTimer = 0.0f; shootingInterval = 1.0f; // Invincible Tank Round invincibleRoundCount = 0; maxInvincibleRound = 1; isInvincibleTankRoundActivated = false; // Unlimited Shots Timer unlimitedShotTimer = 3.0f; unlimitedShotCount = 0.0f; isUnlimitedShotActivated = false; } // Update is called once per frame void Update () { // Check if the Player has Authority over this specific object if (!hasAuthority) { return; } // Check for Controls controls(); } // Function that takes WASD input and moves the tank void controls() { // Move Forward if(Input.GetKey(KeyCode.W)) { transform.Translate(Vector3.right * tankSpeed * Time.deltaTime); } // Move Backward if (Input.GetKey(KeyCode.S)) { transform.Translate(-Vector3.right * tankSpeed * Time.deltaTime); } // Rotate Left if (Input.GetKey(KeyCode.A)) { transform.Rotate(Vector3.up, -1); } // Rotate Right if (Input.GetKey(KeyCode.D)) { transform.Rotate(Vector3.up, 1); } // Shooting Mechanic // - Shoot a projectile towards where the tank is pointing if (Input.GetKeyDown(KeyCode.Space)) { // Unlimited Shot PowerUp if(isUnlimitedShotActivated) { CmdShooting(); } // Spawn a Projectile on the Server else if(shootingTimer > shootingInterval) { CmdShooting(); } } // Add the Timer for Unlimited Shooting PowerUp if(unlimitedShotCount < unlimitedShotTimer) { unlimitedShotCount += Time.deltaTime; } else { isUnlimitedShotActivated = false; shootingInterval = 1.0f; unlimitedShotCount = 0.0f; } // Add the Timer to the shooting mechanic shootingTimer += Time.deltaTime; } // Shooting Function // - Spawns a projectile in front of the tank, launches it forwards [Command] void CmdShooting() { float velocity = 0.0f; // Shoot Invincible Round if(isInvincibleTankRoundActivated && invincibleRoundCount < maxInvincibleRound) { projectile = Instantiate(invincibleRoundPrefeb, this.transform.position + this.transform.right, Quaternion.identity); velocity = 4.0f; // Setting Velocity to the projectile invincibleRoundCount++; // Increasing Invincible Round Shot Count } // Shoot Regular Round else { // Creating the Basic Projectile Object from ProjectilePrefeb isInvincibleTankRoundActivated = false; invincibleRoundCount = 0; projectile = Instantiate(projectilePrefab, this.transform.position + this.transform.right, Quaternion.identity); velocity = 8.0f; // Setting Velocity to the projectile } // Apply the velocity & Spawn Object on Network projectile.GetComponent<Rigidbody>().velocity = this.transform.right * velocity; NetworkServer.Spawn(projectile); // Reset Shooting Cooldown shootingTimer = 0.0f; } // Function that deals with the Collision void OnCollisionEnter(Collision col) { // When it Collides with the Border Wall if (col.gameObject.tag == "InfiniteAmmo") { shootingInterval = 0.0f; isInvincibleTankRoundActivated = false; isUnlimitedShotActivated = true; } // When it Collides with the Border Wall if (col.gameObject.tag == "InvincibleRound") { isUnlimitedShotActivated = false; isInvincibleTankRoundActivated = true; } // When it Collides with the Border Wall if (col.gameObject.tag == "Projectile") { health--; if(health == 0) { Destroy(this.gameObject); } } } }
using System; using System.Linq; using MongoDB.Bson; using Alabo.Domains.Services; using Alabo.Data.People.Merchants.Domain.Entities; using Alabo.Domains.Entities; namespace Alabo.Data.People.Merchants.Domain.Services { public interface IChainMerchantService : IService<ChainMerchant, ObjectId> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class IngresarHabilidad : System.Web.UI.Page { webservicio.Webservice2Client conec = new webservicio.Webservice2Client(); protected void Page_Load(object sender, EventArgs e) { } protected void Button8_Click(object sender, EventArgs e) { string aaaa = codhab.Text; string bbbb = nombrehab.Text; string cccc = resumen.Text; string ssss = karma.Text; conec.IngresarHabilidad(aaaa, bbbb, cccc, ssss); codhab.Text = ""; nombrehab.Text = ""; resumen.Text = ""; karma.Text = ""; } protected void Button10_Click(object sender, EventArgs e) { string aa = codcono.Text; string bb = nomcono.Text; string cc = descono.Text; string ss = codhabi.Text; conec.IngresarConocimiento(aa, bb, cc, ss); codcono.Text = ""; nomcono.Text = ""; descono.Text = ""; codhabi.Text = ""; } protected void Button9_Click(object sender, EventArgs e) { } protected void Button11_Click(object sender, EventArgs e) { string[] Lista; Lista = conec.VerHabilidad("", h1.Text); TableCell c1 = new TableCell(); c1.Text = "Codigo"; TableCell c2 = new TableCell(); c2.Text = "Nombre"; TableCell c3 = new TableCell(); c3.Text = "Resumen"; TableCell c4 = new TableCell(); c4.Text = "Karma"; TableRow fila = new TableRow(); fila.Controls.Add(c1); fila.Controls.Add(c2); fila.Controls.Add(c3); fila.Controls.Add(c4); Table1.Controls.Add(fila); for (int i = 0; i < Lista.Length; i = i + 4) { TableCell casilla1 = new TableCell(); casilla1.Text = Lista[i]; TableCell casilla2 = new TableCell(); casilla2.Text = Lista[i + 1]; TableCell casilla3 = new TableCell(); casilla3.Text = Lista[i + 2]; TableCell casilla4 = new TableCell(); casilla4.Text = Lista[i + 3]; TableRow fila1 = new TableRow(); fila1.Controls.Add(casilla1); fila1.Controls.Add(casilla2); fila1.Controls.Add(casilla3); fila1.Controls.Add(casilla4); Table1.Controls.Add(fila1); } } protected void Button12_Click(object sender, EventArgs e) { string[] Lista2; Lista2 = conec.VerConocimiento("", h2.Text); TableCell c1 = new TableCell(); c1.Text = "Codigo"; TableCell c2 = new TableCell(); c2.Text = "Nombre"; TableCell c3 = new TableCell(); c3.Text = "Descripcion"; TableRow fila = new TableRow(); fila.Controls.Add(c1); fila.Controls.Add(c2); fila.Controls.Add(c3); Table2.Controls.Add(fila); for (int i = 0; i < Lista2.Length; i = i + 4) { TableCell casilla1 = new TableCell(); casilla1.Text = Lista2[i]; TableCell casilla2 = new TableCell(); casilla2.Text = Lista2[i + 1]; TableCell casilla3 = new TableCell(); casilla3.Text = Lista2[i + 2]; TableRow fila1 = new TableRow(); fila1.Controls.Add(casilla1); fila1.Controls.Add(casilla2); fila1.Controls.Add(casilla3); Table2.Controls.Add(fila1); } } protected void Button13_Click(object sender, EventArgs e) { string[] Lista2; Lista2 = conec.VerConocimiento("", h2.Text); TableCell c1 = new TableCell(); c1.Text = "Codigo"; TableCell c2 = new TableCell(); c2.Text = "Nombre"; TableCell c3 = new TableCell(); c3.Text = "Descripcion"; TableRow fila = new TableRow(); fila.Controls.Add(c1); fila.Controls.Add(c2); fila.Controls.Add(c3); Table2.Controls.Add(fila); for (int i = 0; i < Lista2.Length; i = i + 4) { TableCell casilla1 = new TableCell(); casilla1.Text = Lista2[i]; TableCell casilla2 = new TableCell(); casilla2.Text = Lista2[i + 1]; TableCell casilla3 = new TableCell(); casilla3.Text = Lista2[i + 2]; TableRow fila1 = new TableRow(); fila1.Controls.Add(casilla1); fila1.Controls.Add(casilla2); fila1.Controls.Add(casilla3); Table2.Controls.Add(fila1); } } protected void Button14_Click(object sender, EventArgs e) { int s2 = conec.SeleccionarKarma("", t10.Text); lkarma.Text = Convert.ToString(s2); } protected void Button15_Click(object sender, EventArgs e) { string s = s1.Text; string d = d1.Text; conec.AgregarConocimiento(s, d); s1.Text = ""; d1.Text = ""; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Alps.Domain.Common; using Alps.Domain.ProductMgr; using Alps.Domain.AccountingMgr; using Alps.Domain.DistributionMgr; using System.ComponentModel.DataAnnotations; namespace Alps.Domain.SaleMgr { public class SaleOrder : EntityBase { public Customer Customer { get; set; } [Display(Name="客户")] public Guid CustomerID { get; set; } [Display(Name="下单时间")] public DateTime OrderTime { get; set; } [Display(Name="订单状态")] public SaleOrderState State { get; set; } [Display(Name="配送地址")] public string DeliveryAddress { get; set; } public ICollection<SaleOrderItem> Items { get; set; } public ICollection<DistributionVoucher> DeliveryVouchers { get; set; } public SaleOrder ParentSaleOrder { get; set; } public SaleOrder() { Items = new HashSet<SaleOrderItem>(); DeliveryVouchers = new HashSet<DistributionVoucher>(); } public static SaleOrder Create(Guid customerID,SaleOrder parentSaleOrder = null) { SaleOrder saleOrder = new SaleOrder(); saleOrder.CustomerID = customerID; saleOrder.Items = new HashSet<SaleOrderItem>(); saleOrder.OrderTime = DateTime.Now; saleOrder.ParentSaleOrder = parentSaleOrder; return saleOrder; } public void UpdateItems(Guid commodityID, decimal count, decimal weight, Guid unitID, decimal price) { SaleOrderItem existingItem = this.Items.FirstOrDefault(p => p.CommodityID == commodityID); if (existingItem == null) { existingItem = new SaleOrderItem(); this.Items.Add(existingItem); } existingItem.CommodityID = commodityID; existingItem.Quantity += new Quantity(count, weight); existingItem.UnitID = unitID; existingItem.Price = price; if (existingItem.Quantity.Count == 0) { this.Items.Remove(existingItem); } if (existingItem.Quantity.IsNegative()) throw new DomainException("订单数量不能小于零"); } public void Confirm() { this.State = SaleOrderState.Confirm; } public void AddItem(Guid commodityID,Quantity quantity,decimal price,string remark) { var item=new SaleOrderItem(){CommodityID=commodityID,Quantity=quantity,Price=price,Remark=remark}; this.Items.Add(item); } public void RemoveItem(Guid commodityID,Quantity quantity) { var item=this.Items.FirstOrDefault(p => p.CommodityID == commodityID); if (item == null) throw new DomainException("订单中无此物品"); this.Items.Remove(item); } private void UpdateItem(Guid itemID,Guid commodityID,Quantity quantity,decimal price,string remark) { if (itemID == Guid.Empty) throw new ArgumentException("参数不含主键"); var existingSaleOrderItem = this.Items.FirstOrDefault(p => p.ID == itemID); if (existingSaleOrderItem == null) throw new DomainException("无此主键实体"); existingSaleOrderItem.CommodityID = commodityID; existingSaleOrderItem.Quantity = quantity; existingSaleOrderItem.Price = price; existingSaleOrderItem.Remark = remark; } public void UpdateItems(IEnumerable<SaleOrderItem> items) { var existingItems = this.Items.ToList(); var updatedItems = this.Items.Where(p => items.Any(k => k.ID == p.ID)).ToList(); var addedItems = items.Where(p => !this.Items.Any(k => k.ID == p.ID)).ToList(); var deletedItems = this.Items.Where(p => !items.Any(k => k.ID == p.ID)).ToList(); deletedItems.ForEach(p => this.Items.Remove(p)); addedItems.ForEach(p => this.AddItem(p.CommodityID,p.Quantity,p.Price,p.Remark)); updatedItems.ForEach(p => this.UpdateItem(p.ID,p.CommodityID,p.Quantity,p.Price,p.Remark)); } public void UpdateBy(SaleOrder saleOrder) { this.CustomerID = saleOrder.CustomerID; this.DeliveryAddress = saleOrder.DeliveryAddress; this.UpdateItems(saleOrder.Items); } } }
using InoDrive.Domain.Entities; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InoDrive.Domain.Contexts { public class InoDriveContext : IdentityDbContext<ApplicationUser> { public InoDriveContext() : base("InoDirveContext") { } public DbSet<Client> Clients { get; set; } public DbSet<RefreshToken> RefreshTokens { get; set; } public DbSet<Bid> Bids { get; set; } public DbSet<Place> Places { get; set; } public DbSet<Comment> Comments { get; set; } public DbSet<Trip> Trips { get; set; } public DbSet<WayPoint> WayPoint { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace DPYM { /// <summary> /// 加载器,负责场景、资源的加载工作 /// </summary> public class Loader : MonoBehaviour { public Loader() { } /// <summary> /// 是否完成加载 /// </summary> public virtual bool Ready { get { return true; } } /// <summary> /// 开始加载过程 /// </summary> /// <returns></returns> public virtual bool Begin() { return true; } /// <summary> /// 结束加载操作,释放资源等 /// </summary> /// <returns></returns> public virtual bool End() { return true; } /// <summary> /// 更新过程 /// </summary> protected void Update() { } } }
using System; namespace EventLite.MongoDB.DTO { internal class CommitDTO { public Guid StreamId { get; set; } public int CommitNumber { get; set; } public long Timestamp { get; set; } public object Event { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace OnlineShopping.Models { public class MyOrderModel { public int OrderID { get; set; } public int UserID { get; set; } public double OrderTotal { get; set; } public DateTime OrderDate { get; set; } public string Image { get; set; } public List<CartModel> CartModel { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MinnerTask2 { class Program { static void Main(string[] args) { Dictionary<string, decimal> mine = new Dictionary<string, decimal>(); string userInput = Console.ReadLine(); //loops till "stop" is entered as a resource value while (userInput != "stop") { decimal amount = decimal.Parse(Console.ReadLine()); //if resource exists if (mine.ContainsKey(userInput)) { mine[userInput] += amount; } //if resource does not exists else { mine[userInput] = amount; } //waits for the next loop userInput = Console.ReadLine(); } //prints the result ( if any) foreach (string key in mine.Keys) { Console.WriteLine($"{key} -> {mine[key]}"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //"http://localhost:5000/echo"; // public class SaveUserProgressAtUniverseScene : MonoBehaviour { [SerializeField] private string saveLastSceneURL = "http://localhost/saveLastScene.php"; private bool isAuthorized; // Start is called before the first frame update void Start() { isAuthorized = PlayerPrefs.GetInt("isAuthorized") == 1 ? true : false; if (isAuthorized) { //save scene to DB WWWForm form = new WWWForm(); form.AddField("userId", PlayerPrefs.GetInt("id_user")); form.AddField("sceneId", 10); WWW www = new WWW(saveLastSceneURL, form); } } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _04.Telephony { public class Smartphone : ICallable, IBrowsable { public string Browse(string website) { if(website.Any(w => char.IsDigit(w))) { return "Invalid URL!"; } return $"Browsing: {website}!"; } public string Call(string number) { if(!number.All(n => char.IsDigit(n))) { return "Invalid number!"; } return $"Calling... {number}"; } } }
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace Appnotics.Library.UI.Converters { /// <summary> /// Converter that allows a UIE to be collapsed if the bound value is null /// </summary> public class CollapseIfZeroConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int) { int iValue = (int)value; return (iValue == 0) ? Visibility.Collapsed : Visibility.Visible; } if (value is double) { double dValue = (double)value; return (dValue == 0) ? Visibility.Collapsed : Visibility.Visible; } if (value is long) { long lValue = (long)value; return (lValue == 0) ? Visibility.Collapsed : Visibility.Visible; } if (value is decimal) { decimal dValue = (decimal)value; return (dValue == 0) ? Visibility.Collapsed : Visibility.Visible; } return Visibility.Visible; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return Binding.DoNothing; } } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(Actor))] public class ActorController : MonoBehaviour { [SerializeField] private Actor myActor; public Actor MyActor { get { return myActor; } } protected virtual void Awake() { } protected virtual void Start() { } protected virtual void Update() { } protected virtual void OnDestroy() { } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Payment.Infrastructure.Migrations { public partial class initDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "tblPayments", columns: table => new { Id = table.Column<long>(type: "bigint", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Card_Number = table.Column<string>(type: "nvarchar(max)", nullable: true), Card_CardHolderName = table.Column<string>(type: "nvarchar(max)", nullable: true), Card_ExpirationDate = table.Column<DateTime>(type: "datetime2", nullable: true), Card_SecurityCode = table.Column<string>(type: "nvarchar(max)", nullable: true), Amount = table.Column<decimal>(type: "decimal(18,2)", nullable: false), IsDeleted = table.Column<bool>(type: "bit", nullable: false), CurrentState = table.Column<string>(type: "nvarchar(max)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_tblPayments", x => x.Id); }); migrationBuilder.CreateTable( name: "tblPaymentStates", columns: table => new { Id = table.Column<long>(type: "bigint", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), RequestId = table.Column<long>(type: "bigint", nullable: false), State = table.Column<string>(type: "nvarchar(450)", nullable: false), At = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false) }, constraints: table => { table.PrimaryKey("PK_tblPaymentStates", x => x.Id); table.ForeignKey( name: "FK_tblPaymentStates_tblPayments_RequestId", column: x => x.RequestId, principalTable: "tblPayments", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_tblPaymentStates_RequestId_State_At", table: "tblPaymentStates", columns: new[] { "RequestId", "State", "At" }, unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "tblPaymentStates"); migrationBuilder.DropTable( name: "tblPayments"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class E_StockInventory: E_BaseModel { /// <summary> /// 作业区ID /// </summary> public int operationid { get; set; } /// <summary> /// 班组ID /// </summary> public int classid { get; set; } /// <summary> /// 公司ID /// </summary> public int companyid { get; set; } /// <summary> /// 商品名称 /// </summary> public string pname { get; set; } /// <summary> /// 入库总量 /// </summary> public int intotal { get; set; } /// <summary> /// 出库总量 /// </summary> public int outtotal { get; set; } /// <summary> /// 库存结余 /// </summary> public int surplusstock { get; set; } /// <summary> /// 精确匹配 /// </summary> public string pnameall { get; set; } } }
// <copyright file="SmartLibraryAPIData.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> /// <summary> /// Register Model /// </summary> namespace SmartLibrary.Models.AGModels { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Register API Model /// </summary> public class SmartLibraryAPIData { /// <summary> /// Gets or sets the SmartLibraryId value. /// </summary> public object SmartLibraryId { get; set; } /// <summary> /// Gets or sets the ProfileImage value. /// </summary> public object ProfileImage { get; set; } /// <summary> /// Gets or sets the Gender value. /// </summary> public object Gender { get; set; } /// <summary> /// Gets or sets the Phone value. /// </summary> public object Phone { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuSoundManager : MonoBehaviour { public MenuFXController fx; public MenuMusicController music; private bool first = true; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void PlayMenuMusic() { music.PlayMusic(); } public void PlayButtonFX() { fx.PlayButtonFX(); } public void PlayButtonHigh() { if (!first) fx.PlayButtonHighlight(); else first = false; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Bloodhound.Models; using Bloodhound.Core.Model; using Newtonsoft.Json; using System.IO; namespace Bloodhound.Controllers { public class HomeController : Controller { private readonly BloodhoundContext _context; public HomeController(BloodhoundContext context) { _context = context; } public IActionResult Index() { JsonSerializer jsonSerializer = JsonSerializer.Create(); StringWriter sw = new StringWriter(); jsonSerializer.Serialize(sw, this._context.v_OffenderLastLocation.ToList()); ViewData["LastLocations"] = sw.ToString(); return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public float speed = 15f; public float mapWidth = 5.5f; //half of the width private Rigidbody2D rb; private AudioSource audio; private float collisionVolumeLimiter = 40f; void Start() { rb = GetComponent<Rigidbody2D>(); audio = GetComponent<AudioSource>(); if (audio == null) audio = gameObject.AddComponent<AudioSource>(); } void FixedUpdate() { float x = Input.GetAxis("Horizontal") * Time.fixedDeltaTime * speed; Vector2 newPosition = rb.position + Vector2.right * x; newPosition.x = Mathf.Clamp(newPosition.x, -mapWidth, mapWidth); rb.MovePosition(newPosition); //Same as going 0 to the left and 1 to the right if (Input.anyKey) { rb.AddForce(Vector2.up * 50); } } void OnCollisionEnter2D(Collision2D collisionInfo) { rb.bodyType = RigidbodyType2D.Dynamic; rb.mass = 0.001f; rb.gravityScale = 10; audio.volume = collisionInfo.relativeVelocity.magnitude/ collisionVolumeLimiter; audio.PlayOneShot(Resources.Load<AudioClip>("DM-CGS-43")); audio.PlayOneShot(Resources.Load<AudioClip>("death")); FindObjectOfType<GameManager>().EndGame(); } }
using Datos; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Configuracion; namespace Negocio { public class Aeronave { public int idAeronave {get;set;} public string matriculaAeronave { get; set; } public DateTime fechaAltaAeronave { get; set; } public DateTime fechaBajaDefinitivaAeronave { get; set; } public Boolean bajaFueraServicioAeronave { get; set; } public Boolean bajaVidaUtilAeronave { get; set; } public Decimal kgsDispAeronave { get; set; } public int idModelo { get; set; } public int idTipoServicio { get; set; } public DataTable obtenerHabilitadas() { string[] parametros = { "@fechaActual" }; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronavesHabilitadas]", parametros, ConfiguracionGlobal.FechaSistema); } public List<Aeronave> obtenerHabilitadasLista() { List<Aeronave> aeronaves = new List<Aeronave>(); DataTable dt = obtenerHabilitadas(); foreach (DataRow row in dt.Rows) { Aeronave a = new Aeronave(); a.idAeronave = Int32.Parse(row["AERO_ID"].ToString()); a.matriculaAeronave = row["AERO_MATRICULA"].ToString(); a.fechaAltaAeronave = DateTime.Parse(row["AERO_FECHA_ALTA"].ToString()); a.fechaBajaDefinitivaAeronave = convertirFecha(row["AERO_FECHA_BAJA_DEFINITIVA"].ToString()); a.bajaFueraServicioAeronave = Boolean.Parse(row["AERO_BAJA_FUERA_SERVICIO"].ToString()); a.bajaVidaUtilAeronave = Boolean.Parse(row["AERO_BAJA_VIDA_UTIL"].ToString()); a.kgsDispAeronave = Decimal.Parse(row["AERO_KGS_DISP"].ToString()); a.idModelo = Int32.Parse(row["MODELO_ID"].ToString()); a.idTipoServicio = Int32.Parse(row["TIPO_SERVICIO_ID"].ToString()); aeronaves.Add(a); } return aeronaves; } private DateTime convertirFecha(string f) { if (f == "") { return DateTime.MinValue; } return DateTime.Parse(f); } public bool tieneViajesEntreHorarios(DateTime fechaSalida, DateTime fechaLlegadaEstimada, int idAero) { string[] parametros = { "@idAero","@fechaDesde","@fechaHasta" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spViajesDeAeronaveEnFranjaHoraria]", parametros, idAero, fechaSalida, fechaLlegadaEstimada); return dt.Rows.Count > 0; } public void almacenar() { string[] parametros = { "@aeroID","@aeroMatricula","@aeroFechaAlta","@aeroFechaBajaFueraServicio" ,"@aeroBajaVidaUtil","@aeroFechaBajaDefinitiva","@aeroKGSDisponibles","@modeloID", "@tipoServicioID"}; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spInsertarAeronaves]", parametros, this.idAeronave, this.matriculaAeronave, this.fechaAltaAeronave, this.fechaBajaDefinitivaAeronave, this.bajaVidaUtilAeronave, this.bajaFueraServicioAeronave, this.kgsDispAeronave, this.idModelo); } public void almacenarCambios() { string[] parametros = { "@aeroID","@aeroMatricula","@aeroFechaAlta","@aeroFechaBajaFueraServicio" ,"@aeroBajaVidaUtil","@aeroFechaBajaDefinitiva","@aeroKGSDisponibles","@modeloID", "@tipoServicioID"}; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spActualizarAeronaves]", parametros, this.idAeronave, this.matriculaAeronave, this.fechaAltaAeronave, this.fechaBajaDefinitivaAeronave, this.bajaVidaUtilAeronave, this.bajaFueraServicioAeronave, this.kgsDispAeronave, this.idModelo); } public void eliminar() { this.bajaVidaUtilAeronave = true; this.almacenarCambios(); } public DataTable obtenerAeronavesDGV() { string[] parametros = { "@fechaActual" }; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronavesParaDGV]", parametros, ConfiguracionGlobal.FechaSistema); } public DataTable obtenerAeronavesFiltro(string matricula, int? fabricante, int? modelo, int? tipoServicio, decimal kgDesde, decimal kgHasta, int? soloServicio) { string[] parametros = { "@matricula", "@fabricante", "@modelo", "@tipoServicio", "@kgDesde", "@kgHasta", "@soloServicio", "@fechaActual"}; DatosSistema datos = new DatosSistema(); return datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronavesFiltro]", parametros, "%"+matricula+"%", fabricante != null ? (int)fabricante : (object)DBNull.Value, modelo != null ? (int)modelo : (object)DBNull.Value, tipoServicio != null ? (int)tipoServicio : (object)DBNull.Value, kgDesde, kgHasta, soloServicio != null ? (int)soloServicio : (object)DBNull.Value, ConfiguracionGlobal.FechaSistema); } public Aeronave obtenerAeronavePorId(int idAeronave) { Aeronave a = new Aeronave(); string[] parametros = { "@idAeronave" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronavePorId]", parametros, idAeronave); if (dt.Rows.Count != 0) { a.idAeronave = Int32.Parse(dt.Rows[0]["AERO_ID"].ToString()); a.matriculaAeronave = dt.Rows[0]["AERO_MATRICULA"].ToString(); a.fechaAltaAeronave = DateTime.Parse(dt.Rows[0]["AERO_FECHA_ALTA"].ToString()); a.fechaBajaDefinitivaAeronave = convertirFecha(dt.Rows[0]["AERO_FECHA_BAJA_DEFINITIVA"].ToString()); a.bajaFueraServicioAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_FUERA_SERVICIO"].ToString()); a.bajaVidaUtilAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_VIDA_UTIL"].ToString()); a.kgsDispAeronave = Decimal.Parse(dt.Rows[0]["AERO_KGS_DISP"].ToString()); a.idModelo = Int32.Parse(dt.Rows[0]["MODELO_ID"].ToString()); a.idTipoServicio = Int32.Parse(dt.Rows[0]["TIPO_SERVICIO_ID"].ToString()); } else { return null; } return a; } public bool tieneViajes(int idAeronave) { string[] parametros = { "@idAeronave" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spObtenerViajesPorAeronave]", parametros, idAeronave); return dt.Rows.Count > 0; } public void bajaPorFueraDeServicio(int idAero, DateTime baja, DateTime reinicio) { string[] parametros = { "@idAero", "@baja", "@reinicio" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spBajaPorFueraDeServicio]", parametros, idAero, baja, reinicio); } public void cancelarPorFueraServicio(int idAero, DateTime baja, DateTime reinicio, int idUsuario) { string[] parametros = { "@idAero", "@baja", "@reinicio", "@motivo", "@idUsuario", "@fechaActual"}; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spCancelarPorFueraServicio]", parametros, idAero, baja, reinicio, "La aeronave estará fuera de servicio en la fecha del viaje.", idUsuario, ConfiguracionGlobal.FechaSistema); } public Aeronave obtenerAeronaveReemplazoFueraServicio(int idAero, DateTime baja, DateTime reinicio) { Aeronave a = new Aeronave(); string[] parametros = { "@idAero", "@baja", "@reinicio" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronaveReemplazoFueraServicio]", parametros, idAero, baja, reinicio); if (dt.Rows.Count != 0) { a.idAeronave = Int32.Parse(dt.Rows[0]["AERO_ID"].ToString()); a.matriculaAeronave = dt.Rows[0]["AERO_MATRICULA"].ToString(); a.fechaAltaAeronave = DateTime.Parse(dt.Rows[0]["AERO_FECHA_ALTA"].ToString()); a.fechaBajaDefinitivaAeronave = convertirFecha(dt.Rows[0]["AERO_FECHA_BAJA_DEFINITIVA"].ToString()); a.bajaFueraServicioAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_FUERA_SERVICIO"].ToString()); a.bajaVidaUtilAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_VIDA_UTIL"].ToString()); a.kgsDispAeronave = Decimal.Parse(dt.Rows[0]["AERO_KGS_DISP"].ToString()); a.idModelo = Int32.Parse(dt.Rows[0]["MODELO_ID"].ToString()); a.idTipoServicio = Int32.Parse(dt.Rows[0]["TIPO_SERVICIO_ID"].ToString()); } else { return null; } return a; } public void reemplazarViajesPorFueraServicio(int idAero, int idReemplazo, DateTime baja, DateTime reinicio) { string[] parametros = { "@idAero", "@idReemplazo", "@baja", "@reinicio" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spReemplazarViajesPorFueraServicio]", parametros, idAero,idReemplazo, baja, reinicio); } public Aeronave obtenerAeronavePorMatricula(string matricula) { Aeronave a = new Aeronave(); string[] parametros = { "@matricula" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronavePorMatricula]", parametros, matricula); if (dt.Rows.Count != 0) { a.idAeronave = Int32.Parse(dt.Rows[0]["AERO_ID"].ToString()); a.matriculaAeronave = dt.Rows[0]["AERO_MATRICULA"].ToString(); a.fechaAltaAeronave = DateTime.Parse(dt.Rows[0]["AERO_FECHA_ALTA"].ToString()); a.fechaBajaDefinitivaAeronave = convertirFecha(dt.Rows[0]["AERO_FECHA_BAJA_DEFINITIVA"].ToString()); a.bajaFueraServicioAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_FUERA_SERVICIO"].ToString()); a.bajaVidaUtilAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_VIDA_UTIL"].ToString()); a.kgsDispAeronave = Decimal.Parse(dt.Rows[0]["AERO_KGS_DISP"].ToString()); a.idModelo = Int32.Parse(dt.Rows[0]["MODELO_ID"].ToString()); a.idTipoServicio = Int32.Parse(dt.Rows[0]["TIPO_SERVICIO_ID"].ToString()); } else { return null; } return a; } public void insertarAeronaveYButacas(Aeronave aeronaveActual, int pasillo, int ventanilla) { string[] parametros = { "@matricula","@tipoServicio","@modelo","@kgsDisp","@fechaAlta","@pasillo","@ventanilla"}; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spInsertarAeronaveYButacas]", parametros, aeronaveActual.matriculaAeronave, aeronaveActual.idTipoServicio, aeronaveActual.idModelo, aeronaveActual.kgsDispAeronave, aeronaveActual.fechaAltaAeronave, pasillo, ventanilla); } public void modificarAeronaveYButacas(Aeronave aeronaveActual, int pasillo, int ventanilla) { string[] parametros = {"@idAero", "@matricula", "@tipoServicio", "@modelo", "@kgsDisp", "@pasillo", "@ventanilla" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spModificarAeronaveYButacas]", parametros,aeronaveActual.idAeronave, aeronaveActual.matriculaAeronave, aeronaveActual.idTipoServicio, aeronaveActual.idModelo, aeronaveActual.kgsDispAeronave, pasillo, ventanilla); } public void bajaPorVidaUtil(int idAero, DateTime fechaBaja) { string[] parametros = { "@idAero", "@fechaBaja" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spBajaPorVidaUtil]", parametros, idAero,fechaBaja); } public void cancelarPorBaja(int idAero, DateTime baja, int idUsuario) { string[] parametros = { "@idAero", "@baja", "@motivo", "@idUsuario", "@fechaActual" }; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spCancelarPorBaja]", parametros, idAero, baja, "La aeronave ha sido dada de baja definitivamente.", idUsuario, ConfiguracionGlobal.FechaSistema); } public Aeronave obtenerAeronaveReemplazoBajaVidaUtil(int idAero, DateTime baja) { Aeronave a = new Aeronave(); string[] parametros = { "@idAero", "@baja" }; DatosSistema datos = new DatosSistema(); DataTable dt = datos.getDatosTabla("[INFONIONIOS].[spObtenerAeronaveReemplazoBajaVidaUtil]", parametros, idAero, baja); if (dt.Rows.Count != 0) { a.idAeronave = Int32.Parse(dt.Rows[0]["AERO_ID"].ToString()); a.matriculaAeronave = dt.Rows[0]["AERO_MATRICULA"].ToString(); a.fechaAltaAeronave = DateTime.Parse(dt.Rows[0]["AERO_FECHA_ALTA"].ToString()); a.fechaBajaDefinitivaAeronave = convertirFecha(dt.Rows[0]["AERO_FECHA_BAJA_DEFINITIVA"].ToString()); a.bajaFueraServicioAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_FUERA_SERVICIO"].ToString()); a.bajaVidaUtilAeronave = Boolean.Parse(dt.Rows[0]["AERO_BAJA_VIDA_UTIL"].ToString()); a.kgsDispAeronave = Decimal.Parse(dt.Rows[0]["AERO_KGS_DISP"].ToString()); a.idModelo = Int32.Parse(dt.Rows[0]["MODELO_ID"].ToString()); a.idTipoServicio = Int32.Parse(dt.Rows[0]["TIPO_SERVICIO_ID"].ToString()); } else { return null; } return a; } public void reemplazarViajesPorBaja(int idAero, int idReemplazo, DateTime baja) { string[] parametros = { "@idAero", "@idReemplazo", "@baja"}; DatosSistema datos = new DatosSistema(); datos.Ejecutar("[INFONIONIOS].[spReemplazarViajesPorBaja]", parametros, idAero, idReemplazo, baja); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using IWorkFlow.DataBase; namespace IWorkFlow.ORM { [Serializable] [DataTableInfo("B_OA_Notice_FileType_R", "id")] public class B_OA_Notice_FileType_R : QueryInfo { /// <summary> /// 主键 /// </summary> [DataField("id", "B_OA_Notice_FileType_R", false)] public int id { get { return _id; } set { _id = value; } } private int _id; /// <summary> /// 文章ID /// </summary> [DataField("noticeId", "B_OA_Notice_FileType_R")] public string noticeId { get { return _noticeId; } set { _noticeId = value; } } private string _noticeId; /// <summary> /// 文件夹ID /// </summary> [DataField("fileTypeId", "B_OA_Notice_FileType_R")] public string fileTypeId { get { return _fileTypeId; } set { _fileTypeId = value; } } private string _fileTypeId; } }
using Microsoft.Extensions.Caching.Memory; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace RabbitMQ.Services { public class Consumer { private readonly IMemoryCache _memoryCache; ConnectionFactory _factory { get; set; } IConnection _connection { get; set; } IModel _channel { get; set; } public Consumer(IMemoryCache memoryCache) { _memoryCache = memoryCache; } public void ReceiveMessageFromQ() { try { _factory = new ConnectionFactory() { HostName = "54.202.17.105" }; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); { _channel.QueueDeclare(queue: "counter", durable: true, exclusive: false, autoDelete: false, arguments: null); _channel.BasicQos(prefetchSize: 0, prefetchCount: 3, global: false); var consumer = new EventingBasicConsumer(_channel); consumer.Received += async (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Dictionary<string, int> messages = null; _memoryCache.TryGetValue<Dictionary<string, int>>("messages", out messages); if (messages == null) messages = new Dictionary<string, int>(); Console.WriteLine(" [x] Received {0}", message); Thread.Sleep(3000); messages.Remove(message); _memoryCache.Set<Dictionary<string, int>>("messages", messages); _channel.BasicAck(ea.DeliveryTag, false); }; _channel.BasicConsume(queue: "counter", autoAck: false, consumer: consumer); } } catch (Exception ex) { Console.WriteLine($"{ex.Message} | {ex.StackTrace}"); } } } }
using GridPlacing; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; [CustomEditor(typeof(GridPlacer))] public class GridPlacer_Editor : Editor { bool showGridMenu = true; bool showCreditsMenu = false; bool showVisibilityOptions = false; GridPlacer gridPlacerScript; Grid grid; public override void OnInspectorGUI() { gridPlacerScript = (GridPlacer)target; //-- Hide Grid Component if (Selection.activeGameObject.GetComponent<Grid>() != null) grid = Selection.activeGameObject.GetComponent<Grid>(); grid.hideFlags = HideFlags.HideInInspector; //-- EditorGUILayout.Space(); GridPlacingMasterEditor.TitleCreator("GridPlacer", 10, true); GridPlacingMasterEditor.DrawUILine(Color.white, 2, 20); gridPlacerScript.gridID = EditorGUILayout.IntField("Grid ID", gridPlacerScript.gridID); foreach (GridPlacer item in GameObject.FindObjectsOfType<GridPlacer>()) { if (item.gridID == gridPlacerScript.gridID) { if (item != gridPlacerScript) { EditorGUILayout.HelpBox("You can't have same ID in different grids", MessageType.Error); if (EditorApplication.isPlaying) { UnityEditor.EditorApplication.isPlaying = false; Debug.LogError("You can't have same ID in different grids: " + item.name + " || " + gridPlacerScript.name); } } } } gridPlacerScript.grid2D = EditorGUILayout.Toggle("Grid2D", gridPlacerScript.grid2D); EditorGUILayout.Space(); showGridMenu = EditorGUILayout.Foldout(showGridMenu, "Grid Options", true); if (showGridMenu) { EditorGUILayout.Space(); if (gridPlacerScript.grid2D) { Grid2D(); } else { Grid3D(); } EditorGUILayout.Space(); gridPlacerScript.gridCellLayout = (Grid.CellLayout)EditorGUILayout.EnumPopup("Grid Layout", gridPlacerScript.gridCellLayout); grid.cellLayout = gridPlacerScript.gridCellLayout; /* gridPlacerScript.gridCellSwizzle = (Grid.CellSwizzle)EditorGUILayout.EnumPopup("Grid Swizzle", gridPlacerScript.gridCellSwizzle); grid.cellSwizzle = gridPlacerScript.gridCellSwizzle;*/ gridPlacerScript.keepObjectInGrid = EditorGUILayout.Toggle(new GUIContent("Keep Object in Grid", "Keep object in grid if grid is moved."), gridPlacerScript.keepObjectInGrid); gridPlacerScript.placeObjectRelativeToGridPosition = EditorGUILayout.Toggle(new GUIContent("Place Object Relative To Grid Position", "Place Object Relative To Grid Position."), gridPlacerScript.placeObjectRelativeToGridPosition); } GridPlacingMasterEditor.DrawUILine(Color.gray, 1.5f, 6); showVisibilityOptions = EditorGUILayout.Foldout(showVisibilityOptions, "Visibility Options", true); if (showVisibilityOptions) { gridPlacerScript.drawGridIDText = EditorGUILayout.Toggle("Draw Grid ID Text", gridPlacerScript.drawGridIDText); gridPlacerScript.drawGridPoints = EditorGUILayout.Toggle("Draw Grid Points", gridPlacerScript.drawGridPoints); if (gridPlacerScript.drawGridPoints) { gridPlacerScript.visibilityRange = EditorGUILayout.Vector2IntField(new GUIContent("Visibility Range", "Don't increase too much or it will lag"), gridPlacerScript.visibilityRange); gridPlacerScript.gridPointsColor = EditorGUILayout.ColorField("Points Color", gridPlacerScript.gridPointsColor); //gridPlacerScript.radiusGridPoints = EditorGUILayout.FloatField("Points Radius", gridPlacerScript.radiusGridPoints); gridPlacerScript.radiusGridPoints = EditorGUILayout.Slider("Radius Grid Points", gridPlacerScript.radiusGridPoints, 0.00f, 0.55f); } if (GUILayout.Button("Generate Visible Grid")) { CreateVisibileGrid(); } } GridPlacingMasterEditor.DrawUILine(Color.gray, 1.5f, 6); showCreditsMenu = EditorGUILayout.Foldout(showCreditsMenu, "Credits", true); if (showCreditsMenu) { GridPlacingMasterEditor.TitleCreator("Made by: Joan Ortiga Balcells", 2, true, TextAnchor.MiddleCenter); GridPlacingMasterEditor.TitleCreator("Personal Links:"); EditorGUILayout.Space(); if (GUILayout.Button("LinkedIN")) { Application.OpenURL("www.linkedin.com/in/joanortigabalcells"); } if (GUILayout.Button("Itch.io")) { Application.OpenURL("https://joanstark.itch.io/"); } if (GUILayout.Button("GitHub")) { Application.OpenURL("https://github.com/JoanStark"); } EditorGUILayout.Space(); EditorGUILayout.Space(); GUIStyle versionBox = new GUIStyle(EditorStyles.helpBox); GUIStyle a = new GUIStyle(EditorStyles.helpBox); a.alignment = TextAnchor.MiddleCenter; a.fontStyle = FontStyle.Bold; a.fontSize = 15; Rect r = EditorGUILayout.GetControlRect(GUILayout.Height(10 + 2)); r.height = 42; r.y += 10 / 2; r.x -= 2; r.xMin = 0; r.width += 6; EditorGUI.DrawRect(r, Color.black); EditorGUILayout.LabelField("Vesion: 1.0.0", a); //DrawUILine(Color.gray, 0.5f, 0); //TitleCreator("Vesion: 1.0.0", 1, true, TextAnchor.MiddleCenter); //DrawUILine(Color.gray, 0.5f, 0); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Look for Updates")) { Application.OpenURL("https://github.com/JoanStark"); } } } private void Grid2D() { GridPlacingMasterEditor.TitleCreator("2D GRID", 5, true); gridPlacerScript.gridCellSize2D = EditorGUILayout.Vector2Field("Grid Cell Size", gridPlacerScript.gridCellSize2D); grid.cellSize = gridPlacerScript.gridCellSize2D; //Hexagon grid gap is not supported. if (gridPlacerScript.gridCellLayout != GridLayout.CellLayout.Hexagon) { gridPlacerScript.gridCellGap2D = EditorGUILayout.Vector2Field("Grid Cell Gap", gridPlacerScript.gridCellGap2D); grid.cellGap = gridPlacerScript.gridCellGap2D; } } private void Grid3D() { GridPlacingMasterEditor.TitleCreator("3D GRID", 5, true); gridPlacerScript.gridCellSize3D = EditorGUILayout.Vector3Field("Grid Cell Size", gridPlacerScript.gridCellSize3D); grid.cellSize = gridPlacerScript.gridCellSize3D; //Hexagon grid gap is not supported. if (gridPlacerScript.gridCellLayout != GridLayout.CellLayout.Hexagon) { gridPlacerScript.gridCellGap3D = EditorGUILayout.Vector3Field("Grid Cell Gap", gridPlacerScript.gridCellGap3D); grid.cellGap = gridPlacerScript.gridCellGap3D; } } private void CreateVisibileGrid() { int width = 300; int height = 300; int widthPixels = 10; Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false); texture.filterMode = FilterMode.Point; Color[] colorArray = new Color[width*height]; for (int i = 0; i < colorArray.Length; i++) { colorArray[i] = Color.black; } texture.SetPixels(0, 0, widthPixels, height, colorArray); texture.SetPixels(0, 0, width, widthPixels, colorArray); texture.SetPixels(width - widthPixels, 0, widthPixels, height, colorArray); texture.SetPixels(0, height - widthPixels, width, widthPixels, colorArray); texture.Apply(); } }
using ProjectCore.Model.EntityModel; using System; using System.Collections.Generic; using System.Text; namespace ProjectCore.Core.Data.Repository.System { public interface ISystemConfigRepository : IRepositoryBase<SystemConfig> { } }
using Newtonsoft.Json; namespace JsonLibrary; public class Message { public string sender { get; set; } public string lobby { get; set; } public string type { get; set; } public dynamic body { get; set; } public Message() { } public Message(string sender, string lobby, string type, dynamic body) { this.sender = sender; this.lobby = lobby; this.type = type; this.body = body; } public static Message Deserialize(string json) => JsonConvert.DeserializeObject<Message>(json); public static string Serialize(Message m) => JsonConvert.SerializeObject(m); }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class AchievementBanner : MonoBehaviour { public Text lbTitle; public Text lbDescription; public void ShowAchievement(string title, string description) { lbDescription.text = description; lbTitle.text = title; gameObject.SetActive(true); Invoke("Hide", 2); } public void Hide() { gameObject.SetActive(false); } }
public class Solution { public int MaxProfit(int k, int[] prices) { int n = prices.Length; if (n == 0 || n == 1) return 0; if (k >= n - 1) return Helper(prices); int[][] loc = new int[n][]; int[][] glo = new int[n][]; for (int i = 0; i < n; i ++) { loc[i] = new int[k + 1]; glo[i] = new int[k + 1]; } for (int i = 1; i < n; i ++) { for (int j = 1; j <= k; j ++) { int diff = prices[i] - prices[i - 1]; loc[i][j] = Math.Max(glo[i-1][j-1] + Math.Max(0, diff), loc[i-1][j] + diff); glo[i][j] = Math.Max(glo[i-1][j], loc[i][j]); } } return glo[n-1][k]; } private int Helper(int[] prices) { int res = 0; for (int i = 1; i < prices.Length; i ++) { if (prices[i] > prices[i - 1]) { res += prices[i] - prices[i - 1]; } } return res; } }
using AbstractFactoryPattern.Abstractions; using AbstractFactoryPattern.Ingredients; namespace AbstractFactoryPattern.ConcreteFactories { public class ChicagoPizzaIngredientFactory: IPizzaIngredientFactory { public IDough CreateDough() { return new ThinCrustDough(); } public ICheese CreateCheese() { return new ReggianoCheese(); } public IClams CreateClams() { return new FrozenClams(); } public ISauce CreateSauce() { return new PlumTomatoSauce(); } } }
using System; using System.Collections.Generic; using AutoTests.Framework.TestData.Entities; using AutoTests.Framework.TestData.TestDataProviders.FileResoruceProviders; namespace AutoTests.Framework.Tests.TestData.Providers { public class TextFileResoruceProvider : TextFileResoruceProviderBase { protected override IEnumerable<ResourceFileLocation> GetFileLocations() { yield return new ResourceFileLocation(Environment.CurrentDirectory + @"\TestData", "txt"); } } }
namespace ApiSoftPlan.Tests { using ApiSoftPlan.Controllers; using ApiSoftPlan.Core; using ApiSoftPlan.Models; using Microsoft.AspNetCore.Mvc; using Moq; using Xunit; public class CalculaJurosTests { [Fact] public void ShouldBeRightValue() { var mathSoft = new MathSoft { InitialValue = 100, Month = 5, TotalValue = (decimal)105.10 }; var mathCore = new Mock<IMathCore>(); mathCore.Setup(x => x.CalculateInterest(mathSoft)) .Returns(mathSoft.TotalValue); var controller = new CalculaJurosController(mathCore.Object); var result = controller.CalculaJurosPost(mathSoft); var okObjectResult = Assert.IsType<OkObjectResult>(result); Assert.Equal((decimal)105.10, okObjectResult.Value); } [Fact] public void ShouldBeWrongValue() { var mathSoft = new MathSoft { InitialValue = 100, Month = 5, TotalValue = (decimal)105.10 }; var mathCore = new Mock<IMathCore>(); mathCore.Setup(x => x.CalculateInterest(mathSoft)) .Returns(mathSoft.TotalValue); var controller = new CalculaJurosController(mathCore.Object); var result = controller.CalculaJurosPost(mathSoft); var okObjectResult = Assert.IsType<OkObjectResult>(result); Assert.NotEqual((decimal)110.10, okObjectResult.Value); } [Fact] public void ShouldBeOk() { var mathSoft = new MathSoft { InitialValue = 100, Month = 10, TotalValue = (decimal)105.10 }; var mathCore = new Mock<IMathCore>(); mathCore.Setup(x => x.CalculateInterest(mathSoft)) .Returns(mathSoft.TotalValue); var controller = new CalculaJurosController(mathCore.Object); var result = controller.CalculaJurosPost(mathSoft); var okObjectResult = Assert.IsType<OkObjectResult>(result); Assert.True(((ObjectResult)result).StatusCode == 200); } [Fact] public void ShouldBeBad() { var mathSoft = new MathSoft { InitialValue = 100, Month = 10, TotalValue = (decimal)105.10 }; var mathCore = new Mock<IMathCore>(); mathCore.Setup(x => x.CalculateInterest(null)) .Returns(mathSoft.TotalValue); var controller = new CalculaJurosController(mathCore.Object); var result = controller.CalculaJurosPost(null); Assert.True(((StatusCodeResult)result).StatusCode == 400); } } }
using PizzaBox.Models; using PizzaBox.Storing.Repositories; using PizzaBox.Domain.Interfaces; namespace PizzaBox.Storing { public class UnitofWork: IUnitofWork { private readonly PizzaBoxContext _context; public UnitofWork(PizzaBoxContext context) { _context = context; Customer = new CustomerRepository(_context); Employee = new EmployeeRepository(_context); Pizza = new PizzaRepository(_context); Order = new OrderRepository(_context); Address = new AddressRepository(_context); Store = new StoreRepository(_context); Ingrediants = new IngredientsRepository(_context); } public IOrders Order { get; private set; } public IAddress Address { get; private set; } public IIngrediants Ingrediants { get; private set; } public IPizza Pizza { get; private set; } public IEmployee Employee { get; private set; } public ICustomer Customer { get; private set; } public IngrediantsPizza ingrediantsPizza { get; private set; } public IOrders Orders { get; private set; } public IStore Store { get; private set; } public int Complete() { return _context.SaveChanges(); } public void Dispose() { _context.Dispose(); } } }
namespace CarDealer.Models.Attributes { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; public class OperationAttribute : ValidationAttribute { public override bool IsValid(object value) { string opeartionValue = value.ToString(); if (opeartionValue == "Add" || opeartionValue == "Delete" || opeartionValue == "Edit") { return true; } return false; } } }
using EncryptionDecryptionConsole; using System; using System.IO; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptionDecryption { internal class Program { private const string PlainText = "Test"; private static IOneWayEncryptionService OneWayEncrpytionService { get; set; } private static ICryptographyService CryptographyService { get; set; } private static void Main(string[] args) { RunAsync().Wait(); Console.ReadLine(); } private async static Task RunAsync() { Console.WriteLine($"Plain Text: {PlainText}"); OneWayEncrpytionService = new MD5CryptographyService(); var hash = OneWayEncrpytionService.Encrypt(PlainText); Console.WriteLine($"MD5 Hashed: {hash}"); OneWayEncrpytionService = new HashCryptographyService(new SHA1Managed()); hash = OneWayEncrpytionService.Encrypt(PlainText); Console.WriteLine($"SHA1 Hashed: {hash}"); var symmetricAlgorithmCryptographyService = new SymmetricAlgorithmCryptographyService( new AesCryptoServiceProvider { Mode = CipherMode.CBC, KeySize = 128, Key = Encoding.UTF8.GetBytes("1234567890123456"), IV = Encoding.UTF8.GetBytes("0234567890123456") }); CryptographyService = symmetricAlgorithmCryptographyService; var encryptedText = CryptographyService.Encrypt(PlainText); Console.WriteLine($"AES Encrypted: {encryptedText}"); var decryptedText = CryptographyService.Decrypt(encryptedText).Trim(); Console.WriteLine($"AES Decrypted: {decryptedText}"); const string filename = "Credentials.txt"; var encryptedPersister = new EncryptedPersister(CryptographyService, new FileIOService()); await encryptedPersister.SaveAsync(filename, new Credentials { Username = "Bob", Password = "Password123" }); var credentials = await encryptedPersister.LoadAsync<Credentials>(filename); Console.WriteLine($"AES Encrypted File: {await File.ReadAllTextAsync(filename)}"); Console.WriteLine($"AES Decrypted Credentials Username: {credentials.Username} Password: {credentials.Password}"); } } }
using PatientWebAppTests.CreateObjectsForTests; namespace PatientWebAppTests.UnitTests { public class TherapySearchTests { private readonly TestObjectFactory _objectFactory; private readonly StubRepository _stubRepository; /* public TherapySearchTests() { _objectFactory = new TestObjectFactory(); _stubRepository = new StubRepository(); } [Fact] public void Advanced_search_therapy_operator_and_drug_name() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var therapySearchDTOValidObject = _objectFactory.GetTherapySearchDTO().CreateValidTestObject(); var result = therapyService.AdvancedSearch(therapySearchDTOValidObject); Assert.NotEmpty(result); } [Fact] public void Advanced_search_therapy_operator_or_drug_name() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var result = therapyService.AdvancedSearch(new TherapySearchDTO(jmbg: "1309998775018", startDate: new DateTime(2020, 10, 10), endOperator: LogicalOperator.Or, endDate: new DateTime(2020, 12, 12), doctorOperator: LogicalOperator.And, doctorSurname: null, drugOperator: LogicalOperator.Or, drugName: "lklklkl")); Assert.NotEmpty(result); } [Fact] public void Advanced_search_therapy_and_surname() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var result = therapyService.AdvancedSearch(new TherapySearchDTO(jmbg: "1309998775018", startDate: new DateTime(2020, 10, 10), endOperator: LogicalOperator.Or, endDate: new DateTime(2020, 12, 12), doctorOperator: LogicalOperator.And, doctorSurname: "Markovic", drugOperator: LogicalOperator.Or, drugName: "lklklkl")); Assert.NotEmpty(result); } [Fact] public void Advanced_search_therapy_or_surname() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var result = therapyService.AdvancedSearch(new TherapySearchDTO(jmbg: "1309998775018", startDate: new DateTime(2020, 10, 10), endOperator: LogicalOperator.Or, endDate: new DateTime(2020, 12, 12), doctorOperator: LogicalOperator.Or, doctorSurname: "jjjk", drugOperator: LogicalOperator.Or, drugName: "lklklkl")); Assert.NotEmpty(result); } [Fact] public void Advanced_search_therapy_start_date() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var result = therapyService.AdvancedSearch(new TherapySearchDTO(jmbg: "1309998775018", startDate: new DateTime(2020, 10, 10), endOperator: LogicalOperator.Or, endDate: new DateTime(2020, 12, 12), doctorOperator: LogicalOperator.Or, doctorSurname: "jjjk", drugOperator: LogicalOperator.Or, drugName: "lklklkl")); Assert.NotEmpty(result); } [Fact] public void Advanced_search_therapy_or_end_date() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var result = therapyService.AdvancedSearch(new TherapySearchDTO(jmbg: "1309998775018", startDate: new DateTime(2020, 10, 10), endOperator: LogicalOperator.Or, endDate: new DateTime(2020, 10, 10), doctorOperator: LogicalOperator.Or, doctorSurname: "jjjk", drugOperator: LogicalOperator.Or, drugName: "lklklkl")); Assert.NotEmpty(result); } [Fact] public void Advanced_search_therapy_and_end_date() { TherapyService therapyService = new TherapyService(_stubRepository.CreateTherapyStubRepository()); var result = therapyService.AdvancedSearch(new TherapySearchDTO(jmbg: "1309998775018", startDate: new DateTime(2020, 10, 10), endOperator: LogicalOperator.And, endDate: new DateTime(2020, 10, 10), doctorOperator: LogicalOperator.Or, doctorSurname: "jjjk", drugOperator: LogicalOperator.Or, drugName: "lklklkl")); Assert.Empty(result); } */ } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using CYJ.DingDing.Dto; using CYJ.DingDing.Dto.Dto; using CYJ.DingDing.Dto.Enum; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace CYJ.DingDing.Service.Http.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly ILogger<TokensController> _logger; /// <summary> /// 创建静态字段,保证全局一致 /// </summary> public static AccessTokenResponse AccessToken = new AccessTokenResponse(); public ValuesController(ILogger<TokensController> logger) { _logger = logger; } // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { _logger.LogInformation("你访问了首页"); _logger.LogWarning("警告信息"); _logger.LogError("错误信息"); string CorpID = "dingb578e1d0be14c3f135c2f4657eb6378f";// ConfigHelper.FetchCorpID(); string CorpSecret = "p_FeZ6xm3cnnDDdcvvbFbWc9uKyimvZjzmAAJ-csDkwE5oE7XeeHY-WLtLuvWbeM";// ConfigHelper.FetchCorpSecret(); string TokenUrl = "https://oapi.dingtalk.com/gettoken"; string apiurl = $"{TokenUrl}?corpid={CorpID}&corpsecret={CorpSecret}"; WebRequest request = WebRequest.Create(@apiurl); request.Method = "GET"; WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); Encoding encode = Encoding.UTF8; StreamReader reader = new StreamReader(stream, encode); string resultJson = reader.ReadToEnd(); AccessTokenResponse tokenResult = JsonConvert.DeserializeObject<AccessTokenResponse>(resultJson); if (tokenResult.ErrCode == ErrCodeEnum.OK) { } return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using UnityEngine; using UnityEditor; using Unity.Mathematics; using static Unity.Mathematics.math; namespace IzBone.IzBCollider { using Common; [CanEditMultipleObjects] [CustomEditor(typeof(BodiesPackAuthoring))] sealed class BodiesPackAutoringInspector : Editor { void OnSceneGUI() { var tgt = (BodiesPackAuthoring)target; if (tgt.Bodies != null) foreach (var i in tgt.Bodies) { if (i != null) i.DEBUG_drawGizmos(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Support.V4; using System.Threading.Tasks; using System.Net; using Newtonsoft.Json; using System.IO; namespace Goosent { public class FragmentChat : BaseTabFragment { private List<UserMessage> chatMessages = new List<UserMessage>(); private Adapters.ChatMessagesArrayAdapter chatAdapter; private ListView chatListView; private int _temp_messageCounter = 0; private string currentChannelName; private string prevChannelName; private ServerManager sm; //Temp private List<string> fakeNames = new List<string>(); private List<string> fakeMessages = new List<string>(); Random random = new Random(); public static FragmentChat getInstance(Context context) { Bundle args = new Bundle(); FragmentChat cFragment = new FragmentChat(); cFragment.Arguments = args; cFragment.SetContext(context); cFragment.SetTitle(context.GetString(Resource.String.tab_item_chat)); return cFragment; } //private void TempInitFake() //{ // fakeNames.Add("Ramzan"); // fakeNames.Add("Valera"); // fakeNames.Add("Micheal"); // fakeNames.Add("Denis"); // fakeNames.Add("Max"); // fakeNames.Add("Rose"); // fakeNames.Add("Gleb"); // fakeNames.Add("Artyom"); // fakeMessages.Add("Всем привет!"); // fakeMessages.Add("MLG!"); // fakeMessages.Add("So pro! Such skill! Wow!"); // fakeMessages.Add(")))))))))))))000)000)hrtklhrtklhjmklergmnrklgergjrkgjergkljrglk;ejgrjgkl"); // fakeMessages.Add("KappaPride"); // fakeMessages.Add("SimpleText"); // fakeMessages.Add("Hello everyone!"); // fakeMessages.Add("General Kenobi!"); //} public override void OnActivityCreated(Bundle savedInstanceState) { base.OnActivityCreated(savedInstanceState); chatAdapter = new Adapters.ChatMessagesArrayAdapter(context, chatMessages); chatListView = (ListView)view.FindViewById(Resource.Id.chat_list_view); sm = new ServerManager(); chatListView.Adapter = chatAdapter; AsyncConsistantChatUpdating(); } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Use this to return your custom view for this Fragment view = inflater.Inflate(Resource.Layout.FragmentChatLayout, container, false); //TempInitFake(); return view; } public void SetContext(Context context) { this.context = context; } private async Task AsyncConsistantChatUpdating() { while (true) { Activity.RunOnUiThread(() => { Task.Run(async () => { var newMessages = await ((MainActivity)context).sm.GetNewMessagesFromChat(); AddNewMessages(newMessages); }); }); _temp_messageCounter += 1; chatAdapter.NotifyDataSetChanged(); await Task.Delay(TimeSpan.FromSeconds(0.5)); } } private void AutoScrollChatToTheBottom() { chatListView.SetSelection(chatAdapter.Count - 1); } private async Task AddNewMessages(ServerManager.NewMessagesFromChatContainer newMessages) { //chatMessages.Add(new UserMessage(fakeNames[random.Next(0, fakeNames.Count-1)], fakeMessages[random.Next(0, fakeMessages.Count - 1)], new TimeSpan(14, 10, 5), String.Format("#{0:X6}", random.Next(0x1000000)))); if (((MainActivity)context).SelectedChannel.Name != "") { sm.UID = ((MainActivity)context).sm.UID; currentChannelName = newMessages.channel_name; if (currentChannelName != prevChannelName) { chatMessages.Clear(); chatMessages.Add(new UserMessage("Чтение канала", currentChannelName, new TimeSpan(14, 10, 5), "#ffffff")); } prevChannelName = currentChannelName; foreach (ServerManager.MessageFromChat message in newMessages.messages_array) { Console.WriteLine(message.message); chatMessages.Add(new UserMessage(message.user, message.message, new TimeSpan(14, 10, 5), String.Format("#{0:X6}", random.Next(0x1000000)))); } //if (newMessages.messages_array.Length > 0) //{ //} //if (chatListView.LastVisiblePosition == chatAdapter.Count - 2) //{ // AutoScrollChatToTheBottom(); //} } } } }
using AppointmentManagement.Business.Abstract; using AppointmentManagement.UI.DTOs; using AppointmentManagement.UI.Entity.Abstract; using AppointmentManagement.UI.Identity.Context; using AppointmentManagement.UI.Models; using AppointmentManagement.UI.TagHelpers.TagHelperEntity; using AutoMapper; using CivilManagement.UI.Entity; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NLog.Web.LayoutRenderers; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CivilManagement.UI.Controllers { [Authorize(Roles = "Secretary")] public class HomeController : Controller { private readonly AppIdentityDbContext _context; private readonly UserManager<AppUser> _userManager; private readonly ITrOrderAsnHeaderService _trOrderAsnHeaderService; private readonly IMapper _mapper; private readonly IAppointment _appointment; public HomeController(UserManager<AppUser> userManager, ITrOrderAsnHeaderService trOrderAsnHeaderService, AppIdentityDbContext context, IMapper mapper, IAppointment appointment) { _userManager = userManager; _trOrderAsnHeaderService = trOrderAsnHeaderService; _context = context; _mapper = mapper; _appointment = appointment; } public async Task<IActionResult> Index() { AppUser user = _userManager.FindByNameAsync(User.Identity.Name).Result; var orderHeaders =await _trOrderAsnHeaderService.GetWithCategoryNameAllAsync(); SecretaryViewModel secretaryViewModel = new SecretaryViewModel { VehicleTypes = _context.VehicleTypes.ToList(), UserId = user.Id, ArticulatedLorry = orderHeaders.Where(w => w.ContainerTypeCode == "1").Select(n => new CustomSelectItem { Value = n.OrderAsnHeaderID.ToString(), Text = n.OrderAsnNumber + " " + n.CurrAccDescription, Group = n.ContainerTypeDescription, VehicleId = n.ContainerTypeCode, VendorCode = n.CurrAccCode, TotalBox = n.TotalPackage, TotalPallet = n.TotalCHW }).ToList(), Truck = orderHeaders.Where(w => w.ContainerTypeCode == "2").Select(n => new CustomSelectItem { Value = n.OrderAsnHeaderID.ToString(), Text = n.OrderAsnNumber + " " + n.CurrAccDescription, Group = n.ContainerTypeDescription, VehicleId = n.ContainerTypeCode, VendorCode = n.CurrAccCode, TotalBox = n.TotalPackage, TotalPallet = n.TotalCHW }).ToList(), Van = orderHeaders.Where(w => w.ContainerTypeCode == "3").Select(n => new CustomSelectItem { Value = n.OrderAsnHeaderID.ToString(), Text = n.OrderAsnNumber + " " + n.CurrAccDescription, Group = n.ContainerTypeDescription, VehicleId = n.ContainerTypeCode, VendorCode = n.CurrAccCode, TotalBox = n.TotalPackage, TotalPallet = n.TotalCHW }).ToList(), DeliveryVan = orderHeaders.Where(w => w.ContainerTypeCode == "4").Select(n => new CustomSelectItem { Value = n.OrderAsnHeaderID.ToString(), Text = n.OrderAsnNumber + " " + n.CurrAccDescription, Group = n.ContainerTypeDescription, VehicleId = n.ContainerTypeCode, VendorCode = n.CurrAccCode, TotalBox = n.TotalPackage, TotalPallet = n.TotalCHW }).ToList(), Car = orderHeaders.Where(w => w.ContainerTypeCode == "5").Select(n => new CustomSelectItem { Value = n.OrderAsnHeaderID.ToString(), Text = n.OrderAsnNumber + " " + n.CurrAccDescription, Group = n.ContainerTypeDescription, VehicleId = n.ContainerTypeCode, VendorCode = n.CurrAccCode, TotalBox = n.TotalPackage, TotalPallet = n.TotalCHW }).ToList() }; //OrderAsnHeadersList = orderHeaders.Select(n => new SelectListItem //{ // Value = n.OrderAsnHeaderID.ToString() + "&" + n.ContainerTypeCode, // Text = n.OrderAsnNumber + " " + n.CurrAccDescription // , // Group = new SelectListGroup { Name = n.ContainerTypeDescription } //}).ToList() return View(secretaryViewModel); } public async Task<IActionResult> ExpectantPlugs() { var orderHeaders = await _trOrderAsnHeaderService.GetWithCategoryNameAllAsync(); var orders = orderHeaders.OrderBy(o => o.OrderAsnDate).ThenBy(t => t.OrderAsnNumber).ToList(); return View(_mapper.Map<List<OrderHeaderInfoDto>>(orders)); } public async Task<IActionResult> ApprovedPlugs() { var model = await _appointment.GetApprovedPlugs(); return View(model.OrderBy(o => o.StartDate)); } public IActionResult test() { return View(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Animator))] public class PlayerAttack_SideScroller : MonoBehaviour { //This script handles the animation of attacking on a button press. //It is also necessary to use for the weapon switching script and attack behavior script private Animator animator; public Weapon weapon; // Start is called before the first frame update void Start() { animator = GetComponent<Animator>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Mouse0) && !animator.GetBool("Attack")) { animator.SetBool("Attack", true); } } }
using UnityEngine; public class MonoBehaviourSingleton<T> : MonoBehaviour where T : MonoBehaviour { private static T instance; private static bool applicationQuiting = false; public static T Instance { get { if (instance == null) { CreateInstance(); } return instance; } } public static bool CreateInstance() { if (applicationQuiting) return false; if (instance != null) return false; GameObject singleton = new GameObject(string.Format("_{0}", typeof(T).Name)); singleton.AddComponent<T>(); return true; } protected virtual void OnCreateInstance() { } protected virtual void Awake() { if (instance == null) { instance = this as T; DontDestroyOnLoad(this); OnCreateInstance(); } else { DestroyImmediate(this); DebugLogger.Log(string.Format("Duplicated singlton({0}) in scene", typeof(T).ToString())); } } protected virtual void OnDestroy() { if (instance == this) { instance = null; applicationQuiting = true; } } }
using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace VoxelSpace { // use to calculate the lights after voxel volume generation/deserialization public class VoxelVolumeLightCalculator : VoxelChunkProcessor { public VoxelVolumeLightCalculator() : base() {} protected override void Process() { Input.Wait(); var propagator = new VoxelLightPropagator(Volume); Parallel.For(0, 7, (i) => { if (i < 6) { CalculateSunlight(Volume, i, propagator[i]); } else { CalculatePoint(Volume, propagator[i]); } }); } // seeds sunlight over an entire volume, queueing nodes for propogation unsafe void CalculateSunlight(VoxelVolume volume, int channel, VoxelLightPropagator.ChannelPropagator channelProp) { var cRegion = volume.ChunkRegion; int axis = channel % 3; // x = 0, y = 1, z = 2 var neg = channel >= 3; int ai = (axis + 1) % 3; int bi = (axis + 2) % 3; int ci = axis; int minA, minB, minC; int maxA, maxB, maxC; minA = (&cRegion.Min.X)[ai]; maxA = (&cRegion.Max.X)[ai]; minB = (&cRegion.Min.X)[bi]; maxB = (&cRegion.Max.X)[bi]; int incr = neg ? -1 : 1; Coords lCoords = Coords.ZERO; if (neg) { minC = (&cRegion.Max.X)[ci] - 1; maxC = (&cRegion.Min.X)[ci] - 1; (&lCoords.X)[ci] = VoxelChunk.SIZE - 1; } else { minC = (&cRegion.Min.X)[ci]; maxC = (&cRegion.Max.X)[ci]; (&lCoords.X)[ci] = 0; } Coords cCoords = Coords.ZERO; VoxelChunk chunk; for (int ca = minA; ca < maxA; ca ++) { for (int cb = minB; cb < maxB; cb ++) { (&cCoords.X)[ai] = ca; (&cCoords.X)[bi] = cb; for (int cc = minC; cc != maxC; cc += incr) { (&cCoords.X)[ci] = cc; chunk = volume[cCoords]; if (chunk != null) { for (int la = 0; la < VoxelChunk.SIZE; la ++) { for (int lb = 0; lb < VoxelChunk.SIZE; lb ++) { (&lCoords.X)[ai] = la; (&lCoords.X)[bi] = lb; *chunk.LightData[channel][lCoords] = VoxelLight.MAX_LIGHT; channelProp.QueueForPropagation(chunk, lCoords); } } break; } } } } channelProp.Propagate(); } unsafe void CalculatePoint(VoxelVolume volume, VoxelLightPropagator.ChannelPropagator channelProp) { Parallel.ForEach(volume, (chunk) => { Coords c = new Coords(0, 0, 0); for (c.X = 0; c.X < VoxelChunk.SIZE; c.X ++) { for (c.Y = 0; c.Y < VoxelChunk.SIZE; c.Y ++) { for (c.Z = 0; c.Z < VoxelChunk.SIZE; c.Z ++) { var pointLevel = chunk.Voxels[c].Type?.PointLightLevel; if (pointLevel is byte level) { channelProp.QueueForPropagation(chunk, c, level); } } } } }); channelProp.Propagate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace RRExpress.Common { public enum ErrorTypes { /// <summary> /// 未知 /// </summary> Unknow = 0, /// <summary> /// 取消 /// </summary> Canceled, /// <summary> /// 数据解析错误 /// </summary> ParseError, /// <summary> /// API自定义的错误 /// </summary> ResponsedWithErrorInfo, /// <summary> /// 配置错误 /// </summary> SetupError, /// <summary> /// 参数验证错误 /// </summary> ParameterError, /// <summary> /// 未授权 /// </summary> [StatusErrorMap(HttpStatusCode.Unauthorized)] UnAuth, /// <summary> /// 远程服务错误 /// </summary> [StatusErrorMap( HttpStatusCode.InternalServerError, HttpStatusCode.ServiceUnavailable)] ServiceException, /// <summary> /// 错误的请求 /// </summary> [StatusErrorMap( HttpStatusCode.BadRequest, HttpStatusCode.NotFound, HttpStatusCode.Forbidden, HttpStatusCode.MethodNotAllowed)] RequestError, Network } [AttributeUsage(AttributeTargets.Field)] public class StatusErrorMapAttribute : Attribute { public HttpStatusCode[] Codes { get; private set; } public StatusErrorMapAttribute(params HttpStatusCode[] codes) { this.Codes = codes; } } public static class HttpStatusToErrorTypes { private static Dictionary<HttpStatusCode, ErrorTypes> Map = null; static HttpStatusToErrorTypes() { Map = new Dictionary<HttpStatusCode, ErrorTypes>(); var values = Enum.GetValues(typeof(ErrorTypes)) .Cast<int>(); foreach (var v in values) { var errorType = (ErrorTypes)v; var attr = EnumHelper.GetAttribute<ErrorTypes, StatusErrorMapAttribute>(errorType); if (attr != null && attr.Codes != null) { foreach (var c in attr.Codes) { if (!Map.ContainsKey(c)) Map.Add(c, errorType); } } } } /// <summary> /// 将 HttpStatus 转换为 ErrorType /// </summary> /// <param name="code"></param> /// <returns></returns> public static ErrorTypes? Convert(this HttpStatusCode code) { if (Map.ContainsKey(code)) return Map[code]; else return null; } } }
using System; using System.Collections.Generic; using System.Text; namespace JensPedersen.KompetenceTestS1.FærdighedsDelOpg5 { class Person { private string firstName; private string lastName; private DateTime birthDate; private TimeSpan age; private int ageYears; public Person(string firstName, string lastName, DateTime birthdate) { FirstName = firstName; LastName = lastName; BirthDate = birthDate; } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public DateTime BirthDate { get { return birthDate; } set { birthDate = value; } } public TimeSpan Age { get { return age; } set { age = value; } } public int AgeYears { get { return ageYears; } set { ageYears = value; } } public void CalcAge(DateTime birthDate) { age = DateTime.Now.Subtract(birthDate); for(ageYears = 0; ageYears < age.TotalDays / 365.25 - 1; ageYears++) { } } public void PrintInfo() { Console.WriteLine($"Fornavn: {firstName}"); Console.WriteLine($"Efternavn: {lastName}"); //året 0001 bliver udskrevet hvis datoen er ugyldig if(birthDate.Year == 0001 || birthDate > DateTime.Now) { Console.WriteLine("Denne fødselsdato er ugyldig! Prøv igen"); } else { Console.WriteLine($"Fødselsdato: {birthDate.ToString("dd/MM/yyyy")}"); Console.WriteLine($"Alder: {ageYears} år\n"); } } } }
using System.Threading; using System.Threading.Tasks; namespace DDMedi { public interface IBaseSupplierChannel { IDDBroker DDBroker { get; } } public interface IAsyncSupplierChannel<TInputs, TOutput> : IBaseSupplierChannel where TInputs : IInputs<TOutput> { Task<TOutput> ProcessAsync(TInputs inputs = default, CancellationToken token = default); } public interface IAsyncSupplierChannel<TInputs> : IBaseSupplierChannel where TInputs : IInputs { Task ProcessAsync(TInputs inputs = default, CancellationToken token = default); } public interface ISupplierChannel<TInputs, TOutput> : IBaseSupplierChannel where TInputs : IInputs<TOutput> { TOutput Process(TInputs inputs = default); } public interface ISupplierChannel<TInputs> : IBaseSupplierChannel where TInputs : IInputs { void Process(TInputs inputs = default); } internal abstract class BaseSupplierChannel<TInputs, TSupplier> where TSupplier : class { protected readonly TSupplier _supplier; public IDDBroker DDBroker { get; } protected readonly BaseSupplierContext<TInputs> _context; protected BaseSupplierChannel(IInternalDDBroker ddBroker, SupplierDescriptor descriptor) { _supplier = ddBroker.Provider.GetService(descriptor.ImplementDescriptor.RegisterType) as TSupplier; DDBroker = ddBroker; _context = new BaseSupplierContext<TInputs>(ddBroker); } } internal sealed class AsyncSupplierChannel<TInputs, TOutput> : BaseSupplierChannel<TInputs, IAsyncSupplier<TInputs, TOutput>>, IAsyncSupplierChannel<TInputs, TOutput> where TInputs : IInputs<TOutput> { internal AsyncSupplierChannel(IInternalDDBroker ddBroker, SupplierDescriptor descriptor) : base(ddBroker, descriptor) { } public Task<TOutput> ProcessAsync(TInputs inputs = default, CancellationToken token = default) { _context.Inputs = inputs; return _supplier.ProcessAsync(_context, token); } } internal sealed class AsyncSupplierChannel<TInputs> : BaseSupplierChannel<TInputs, IAsyncSupplier<TInputs>>, IAsyncSupplierChannel<TInputs> where TInputs : IInputs { internal AsyncSupplierChannel(IInternalDDBroker ddBroker, SupplierDescriptor descriptor) : base(ddBroker, descriptor) { } public Task ProcessAsync(TInputs inputs = default, CancellationToken token = default) { _context.Inputs = inputs; return _supplier.ProcessAsync(_context, token); } } internal sealed class SupplierChannel<TInputs, TOutput> : BaseSupplierChannel<TInputs, ISupplier<TInputs, TOutput>>, ISupplierChannel<TInputs, TOutput> where TInputs : IInputs<TOutput> { internal SupplierChannel(IInternalDDBroker ddBroker, SupplierDescriptor descriptor) : base(ddBroker, descriptor) { } public TOutput Process(TInputs inputs = default) { _context.Inputs = inputs; return _supplier.Process(_context); } } internal sealed class SupplierChannel<TInputs> : BaseSupplierChannel<TInputs, ISupplier<TInputs>>, ISupplierChannel<TInputs> where TInputs : IInputs { internal SupplierChannel(IInternalDDBroker ddBroker, SupplierDescriptor descriptor) : base(ddBroker, descriptor) { } public void Process(TInputs inputs = default) { _context.Inputs = inputs; _supplier.Process(_context); } } internal sealed class ESupplierChannel<TEInputs> : BaseSupplierChannel<TEInputs, IESupplier<TEInputs>> where TEInputs : IEInputs { internal ESupplierChannel(IInternalDDBroker ddBroker, SupplierDescriptor descriptor) : base(ddBroker, descriptor) { } public Task ProcessAsync(TEInputs inputs = default, CancellationToken token = default) { _context.Inputs = inputs; return _supplier.ProcessAsync(_context, token); } } }
namespace MinMaxSumAverage { using System; using System.Collections.Generic; using System.Linq; public class StartUp { public static void Main() { var numbersCount = int.Parse(Console.ReadLine()); var numbersList = new List<int>(); for (int i = 0; i < numbersCount; i++) { var number = int.Parse(Console.ReadLine()); numbersList.Add(number); } var sum = numbersList.Sum(); var min = numbersList.Min(); var max = numbersList.Max(); var average = numbersList.Average(); Console.WriteLine($"Sum = {sum}"); Console.WriteLine($"Min = {min}"); Console.WriteLine($"Max = {max}"); Console.WriteLine($"Average = {average}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EQS.AccessControl.API.JWT.Interface; namespace EQS.AccessControl.API.JWT { public class JwtConfiguration : IJwtConfiguration { public string Audience { get; set; } public string Issuer { get; set; } public int Seconds { get; set; } } }
using System; using System.Collections.Generic; namespace Euler_Logic.Problems.AdventOfCode.Y2022 { public class Problem08 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2022: 8"; public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { var trees = GetTrees(input); SetIsVisible(trees); return GetCount(trees); } private long Answer2(List<string> input) { var trees = GetTrees(input); SetDistance(trees); return FindBest(trees); } private void SetIsVisible(Tree[,] trees) { SetIsVisible_Horizontal(trees); SetIsVisible_Vertial(trees); } private void SetIsVisible_Horizontal(Tree[,] trees) { for (int y = 0; y <= trees.GetUpperBound(1); y++) { int highest = -1; for (int x = 0; x <= trees.GetUpperBound(0); x++) { var tree = trees[x, y]; if (tree.Height > highest) { highest = tree.Height; tree.IsVisible = true; } } highest = -1; for (int x = trees.GetUpperBound(0); x >= 0; x--) { var tree = trees[x, y]; if (tree.Height > highest) { highest = tree.Height; tree.IsVisible = true; } } } } private void SetIsVisible_Vertial(Tree[,] trees) { for (int x = 0; x <= trees.GetUpperBound(0); x++) { int highest = -1; for (int y = 0; y <= trees.GetUpperBound(1); y++) { var tree = trees[x, y]; if (tree.Height > highest) { highest = tree.Height; tree.IsVisible = true; } } highest = -1; for (int y = trees.GetUpperBound(1); y >= 0; y--) { var tree = trees[x, y]; if (tree.Height > highest) { highest = tree.Height; tree.IsVisible = true; } } } } private void SetDistance(Tree[,] trees) { SetDistance_Horizontal(trees); } private void SetDistance_Horizontal(Tree[,] trees) { for (int y = 0; y <= trees.GetUpperBound(1); y++) { trees[0, y].BlockedDistance = 1; for (int x = 1; x <= trees.GetUpperBound(0); x++) { var tree = trees[x, y]; var prior = trees[x - 1, y]; if (tree.Height <= prior.Height) { tree.Distance *= 1; tree.BlockedDistance = 1; } else { var distance = GetDistance_Recursive(trees, x - 1, y, enumDirection.Left, tree.Height) + 1; tree.Distance *= distance; tree.BlockedDistance = distance; } } trees[trees.GetUpperBound(0), y].BlockedDistance = 1; for (int x = trees.GetUpperBound(0) - 1; x >= 0; x--) { var tree = trees[x, y]; var prior = trees[x + 1, y]; if (tree.Height <= prior.Height) { tree.Distance *= 1; tree.BlockedDistance = 1; } else { var distance = GetDistance_Recursive(trees, x + 1, y, enumDirection.Right, tree.Height) + 1; tree.Distance *= distance; tree.BlockedDistance = distance; } } } for (int x = 0; x <= trees.GetUpperBound(0); x++) { trees[x, 0].BlockedDistance = 1; for (int y = 1; y <= trees.GetUpperBound(1); y++) { var tree = trees[x, y]; var prior = trees[x, y - 1]; if (tree.Height <= prior.Height) { tree.Distance *= 1; tree.BlockedDistance = 1; } else { var distance = GetDistance_Recursive(trees, x, y - 1, enumDirection.Up, tree.Height) + 1; tree.Distance *= distance; tree.BlockedDistance = distance; } } trees[x, trees.GetUpperBound(1)].BlockedDistance = 1; for (int y = trees.GetUpperBound(1) - 1; y >= 0; y--) { var tree = trees[x, y]; var prior = trees[x, y + 1]; if (tree.Height <= prior.Height) { tree.Distance *= 1; tree.BlockedDistance = 1; } else { var distance = GetDistance_Recursive(trees, x, y + 1, enumDirection.Down, tree.Height) + 1; tree.Distance *= distance; tree.BlockedDistance = distance; } } } } private long FindBest(Tree[,] trees) { long best = 0; for (int x = 1; x < trees.GetUpperBound(0); x++) { for (int y = 1; y < trees.GetUpperBound(1); y++) { var tree = trees[x, y]; if (tree.Distance > best) best = tree.Distance; } } return best; } private int GetDistance_Recursive(Tree[,] trees, int x, int y, enumDirection direction, int height) { var tree = trees[x, y]; Tree prior = null; switch (direction) { case enumDirection.Up: if (y - tree.BlockedDistance == -1) return 0; prior = trees[x, y - tree.BlockedDistance]; break; case enumDirection.Down: if (y + tree.BlockedDistance > trees.GetUpperBound(1)) return 0; prior = trees[x, y + tree.BlockedDistance]; break; case enumDirection.Right: if (x + tree.BlockedDistance > trees.GetUpperBound(1)) return 0; prior = trees[x + tree.BlockedDistance, y]; break; case enumDirection.Left: if (x - tree.BlockedDistance == -1) return 0; prior = trees[x - tree.BlockedDistance, y]; break; } if (prior.Height >= height) { return tree.BlockedDistance; } else { int nextDistance = 0; switch (direction) { case enumDirection.Up: nextDistance = GetDistance_Recursive(trees, x, y - prior.BlockedDistance, direction, height); break; case enumDirection.Down: nextDistance = GetDistance_Recursive(trees, x, y + prior.BlockedDistance, direction, height); break; case enumDirection.Right: nextDistance = GetDistance_Recursive(trees, x + prior.BlockedDistance, y, direction, height); break; case enumDirection.Left: nextDistance = GetDistance_Recursive(trees, x - prior.BlockedDistance, y, direction, height); break; } return nextDistance + prior.BlockedDistance; } } private int GetCount(Tree[,] trees) { int count = 0; foreach (var tree in trees) { if (tree.IsVisible) count++; } return count; } private Tree[,] GetTrees(List<string> input) { var trees = new Tree[input[0].Length, input.Count]; int y = 0; foreach (var line in input) { int x = 0; foreach (var digit in line) { trees[x, y] = new Tree() { Height = Convert.ToInt32(new string(new char[] { digit })), IsVisible = false, Distance = 1 }; x++; } y++; } return trees; } private class Tree { public int Height { get; set; } public bool IsVisible { get; set; } public int BlockedDistance { get; set; } public long Distance { get; set; } } private enum enumDirection { Up, Down, Left, Right } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace KPIDemo.Entity { public class CourseResult : BaseEntity { public Student Student { get; set; } public Course Course { get; set; } public int Score { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Otiport.API.Contract.Request.Medicines; using Otiport.API.Contract.Response.Medicines; namespace Otiport.API.Services { public interface IMedicineService { Task<AddMedicineResponse> AddMedicineAsync(AddMedicineRequest request); Task<DeleteMedicineResponse> DeleteMedicineAsync(DeleteMedicineRequest request); Task<GetMedicinesResponse> GetMedicinesAsync(GetMedicinesRequest request); Task<UpdateMedicineResponse> UpdateMedicinesAsync(UpdateMedicineRequest request); } }
using System; using System.Collections.Generic; namespace WebAPI.MoneyXChange.Models { public partial class UserAccount { public int UspId { get; set; } public string UsaUsername { get; set; } public string UsaPassword { get; set; } public string UsaPasswordHash { get; set; } public string UsaPasswordSalt { get; set; } public User Usp { get; set; } } }
using System; using System.Data; namespace DMS.Presentation { /// <summary> /// Summary description for IDataEdit. /// </summary> public interface IDataEdit { void Insert(DataRow row); void Update(DataRow row); void Delete(DataRow row); void UpdateAll(DataTable dt); bool ValidateData(); } }
using System; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference of type `Collider`. Inherits from `AtomEventReference&lt;Collider, ColliderVariable, ColliderEvent, ColliderVariableInstancer, ColliderEventInstancer&gt;`. /// </summary> [Serializable] public sealed class ColliderEventReference : AtomEventReference< Collider, ColliderVariable, ColliderEvent, ColliderVariableInstancer, ColliderEventInstancer>, IGetEvent { } }
using System.Collections.Generic; using System.Threading.Tasks; namespace BillingApp.Interfaces { public interface IBillingService { public Task<double> CalculatePrice(IEnumerable<string> purchasedItems); } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace FootballBettingModels { public class Competition { public Competition() { this.Games = new HashSet<Game>(); } [Key] public int Id { get; set; } [Required] public string Name { get; set; } public int CompetitionTypeId { get; set; } public virtual CompetitionType CompetitionType { get; set; } public ICollection<Game> Games { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class back_Music : MonoBehaviour { private AudioSource audioSource; public AudioClip backkround; void Start() { audioSource = GetComponent<AudioSource>(); audioSource.clip = backkround; audioSource.Play(0); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem33 : ProblemBase { public override string ProblemName { get { return "33: Digit cancelling fractions"; } } public override string GetAnswer() { return GetCount().ToString(); } private decimal GetCount() { decimal num = 1; decimal den = 1; for (decimal a = 10; a <= 99; a++) { for (decimal b = a + 1; b <= 99; b++) { if (a % 10 == 0 && b % 10 == 0) { break; } string aAsString = a.ToString(); string bAsString = b.ToString(); for (int index = 0; index < 2; index++) { string digit = aAsString.Substring(index, 1); string aCancelled = aAsString.Replace(digit, ""); string bCancelled = bAsString.Replace(digit, ""); if (aCancelled.Length > 0 && bCancelled.Length > 0 && aCancelled != "0" && bCancelled != "0") { decimal x = a / b; decimal y = Convert.ToDecimal(aCancelled) / Convert.ToDecimal(bCancelled); if (x == y) { num *= a; den *= b; } } } } } return FindLowestDen(num, den); } private decimal FindLowestDen(decimal a, decimal b) { decimal den = 0; if (b % 2 == 0) { den = b / 2; } else { den = (b / 2) - Convert.ToDecimal(0.5); } while (true) { if (a % den == 0 && b % den == 0) { return (b / den); } den -= 1; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //by julia duda public class ObrazyScore : MonoBehaviour { public static int theScore; public GameObject teleport; public GameObject scoreText; void Update() { scoreText.GetComponent<Text>().text = " " + theScore; teleporter(); } public void teleporter() { if (ObrazyScore.theScore == 3) { teleport.SetActive(true); Debug.Log("Zebrano 3 punkty!"); } } }
namespace StrBuilderExtensions { using System; using System.Text; class Program { static void Main() { var sb = new StringBuilder(); sb.Append("This is some random text"); Console.WriteLine(sb.Substring(5, 15)); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Kingdee.CAPP.Common; namespace Kingdee.CAPP.Model { /// <summary> /// 类型说明:物料实体类 /// 作 者:jason.tang /// 完成时间:2013-03-05 /// </summary> [TypeConverter(typeof(PropertySorter))] public class MaterialModule { /// <summary> /// 物料类型ID /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("类别ID"), DisplayName("类别ID"), PropertyOrder(12)] [ReadOnlyAttribute(false)] public string TypeId { get; set; } /// <summary> /// 物料类型名称 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("物料类型名称"), DisplayName("物料类型名称"), PropertyOrder(13)] [ReadOnlyAttribute(false)] public string TypeName { get; set; } #region V_MAT_MATERIALVERSION视图 /// <summary> /// 物料编码 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("物料编码"), DisplayName("物料编码"), PropertyOrder(10)] [ReadOnlyAttribute(false)] public string code { get; set; } /// <summary> /// 物料名称 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("物料名称"), DisplayName("物料名称"), PropertyOrder(11)] [ReadOnlyAttribute(false)] public string name { get; set; } /// <summary> /// 图号 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("图号"), DisplayName("图号"), PropertyOrder(14)] [ReadOnlyAttribute(false)] public string drawnumber { get; set; } /// <summary> /// 规格 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("规格"), DisplayName("规格"), PropertyOrder(15)] [ReadOnlyAttribute(false)] public string spec { get; set; } /// <summary> /// 版本号 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("版本号"), DisplayName("版本号"), PropertyOrder(16)] [ReadOnlyAttribute(false)] public string vercode { get; set; } /// <summary> /// 生产方式 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("生产方式"), DisplayName("生产方式"), PropertyOrder(17)] [ReadOnlyAttribute(false)] public string intproductmode { get; set; } /// <summary> /// 创建时间 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("创建时间"), DisplayName("创建时间"), PropertyOrder(18)] [ReadOnlyAttribute(false)] public string createdate { get; set; } /// <summary> /// 组件数量 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("组件数量"), DisplayName("组件数量"), PropertyOrder(19)] [ReadOnlyAttribute(false)] public int count { get; set; } /// <summary> /// 归属产品 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("归属产品"), DisplayName("归属产品"), PropertyOrder(20)] [ReadOnlyAttribute(false)] public string productname { get; set; } /// <summary> /// 业务类型 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("业务类型"), DisplayName("业务类型"), PropertyOrder(21)] [ReadOnlyAttribute(false)] public string categoryname { get; set; } /// <summary> /// 设计虚件 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("设计虚件"), DisplayName("设计虚件"), PropertyOrder(22)] [ReadOnlyAttribute(false)] public string isvirtualdesign { get; set; } /// <summary> /// 通用类别 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("通用类别"), DisplayName("通用类别"), PropertyOrder(23)] [ReadOnlyAttribute(false)] public string typename { get; set; } /// <summary> /// 图纸张数 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("图纸张数"), DisplayName("图纸张数"), PropertyOrder(24)] [ReadOnlyAttribute(false)] public int papercount { get; set; } /// <summary> /// 成员规格 /// </summary> [CategoryAttribute("物料属性"), DescriptionAttribute("成员规格"), DisplayName("成员规格"), PropertyOrder(25)] [ReadOnlyAttribute(false)] public string memberspec { get; set; } [Browsable(false)] public string materialverid { get; set; } [Browsable(false)] public string baseid { get; set; } [Browsable(false)] public string pbomid { get; set; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [RequireComponent(typeof(SpriteRenderer))] [RequireComponent(typeof(Image))] public class SpriteToImageConvert : MonoBehaviour { private SpriteRenderer spriteRenderer; private Image image; private void Awake() { spriteRenderer = GetComponent<SpriteRenderer>(); image = GetComponent<Image>(); } // Update is called once per frame void LateUpdate() { if (spriteRenderer == null || image == null) return; if (spriteRenderer.sprite != null) image.sprite = spriteRenderer.sprite; } }
using System; using System.Globalization; using Xamarin.Forms; namespace HealthVault.Sample.Xamarin.Core.Converters { public class ItemTappedEventArgsConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return ((ItemTappedEventArgs)value).Item; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using Pathoschild.Stardew.Common.Utilities; namespace ContentPatcher.Framework.Tokens { /// <summary>A token whose value may change depending on the current context.</summary> internal interface IToken : IContextual { /********* ** Accessors *********/ /// <summary>The token name.</summary> TokenName Name { get; } /// <summary>Whether this token recognises subkeys (e.g. <c>Relationship:Abigail</c> is a <c>Relationship</c> token with a <c>Abigail</c> subkey).</summary> bool CanHaveSubkeys { get; } /// <summary>Whether this token only allows subkeys (see <see cref="CanHaveSubkeys"/>).</summary> bool RequiresSubkeys { get; } /********* ** Public methods *********/ /// <summary>Whether the token may return multiple values for the given name.</summary> /// <param name="name">The token name.</param> bool CanHaveMultipleValues(TokenName name); /// <summary>Perform custom validation.</summary> /// <param name="name">The token name to validate.</param> /// <param name="values">The values to validate.</param> /// <param name="error">The validation error, if any.</param> /// <returns>Returns whether validation succeeded.</returns> bool TryValidate(TokenName name, InvariantHashSet values, out string error); /// <summary>Get the current subkeys (if supported).</summary> IEnumerable<TokenName> GetSubkeys(); /// <summary>Get the allowed values for a token name (or <c>null</c> if any value is allowed).</summary> /// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="CanHaveSubkeys"/> or <see cref="RequiresSubkeys"/>.</exception> InvariantHashSet GetAllowedValues(TokenName name); /// <summary>Get the current token values.</summary> /// <param name="name">The token name to check.</param> /// <exception cref="InvalidOperationException">The key doesn't match this token, or the key does not respect <see cref="CanHaveSubkeys"/> or <see cref="RequiresSubkeys"/>.</exception> IEnumerable<string> GetValues(TokenName name); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication1.EfStuff.Model.Energy { public class ElectricityMeter : BaseModel { /// <summary> /// Серийный номер у счетчика для регистраций /// </summary> public string SerialNumber { get; set; } public int Consumption { get; set; } public int Debt { get; set; } public virtual ElectricBill ElectricBill { get; set; } public virtual PersonalAccount Account { get; set; } } }
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using TCX.Configuration; namespace OMSamples.Samples { [SampleCode("change_state_extension")] [SampleParam("arg1", "ID extension change status")] [SampleParam("arg2", "State true or false")] [SampleDescription("Change state extension to enable or disabled")] class ExtensionChangeState : ISample { public void Run(string[] args, NetworkStream service) { try { PhoneSystem ps = PhoneSystem.Root; Extension ext = PhoneSystem.Root.GetDNByNumber(args[1]) as Extension; string json = "{'change_state_to': '"+args[2]+"'}"; ext.Enabled = args[2] == "true" ? true : false; ext.Save(); // Send back a response. byte[] msg = System.Text.Encoding.ASCII.GetBytes($"{json}"); service.Write(msg, 0, msg.Length); } catch (Exception ex) { byte[] msg = System.Text.Encoding.ASCII.GetBytes(ex.Message); service.Write(msg, 0, msg.Length); } } } }
//----------------------------------------------------------------------- // <copyright file="Log.cs" company="https://github.com/jhueppauff/Syslog.Server"> // Copyright 2018 Jhueppauff // MIT License // For licence details visit https://github.com/jhueppauff/Syslog.Server/blob/master/LICENSE // </copyright> //----------------------------------------------------------------------- using AzureStorageAdapter.Table; using Microsoft.Azure.ServiceBus; using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Syslog.Server.Model.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; namespace Syslog.Server.Data { /// <summary> /// Log Class /// </summary> public class Log { private readonly List<StorageEndpointConfiguration> configuration; /// <summary> /// Initializes a new instance of the <see cref="Log"/> class. /// </summary> /// <param name="configuration">Inject the <see cref="IConfiguration"/> class.</param> public Log(List<StorageEndpointConfiguration> configuration) { this.configuration = configuration; } /// <summary> /// Writes to log. /// </summary> /// <param name="message">The message to write.</param> /// <param name="path">The path of the file.</param> public async Task WriteToLog(Syslog.Shared.Model.Message[] messages) { if (messages.Length != 0) { foreach (StorageEndpointConfiguration configItem in configuration) { switch (configItem.ConnectionType) { case "TableStorage": await TableOutput(messages, configItem); break; case "ServiceBus": await ServiceBusOutput(messages, configItem); break; case "LocalFile": foreach (var item in messages) { await File.AppendAllTextAsync(configItem.ConnectionString, JsonConvert.SerializeObject(messages)); } break; default: Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Unknow output type: {configItem.ConnectionType}. Check your appsettings"); Console.ResetColor(); break; } } } } private static async Task ServiceBusOutput(Shared.Model.Message[] messages, StorageEndpointConfiguration configItem) { try { QueueClient queueClient = new QueueClient(configItem.ConnectionString, configItem.Name); List<Microsoft.Azure.ServiceBus.Message> serviceBusMessages = new List<Microsoft.Azure.ServiceBus.Message>(); foreach (Syslog.Shared.Model.Message logMessage in messages) { Microsoft.Azure.ServiceBus.Message serviceBusMessage = new Microsoft.Azure.ServiceBus.Message() { Body = Encoding.UTF8.GetBytes(logMessage.MessageText), MessageId = logMessage.RowKey, PartitionKey = logMessage.PartitionKey, }; serviceBusMessage.UserProperties.Add("SourceIP", logMessage.SourceIP); serviceBusMessage.UserProperties.Add("RecvTime", logMessage.RecvTime); serviceBusMessages.Add(serviceBusMessage); } await queueClient.SendAsync(serviceBusMessages); } catch (Exception ex) { if (Program.telemetryClient != null) { Program.telemetryClient.TrackException(ex); } Console.WriteLine("An error occured: " + ex.Message); } } private static async Task TableOutput(Shared.Model.Message[] messages, StorageEndpointConfiguration configItem) { TableStorageAdapter tableStorageAdapter = new TableStorageAdapter(configItem.ConnectionString); await tableStorageAdapter.ExcuteBatchOperationToTable(configItem.Name, messages).ConfigureAwait(false); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace WebAPITest.Migrations { public partial class AddedIcons2 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Icons", table: "NBL", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Icons", table: "NBL"); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace ClassLibrary1.Mocking { public class VideoService { private IFileReader _fileReader; private IVideoRepository _videoRepository; // constructor injection public VideoService(IFileReader fileReader = null, IVideoRepository videoRepository = null) { _fileReader = fileReader ?? new FileReader(); _videoRepository = videoRepository ?? new VideoRepository(); } public string ReadVideoTitle() { // step1. isolate an class var str = _fileReader.Read("video.txt"); var video = JsonConvert.DeserializeObject<Video>(str); if (video == null) return "Error parsing the video."; return video.Title; } public string GetUnprocessedVideoAsCsv() { var videoIds = new List<int>(); var videos = _videoRepository.GetUnprocessedVideos(); foreach (var v in videos) videoIds.Add(v.Id); return String.Join(",", videoIds); } } public class VideoContext : IDisposable { public List<Video> Videos { get; set; } public void Dispose() { throw new NotImplementedException(); } } public class Video { public int Id { get; set; } public string Title { get; set; } public bool IsProcessed { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace DataAccessLayer.dbDTO { public class ReturnNewestQuestions { public int id { get; set; } public string title { get; set; } public string body { get; set; } public DateTime creation_date { get; set; } public int score { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using ConFutureNce.Models; using Microsoft.AspNetCore.Http; using System.IO; using System.Linq.Expressions; using Microsoft.AspNetCore.Identity; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Data.SqlClient; using ConFutureNce.Models.PaperViewModel; using Microsoft.AspNetCore.Authorization; namespace ConFutureNce.Controllers { public class PapersController : Controller { private readonly ConFutureNceContext _context; private readonly UserManager<ApplicationUser> _userManager; public PapersController(ConFutureNceContext context, UserManager<ApplicationUser> userManager) { _context = context; _userManager = userManager; } // GET: Papers [Authorize] public async Task<IActionResult> Index(string sortOrder, string searchString, string currentFilter, int? page) { // Sorting properties ViewData["TitleENGSortParam"] = String.IsNullOrEmpty(sortOrder) ? "TitleENGDesc" : ""; ViewData["AuthorSortParam"] = sortOrder == "AuthorAsc" ? "AuthorDesc" : "AuthorAsc"; ViewData["AuthorsSortParam"] = sortOrder == "AuthorsAsc" ? "AuthorsDesc" : "AuthorsAsc"; ViewData["ReviewerSortParam"] = sortOrder == "ReviewerAsc" ? "ReviewerDesc" : "ReviewerAsc"; ViewData["StatusSortParam"] = sortOrder == "StatusAsc" ? "StatusDesc" : "StatusAsc"; // Pagination propertie ViewData["CurrentSort"] = sortOrder; if (searchString != null) page = 1; else searchString = currentFilter; int pageSize = 10; // Searching propertie ViewData["CurrentFilter"] = searchString; var currentUserId = _userManager.GetUserId(HttpContext.User); var papers = _context.Paper .Include(p => p.Author.ApplicationUser) .Include(p => p.PaperKeywords) .Include(p => p.Reviewer.ApplicationUser) .Include(p => p.Payment); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); ViewData["UserString"] = currentUser.Users.FirstOrDefault().GetType().ToString(); foreach (var userType in currentUser.Users) { switch (userType.GetType().ToString()) { case "ConFutureNce.Models.Author": { var authorId = userType.UserTypeId; IEnumerable<Paper> model = papers .Where(p => p.AuthorId == authorId) .OrderBy(p => p.TitleENG); // Delete unpaid papers var toDelete = model.Where(p => p.Payment == null); _context.Paper.RemoveRange(toDelete); await _context.SaveChangesAsync(); model = SearchPapers(model, searchString); model = SortPapers(model,sortOrder); model = PaginatedList<Paper>.Create( model, page ?? 1, pageSize); return View("Author", (PaginatedList<Paper>)model); } case "ConFutureNce.Models.Reviewer": { var reviewerId = userType.UserTypeId; IEnumerable<Paper> model = papers .Where(p => p.ReviewerId == reviewerId) .OrderBy(p => p.TitleENG); model = SearchPapers(model, searchString); model = SortPapers(model, sortOrder); model = PaginatedList<Paper>.Create(model, page ?? 1, pageSize); return View("Reviewer", (PaginatedList<Paper>)model); } case "ConFutureNce.Models.ProgrammeCommitteeMember": { IEnumerable<Paper> model = papers .OrderBy(p => p.TitleENG); model = SearchPapers(model, searchString); model = SortPapers(model, sortOrder); model = PaginatedList<Paper>.Create(model, page ?? 1, pageSize); return View("ProgrammeCommitteeMember", (PaginatedList<Paper>) model); } } } return RedirectToAction("AccessDenied", "Account", null); } // GET: Papers/Details/5 [Authorize] public async Task<IActionResult> Details(int? id) { if (id == null) { return View("NotFound"); } var paper = await _context.Paper .Include(p => p.Author.ApplicationUser) .Include(p => p.Language) .Include(p => p.PaperKeywords) .Include(p => p.Reviewer.ApplicationUser) .Include(p => p.Review) .SingleOrDefaultAsync(m => m.PaperId == id); if (paper == null) { return View("NotFound"); } var currentUserId = _userManager.GetUserId(HttpContext.User); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); ViewData["UserString"] = currentUser.Users.FirstOrDefault().GetType().ToString(); foreach (var userType in currentUser.Users) { switch (userType.GetType().ToString()) { case "ConFutureNce.Models.Reviewer": { if (paper.ReviewerId != userType.UserTypeId) { return RedirectToAction("AccessDenied", "Account", null); } return View("DetailsReviewer", paper); } case "ConFutureNce.Models.Author": { if (paper.AuthorId != userType.UserTypeId) { return RedirectToAction("AccessDenied", "Account", null); } return View(paper); } } } return View(paper); } // GET: Papers/Create [Authorize] public async Task<IActionResult> Create() { var currentUserId = _userManager.GetUserId(HttpContext.User); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); ViewData["UserString"] = currentUser.Users.FirstOrDefault().GetType().ToString(); foreach (var userType in currentUser.Users) { if (userType.GetType().ToString() == "ConFutureNce.Models.Author") { var paperCount = _context.Paper .Count(p => p.AuthorId == currentUser.Users .First(u => u.GetType() == typeof(Author)) .UserTypeId); if (paperCount >= 10) break; ICollection<Language> languageList = new List<Language>(); languageList = (from language in _context.Language select language).ToList(); ViewBag.ListofLanguages = languageList; return View(); } } return RedirectToAction("Index"); } // POST: Papers/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [Authorize] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("PaperId,TitleENG,TitleORG,Authors,Abstract,OrgName,LanguageId,PaperKeywords")] ViewModels.PaperPaperKeyworsViewModel paperPaperKeyword, IFormFile file) { var userId = _userManager.GetUserId(HttpContext.User); var user = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == userId); foreach (var userType in user.Users) { if (userType.GetType().ToString() == "ConFutureNce.Models.Author") { if (ModelState.IsValid & file != null) { var paper = new Paper { Abstract = paperPaperKeyword.Abstract, TitleENG = paperPaperKeyword.TitleENG, TitleORG = paperPaperKeyword.TitleORG, Authors = paperPaperKeyword.Authors, OrgName = paperPaperKeyword.OrgName, LanguageId = paperPaperKeyword.LanguageId }; var userTypeId = user.Users.First().UserTypeId; paper.AuthorId = userTypeId; if (paperPaperKeyword.PaperKeywords != null) { var paperKeywordsTableWithRepeats = paperPaperKeyword.PaperKeywords.Split(","); for (int i = 0; i < paperKeywordsTableWithRepeats.Length; i++) { paperKeywordsTableWithRepeats[i] = paperKeywordsTableWithRepeats[i].Trim(); } paperKeywordsTableWithRepeats = paperKeywordsTableWithRepeats.Where(x => !string.IsNullOrEmpty(x)).ToArray(); var paperKeywordsTable = paperKeywordsTableWithRepeats.Distinct().ToArray(); List<PaperKeyword> ppk = new List<PaperKeyword>(); foreach (string keyword in paperKeywordsTable) { var paperKeywords = new PaperKeyword { KeyWord = keyword, Paper = paper }; ppk.Add(paperKeywords); } paper.PaperKeywords = ppk; } using (var memoryStream = new MemoryStream()) { await file.CopyToAsync(memoryStream); paper.PaperFile = memoryStream.ToArray(); } paper.SubmissionDate = DateTime.Now; paper.Status = 0; _context.Add(paper); await _context.SaveChangesAsync(); return RedirectToAction("Index", "Payments", new PaymentViewModel { UserName = user.Fullname, BillingAddress = user.Address, PaperId = paper.PaperId }); } ICollection<Language> languageList = new List<Language>(); languageList = (from language in _context.Language select language).ToList(); ViewBag.ListofLanguages = languageList; return View(paperPaperKeyword); } } return RedirectToAction("Index"); } [Authorize] public async Task<IActionResult> AssignReviewer() { var currentUserId = _userManager.GetUserId(HttpContext.User); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); ViewData["UserString"] = currentUser.Users.FirstOrDefault().GetType().ToString(); foreach (var userType in currentUser.Users) { if (userType.GetType().ToString() == "ConFutureNce.Models.ProgrammeCommitteeMember") { IEnumerable<Paper> model = _context.Paper .Include(p => p.Author.ApplicationUser) .Include(p => p.PaperKeywords) .Include(p => p.Reviewer.ApplicationUser) .Include(p => p.Language.ReviewersFirst) .Include(p => p.Language.ReviewersSecond) .Include(p => p.Language.ReviewersThird); model = model.OrderBy(p => (p.Reviewer != null ? p.Reviewer.ApplicationUser.Fullname : string.Empty)); // SelectList data preparation var papersLanguage = model .GroupBy(p => p.LanguageId) .Select(p => p.First()) .Select(p => new { langId = p.LanguageId, reviewerslist = p.Language.AllReviewers }) .OrderBy(pl => pl.langId); var Vmodel = new List<AssignReviewerViewModel>(); var reviewers = _context.ApplicationUser; foreach (var language in papersLanguage) { var tempList = language.reviewerslist .Select(r => new ReviewerVM { ReviewerId = r.UserTypeId, ReviewerName = reviewers.First(au => au.Id == r.ApplicationUserId).Fullname }) .ToList(); tempList.Insert(0, new ReviewerVM { ReviewerId = -1, ReviewerName = "SELECT REVIEWER" }); Vmodel.Add(new AssignReviewerViewModel { LangId = language.langId, reviewersPerLang = tempList }); } ViewBag.listOfReviewers = Vmodel; return View(model); } } return RedirectToAction("AccessDenied", "Account", null); } // POST: PAPERS/ASSIGNREVIEWER // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [Authorize] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AssignReviewer(IFormCollection form) { var currentUserId = _userManager.GetUserId(HttpContext.User); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); foreach (var userType in currentUser.Users) { if (userType.GetType().ToString() == "ConFutureNce.Models.ProgrammeCommitteeMember") { if (ModelState.IsValid) { var assignedReviewers = Request.Form["item.ReviewerId"]; var papersToAssign = Request.Form["item.PaperId"]; var papers = _context.Paper .Where(p => p.ReviewerId == null); for (var i = 0; i < papersToAssign.Count; i++) { if (assignedReviewers[i] == "-1") continue; var paper = await _context.Paper .FirstAsync(p => p.PaperId == Convert.ToInt32(papersToAssign[i])); paper.ReviewerId = Convert.ToInt32(assignedReviewers[i]); paper.Status = Paper.ProcessStatus.UnderReview; } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } } return View(); } [Authorize] public async Task<IActionResult> ChoosePaper() { var currentUserId = _userManager.GetUserId(HttpContext.User); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); ViewData["UserString"] = currentUser.Users.FirstOrDefault().GetType().ToString(); foreach (var userType in currentUser.Users) { if (userType.GetType().ToString() == "ConFutureNce.Models.ProgrammeCommitteeMember") { IEnumerable<Paper> model = _context.Paper .Include(p => p.Author.ApplicationUser) .Include(p => p.PaperKeywords) .Include(p => p.Reviewer.ApplicationUser); model = model.OrderBy(p => (p.Reviewer != null ? p.Reviewer.ApplicationUser.Fullname : string.Empty)); // SelectList data preparation var statusList = new List<object> { new { StatusId = Convert.ToInt32(Paper.ProcessStatus.Qualified), StatusName = "Qualified" }, new { StatusId = Convert.ToInt32(Paper.ProcessStatus.Unqualified), StatusName = "Unqualified" } }; statusList.Insert(0, new { StatusId = -1, StatusName = "Select"}); ViewBag.listOfStatus = statusList; return View(model); } } return RedirectToAction("Index"); } // POST: PAPERS/ASSIGNREVIEWER // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [Authorize] [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChoosePaper(IFormCollection form) { var currentUserId = _userManager.GetUserId(HttpContext.User); var currentUser = _context.ApplicationUser .Include(ap => ap.Users) .FirstOrDefault(ap => ap.Id == currentUserId); foreach (var userType in currentUser.Users) { if (userType.GetType().ToString() == "ConFutureNce.Models.ProgrammeCommitteeMember") { if (ModelState.IsValid) { var assignedStatuses = Request.Form["item.Status"]; var papersToAssign = Request.Form["item.PaperId"]; var papers = _context.Paper .Where(p => p.Status == Paper.ProcessStatus.Reviewed); for (var i = 0; i < papersToAssign.Count; i++) { if (assignedStatuses[i] == "-1") continue; var paper = await _context.Paper .FirstAsync(p => p.PaperId == Convert.ToInt32(papersToAssign[i])); paper.Status = (Paper.ProcessStatus)Convert.ToInt32(assignedStatuses[i]); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(); } } return RedirectToAction("Index"); } private bool PaperExists(int id) { return _context.Paper.Any(e => e.PaperId == id); } // Need loaded Authors and Reviever object with their ApplicationUser objects private IEnumerable<Paper> SortPapers(IEnumerable<Paper> papersToSort, string sortOrder) { switch (sortOrder) { case "TitleENGDesc": { papersToSort = papersToSort.OrderByDescending(p => p.TitleENG); break; } case "AuthorDesc": { papersToSort = papersToSort.OrderByDescending(p => p.Author.ApplicationUser.Fullname); break; } case "AuthorAsc": { papersToSort = papersToSort.OrderBy(p => p.Author.ApplicationUser.Fullname); break; } case "AuthorsDesc": { papersToSort = papersToSort.OrderByDescending(p => p.Authors); break; } case "AuthorsAsc": { papersToSort = papersToSort.OrderBy(p => p.Authors); break; } case "ReviewerDesc": { papersToSort = papersToSort .OrderByDescending(p => p.Reviewer != null ? p.Reviewer.ApplicationUser.Fullname : string.Empty); break; } case "ReviewerAsc": { papersToSort = papersToSort .OrderBy(p => p.Reviewer != null ? p.Reviewer.ApplicationUser.Fullname : string.Empty); break; } case "StatusDesc": { papersToSort = papersToSort.OrderByDescending(p => p.Status); break; } case "StatusAsc": { papersToSort = papersToSort.OrderBy(p => p.Status); break; } default: { papersToSort = papersToSort.OrderBy(p => p.TitleENG); break; } } return papersToSort; } // Need loaded Authors and Reviever object with their ApplicationUser objects private IEnumerable<Paper> SearchPapers(IEnumerable<Paper> papersToFilter, string searchString) { if (!String.IsNullOrEmpty(searchString)) { papersToFilter = papersToFilter .Where(p => p.TitleENG.Contains(searchString) || p.Author.ApplicationUser.Fullname.Contains(searchString) || p.Authors.Contains(searchString) || (p.Reviewer != null ? p.Reviewer.ApplicationUser.Fullname.Contains(searchString) : false) || p.KeywordsToString.Contains(searchString) || p.Status.ToString().Contains(searchString)); } return papersToFilter; } [HttpGet] public FileContentResult DownloadFile(int id) { byte[] fileData; string fileName; var record = from p in _context.Paper where p.PaperId == id select p; fileData = record.First().PaperFile.ToArray(); fileName = record.First().TitleORG + ".pdf"; return File(fileData, "application/pdf", fileName); } } }
using System; using System.Collections.Generic; using System.Drawing; using Grasshopper.Kernel; using PterodactylCharts; using Rhino.Geometry; namespace Pterodactyl { public class PointDataGH : GH_Component { public PointDataGH() : base("Point Data", "Point Data", "Add point data", "Pterodactyl", "Advanced Graph") { } public override bool IsBakeCapable => false; protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { pManager.AddColourParameter("Color", "Color", "Add color for point data", GH_ParamAccess.item, Color.Black); pManager.AddIntegerParameter("Marker", "Marker", "Choose marker as int. 0 - None, 1 - Circle, 2 - Square, 3 - Diamond, 4 - Triangle", GH_ParamAccess.item, 1); } protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { pManager.AddGenericParameter("Data Type", "Data Type", "Set data type", GH_ParamAccess.item); } protected override void SolveInstance(IGH_DataAccess DA) { Color color = Color.Empty; int marker = 0; DA.GetData(0, ref color); DA.GetData(1, ref marker); DataType dataType = new DataType(color, marker); DA.SetData(0, dataType); } protected override System.Drawing.Bitmap Icon { get { return Properties.Resources.PterodactylPointData; } } public override GH_Exposure Exposure { get { return GH_Exposure.quarternary; } } public override Guid ComponentGuid { get { return new Guid("ce4dd50d-6bf6-448f-afdb-9ddeeda515ba"); } } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test_LLU_Service2 { class SQLTest { public static string[] LocalExecuteSQL_Single(string sqlConnectionString, string sql) { string[] ret = new string[10000]; string rowline = null; SqlConnection cnn = new SqlConnection(sqlConnectionString); SqlCommand sqlCommand; SqlDataReader sqlDatareader; try { cnn.Open(); sqlCommand = new SqlCommand(sql, cnn); sqlDatareader = sqlCommand.ExecuteReader(); int row = 0; if (sqlDatareader.HasRows) { while (sqlDatareader.Read()) { string[] line = new string[100]; rowline = ""; int col; for (col = 0; col < sqlDatareader.FieldCount; col++) { line[col] = sqlDatareader.GetValue(col).ToString(); rowline += sqlDatareader.GetValue(col).ToString() + ";"; } rowline = rowline.Remove(rowline.Length-1, 1); } } ret[row] = rowline; sqlDatareader.Close(); sqlCommand.Dispose(); cnn.Close(); } catch (Exception ex) { ret = null; ret[0] = $"Can (most likely) not open connection ! (Connectionstring: {sqlConnectionString})"; return ret; } return ret; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class MenuController : MonoBehaviour { public GameObject scrMain; public GameObject scrConfiguracion; public GameObject btnIniciar; public GameObject btnConfiguracion; public GameObject btnSalir; public GameObject btnBackConf; private CanvasGroup confCanvas; // Use this for initialization void Start () { //inicializar gameobjects scrMain = GameObject.Find ("MainScreen"); scrConfiguracion = GameObject.Find ("ConfiguracionScreen"); btnIniciar = GameObject.Find ("BtnIniciar"); btnConfiguracion = GameObject.Find ("BtnConfiguracion"); btnSalir = GameObject.Find ("BtnSalir"); btnBackConf = GameObject.Find ("BtnBackConf"); //ocultar menu scrConfiguracion.SetActive(false); //visibilidad confCanvas = scrConfiguracion.GetComponent<CanvasGroup>(); confCanvas.alpha = 1; //oculto en la interfaz pero visible cuando se utilice //listeners botonIniciar(); botonSalir(); botonConf (); botonBackConf (); } // Update is called once per frame void Update () { } void botonIniciar(){ //listener para iniciar el xplora btnIniciar.GetComponent<Button> ().onClick.AddListener(()=> { SceneManager.LoadScene("tablero", LoadSceneMode.Single); }); } void botonConf(){ //listener que desactiva la pantalla anterior y activa la pantalla siguiente btnConfiguracion.GetComponent<Button> ().onClick.AddListener (() => { scrConfiguracion.SetActive(true); scrMain.SetActive(false); }); } void botonBackConf(){ //listener que desactiva la pantalla anterior y activa la pantalla siguiente btnBackConf.GetComponent<Button> ().onClick.AddListener (() => { scrMain.SetActive(true); scrConfiguracion.SetActive(false); }); } void botonSalir(){ //listener que sale del programa btnSalir.GetComponent<Button> ().onClick.AddListener (()=>{ salir(); }); } void salir(){ //si esta en el editor, hace pausa, sino sale del programa #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit (); #endif } }
using UnityEngine; public class LookAt : MonoBehaviour { public float w = 0f; public float wMax = 0.01f; public Transform target; void Update(){ var t = transform; var u = target.position - transform.position; var v = Vector3.Lerp(t.forward, u, w); transform.forward = v; w+=0.000001f; if(w>wMax) w=wMax; } }
using System; using System.Collections.Generic; using Utilities; namespace EddiEvents { [PublicAPI] public class BountyAwardedEvent : Event { public const string NAME = "Bounty awarded"; public const string DESCRIPTION = "Triggered when you are awarded a bounty"; public const string SAMPLE = @"{ ""timestamp"":""2016-12-29T10:10:11Z"", ""event"":""Bounty"", ""Rewards"":[ { ""Faction"":""FrogCorp"", ""Reward"":400 }, { ""Faction"":""Federation"", ""Reward"":123187 } ], ""Target"":""federation_dropship_mkii"", ""TotalReward"":123587, ""VictimFaction"":""TZ Arietis Purple Council"" }"; [PublicAPI("The name of the asset you destroyed (if applicable)")] public string target { get; private set; } [PublicAPI("The name of the faction whose asset you destroyed")] public string faction { get; private set; } [PublicAPI("The total number of credits obtained for destroying the asset")] public long reward { get; private set; } [PublicAPI("The rewards obtained for destroying the asset")] public List<Reward> rewards { get; private set; } [PublicAPI("True if the rewards have been shared with wing-mates")] public bool shared { get; private set; } public BountyAwardedEvent(DateTime timestamp, string target, string faction, long reward, List<Reward> rewards, bool shared) : base(timestamp, NAME) { this.target = target; this.faction = faction; this.reward = reward; this.rewards = rewards; this.shared = shared; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using static System.Math; namespace NewFeaturesComparisonCS6 { /// <summary> /// C# 6 (.NET 4.6) implementation. /// </summary> public class NewFeatures : IFeatureComparison { /// <summary> /// Gets a read only property value. /// </summary> public bool IsReadOnly { get; } = true; /// <summary> /// Gets the name of a property (in this case IsReadOnly property) /// NOTE: This is refactor friendly code. /// </summary> public string IsReadOnlyPropertyName { get; } = nameof(IsReadOnly); /// <summary> /// Simple event handler. /// </summary> public event EventHandler OperationCompleted; /// <summary> /// Simple Math.Pow calculation. /// </summary> public double Compute(double a, double b) => Pow(a, b); /// <summary> /// A bit more complex async method when using C# 5 language. /// In C# 6 await is now supported in catch and finally statements! /// </summary> public async Task DoSomeWorkWithTryCatchFinallyAsync(bool throwExceptionInCatch) { Exception tryException = null; try { ThrowAndLogException(); } catch (Exception e) { // Do analytics, uploading bug infos, etc. This will throw exception if throwExceptionInCatch is true. await SharedUtils.ThrowExceptionIfTrueOtherwiseWaitAsync(throwExceptionInCatch); } finally { // Finally has to execute regardless what happened above. // Perhaps log something or wait for resources to get free. RaiseEvent(); } } /// <summary> /// Simple event invocation. /// </summary> public void RaiseEvent() { // Null conditional operator is short, null safe and thread safe. (sometimes called Elvis operator - http://i.stack.imgur.com/hQlrp.png) OperationCompleted?.Invoke(this, EventArgs.Empty); } /// <summary> /// This method will throw a exception while also logging that exception before exception bubbles up /// </summary> public void ThrowAndLogException() { try { // A local variable for try statement. bool rogueVariable = true; if (rogueVariable) { // If this exception is not handled anywhere, debugger will highlight line bellow. // Value of rogueVariable and everything else in this scope is available. throw new Exception("Evil exception!!!"); } } catch (Exception ex) when (SharedUtils.Log(ex, letItThrow: true)) { Debug.WriteLine("This will never execute due exception filtering!"); } } /// <summary> /// A simple demonstration of a dictionary settings. /// </summary> /// <returns>Returns dictionary of settings.</returns> public Dictionary<string, string> GetSettings() { // More compact and "JSON like" syntax return new Dictionary<string, string> { ["EnableStuff"] = "True", ["OffsetStuff"] = "1234", ["WidthStuff"] = "12345", ["HeightStuff"] = "1234", }; } /// <summary> /// Formats a settings based on their key. /// It should gracefully handle missing keys and null settings values. /// </summary> /// <param name="key">Setting key</param> /// <returns>Returns information about a setting.</returns> public string GetFormattedSettingValue(string key) { var settings = GetSettings(); string value = null; if (!string.IsNullOrWhiteSpace(key)) { settings.TryGetValue(key, out value); } // Using Elvis operator and $" for significantly shorter code. return $"{key} => `{value ?? "key not found"}` with length {value?.Length ?? -1}"; } } }
using System; using System.Windows.Forms; using Phenix.Core.Net; using Phenix.Core.Security; namespace Phenix.Windows.Security { /// <summary> /// 修改登录口令窗体 /// </summary> public partial class ChangePasswordDialog : Phenix.Core.Windows.DialogForm { /// <summary> /// 初始化 /// </summary> protected ChangePasswordDialog() { InitializeComponent(); } #region 工厂 /// <summary> /// 修改登录口令窗体 /// </summary> public static bool Execute() { using (ChangePasswordDialog dialog = new ChangePasswordDialog()) { dialog.ServicesAddress = NetConfig.ServicesAddress; if (UserIdentity.CurrentIdentity != null && UserIdentity.CurrentIdentity.IsAuthenticated) { dialog.UserNumber = UserIdentity.CurrentIdentity.UserNumber; dialog.userNumberTextBox.Enabled = false; } return dialog.ShowDialog() == DialogResult.OK; } } internal static bool Execute(string servicesAddress) { using (ChangePasswordDialog dialog = new ChangePasswordDialog()) { dialog.ServicesAddress = servicesAddress; if (UserIdentity.CurrentIdentity != null) { dialog.UserNumber = UserIdentity.CurrentIdentity.UserNumber; if (UserIdentity.CurrentIdentity.IsAuthenticated) { dialog.OldPassword = UserIdentity.CurrentIdentity.Password; dialog.userNumberTextBox.Enabled = false; dialog.oldPasswordTextBox.Enabled = false; } } return dialog.ShowDialog() == DialogResult.OK; } } internal static bool Execute(string servicesAddress, string userNumber) { using (ChangePasswordDialog dialog = new ChangePasswordDialog()) { dialog.ServicesAddress = servicesAddress; dialog.UserNumber = userNumber; return dialog.ShowDialog() == DialogResult.OK; } } #endregion #region 属性 private string ServicesAddress { get; set; } private string Caption { get { return this.Text; } } private string UserNumber { get { return this.userNumberTextBox.Text; } set { this.userNumberTextBox.Text = value; } } private string OldPassword { get { return this.oldPasswordTextBox.Text; } set { this.oldPasswordTextBox.Text = value; } } private string NewPassword1 { get { return this.newPassword1TextBox.Text; } } private string NewPassword2 { get { return this.newPassword2TextBox.Text; } } #endregion #region 方法 private void Humanistic() { if (String.IsNullOrEmpty(UserNumber)) this.userNumberTextBox.Focus(); else if (String.IsNullOrEmpty(OldPassword)) this.oldPasswordTextBox.Focus(); else if (String.IsNullOrEmpty(NewPassword1)) this.newPassword1TextBox.Focus(); else if (String.IsNullOrEmpty(NewPassword2)) this.newPassword2TextBox.Focus(); else this.okButton.Focus(); } private void ApplyRules() { this.okButton.Enabled = (!String.IsNullOrEmpty(UserNumber)) && (!String.IsNullOrEmpty(OldPassword)) && (!String.IsNullOrEmpty(NewPassword1)) && (!String.IsNullOrEmpty(NewPassword2)); } #endregion #region 事件 private void ChangePasswordForm_Shown(object sender, EventArgs e) { ApplyRules(); Humanistic(); } private void UserNumberTextBox_TextChanged(object sender, EventArgs e) { ApplyRules(); } private void OldPasswordTextBox_TextChanged(object sender, EventArgs e) { ApplyRules(); } private void NewPassword1TextBox_TextChanged(object sender, EventArgs e) { ApplyRules(); } private void NewPassword2TextBox_TextChanged(object sender, EventArgs e) { ApplyRules(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void OK_Click(object sender, EventArgs e) { if (NewPassword1 != NewPassword2) { MessageBox.Show(Phenix.Services.Client.Properties.Resources.InputPasswordPlease, Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); this.newPassword1TextBox.Focus(); return; } this.Cursor = Cursors.WaitCursor; try { if (LogOnHelper.ChangePassword(ServicesAddress, NewPassword1, UserIdentity.CurrentIdentity != null && UserIdentity.CurrentIdentity.IsAuthenticated ? UserIdentity.CurrentIdentity : new UserIdentity(UserNumber, OldPassword))) { MessageBox.Show(Phenix.Services.Client.Properties.Settings.Default.UserNumber + UserNumber + Phenix.Services.Client.Properties.Resources.ModifyPasswordSucceed, Caption, MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } else { MessageBox.Show(Phenix.Services.Client.Properties.Settings.Default.UserNumber + UserNumber + Phenix.Services.Client.Properties.Resources.ModifyPasswordFailed, Caption, MessageBoxButtons.OK, MessageBoxIcon.Error); this.oldPasswordTextBox.Focus(); } } catch (Exception ex) { MessageBox.Show(Phenix.Services.Client.Properties.Settings.Default.UserNumber + UserNumber + Phenix.Services.Client.Properties.Resources.ModifyPasswordFailed + '\n' + Phenix.Core.AppUtilities.GetErrorHint(ex), this.Caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { this.Cursor = Cursors.Default; } } #endregion } }
using System.IO; using System.Threading.Tasks; using BSMU_Schedule.Interfaces; using BSMU_Schedule.Interfaces.DataAccess.StorageAdapters; using System.Xml.Linq; using System.Xml.Serialization; namespace BSMU_Schedule.Services.DataAccess.StorageAdapters { public class XmlStorageAdapter<T>: IStorageAdapter<T> { private readonly string fullPath; private readonly string fileName; public XmlStorageAdapter(IHasConnectionConfiguration configuration) { fileName = configuration.ConnectionConfiguration; fullPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), fileName); } public Task<T> Get() { if (!File.Exists(fullPath)) { return Task.Run(() => default(T)); } XDocument xdoc = XDocument.Load(fullPath); T obj; var xmlSerializer = new XmlSerializer(typeof(T)); using(var reader = xdoc.CreateReader()) { obj = (T)xmlSerializer.Deserialize(reader); } return Task.Run(() => obj); } public Task<T> InsertOrUpdate(T value) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StreamWriter writer = new StreamWriter(fullPath)) { serializer.Serialize(writer, value); } return Task.Run(() => value); } public void Commit() { } public void Dispose() { } } }
using Data; using Display; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using UnityEngine; using SFB; using GK; using DesktopInterface; public class LoadTextMesh : MonoBehaviour { public Material material; public void LoadFile() { var extensions = new[] { new ExtensionFilter("text format", "txt"), new ExtensionFilter("All Files", "*" ) }; StandaloneFileBrowser.OpenFilePanelAsync("Open File", "", extensions, true, (string[] paths) => { LoadMesh(paths); }); } private void LoadMesh(string[] paths) { List<float> CellIDList = new List<float>(); List<float> XList = new List<float>(); List<float> YList = new List<float>(); List<float> ZList = new List<float>(); Dictionary<float, List<Vector3>> VertexbyCellList = new Dictionary<float, List<Vector3>>(); string filepath = paths[0]; string[] lines = File.ReadAllLines(filepath); int columnNumber = lines[0].Split('\t').Length; Debug.Log(columnNumber); string[] indices_entries = lines[0].Split('\t'); string[] X_entries = lines[1].Split('\t'); string[] Y_entries = lines[2].Split('\t'); string[] Z_entries = lines[3].Split('\t'); for (int i = 0; i < columnNumber; i++) { float parsednumber; bool ParseSuccess = Single.TryParse(indices_entries[i], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out parsednumber); if (ParseSuccess) { CellIDList.Add(parsednumber); } } float xMax = Mathf.NegativeInfinity; float xMin = Mathf.Infinity; float yMax = Mathf.NegativeInfinity; float yMin = Mathf.Infinity; float zMax = Mathf.NegativeInfinity; float zMin = Mathf.Infinity; for (int i = 0; i < columnNumber; i++) { //float x, y, z; float parsednumber1; bool ParseSuccess = Single.TryParse(X_entries[i], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out parsednumber1); if (ParseSuccess) { if (parsednumber1 < xMin) { xMin = parsednumber1; } if (parsednumber1 > xMax) { xMax = parsednumber1; } XList.Add(parsednumber1);//CellIDList.Add(parsednumber); } float parsednumber2; bool ParseSuccess2 = Single.TryParse(Y_entries[i], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out parsednumber2); if (ParseSuccess2) { if (parsednumber2 < yMin) { yMin = parsednumber2; } if (parsednumber2 > yMax) { yMax = parsednumber2; } YList.Add(parsednumber2);//CellIDList.Add(parsednumber); } float parsednumber3; bool ParseSuccess3 = Single.TryParse(Z_entries[i], System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out parsednumber3); if (ParseSuccess3) { if (parsednumber3 < zMin) { zMin = parsednumber3; } if (parsednumber3 > zMax) { zMax = parsednumber3; } ZList.Add(parsednumber3);//CellIDList.Add(parsednumber); } } float xRange = xMax - xMin; float yRange = yMax - yMin; float zRange = zMax - zMin; float[] rangeList = new float[] { xRange, yRange, zRange }; float MaxRange = Mathf.Max(rangeList); Vector3 offsetVector = new Vector3((xMin + xMax) / 2, (yMin + yMax) / 2, (zMin + zMax) / 2); Debug.Log("xMax : " + xMax); Debug.Log("yMax : " + yMax); Debug.Log("zMax : " + zMax); Debug.Log("xMin : " + xMin); Debug.Log("yMin : " + yMin); Debug.Log("zMin : " + zMin); Debug.Log("MaxRange : " + MaxRange); Debug.Log(offsetVector); for(int j = 0; j < XList.Count; j++) { float Cellid = CellIDList[j]; Vector3 tempvector = new Vector3(XList[j], YList[j], ZList[j]); Vector3 resultVector = (tempvector - offsetVector) / MaxRange; //Debug.Log(tempvector+" vs "+ resultVector); if (!VertexbyCellList.ContainsKey(Cellid)) { VertexbyCellList.Add(Cellid, new List<Vector3>()); } VertexbyCellList[Cellid].Add(resultVector); } //var calc = new ConvexHullCalculator(); foreach (KeyValuePair<float, List<Vector3>> kvp in VertexbyCellList) { var verts = new List<Vector3>(); var tris = new List<int>(); var normals = new List<Vector3>(); var points = kvp.Value; //Debug.Log(kvp.Value.Count + " vertices on Cell nb : " + kvp.Key); //calc.GenerateHull(points, true, ref verts, ref tris, ref normals); for (int k = 0; k < kvp.Value.Count; k++) { //Debug.Log(k); //Debug.Log("position : " + kvp.Value[k] + " Cell : " + kvp.Key); verts.Add(kvp.Value[k]); //tris.Add(k); // Counterclockwise } for (int k = 0; k < kvp.Value.Count; k+=3) { tris.Add(k); tris.Add(k + 1); tris.Add(k + 2); tris.Add(k + 2); tris.Add(k + 1); tris.Add(k); } GameObject go = new GameObject(); MeshFilter Mfilter = go.AddComponent<MeshFilter>(); MeshRenderer Mrenderer = go.AddComponent<MeshRenderer>(); var mesh = new Mesh(); mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; mesh.SetVertices(verts); mesh.SetTriangles(tris, 0); //mesh.SetNormals(normals); //material.SetColor("_Color", Color.Lerp(Color.red, Color.green, (c.ID+1) / ClusterList.Count)); Mfilter.mesh = mesh; Mrenderer.material = material; ColorMap map = ColorMapManager.instance.GetColorMap("jet"); Mrenderer.material.SetColor("_Color", map.texture.GetPixel(Mathf.RoundToInt((kvp.Key / VertexbyCellList.Count) * 256), 1)); //Mrenderer.material.SetColor("_Color", Color.Lerp(new Color(1,0,0,0.45f), new Color(0, 1, 0, 0.45f), (float)(c.ID+1) / ClusterList.Count)); go.AddComponent<DragMouse>(); //Debug.Log("Hull Created"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceDeskSVC.Domain.Utilities { public enum TicketPriorityEnum { [Description("Unable to Work")] UnableToWork = 0, [Description("High")] High = 1, [Description("Medium")] Medium = 2, [Description("Low")] Low = 3, } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MultiUserBlock.Web.TagHelpers { public static class TagHelperTools { public static string FirstLetterToLower(string data) { if (string.IsNullOrEmpty(data)) { throw new ArgumentException("null or empty", data); } return Char.ToLowerInvariant(data[0]) + data.Substring(1); } public static string GetID(string id = "") { return id + Guid.NewGuid(); } } }
namespace Reviews.Models { public class DatabaseConfiguration { public string ReviewsCollectionName { get; set; } public string UsersCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } } }
using Microsoft.AspNet.Identity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; public partial class Simulador_tasainflacion : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string extraerindices() { var db = new Entidades(); /* Crear la instancia a las tablas de la BD */ var consulta1 = db.indice_INPC.OrderByDescending(indice => indice.Id_indice); List<string> result_ids_indice = new List<string>(); List<string> result_descrip_indice_base = new List<string>(); foreach (indice_INPC INPC_id in consulta1) { result_ids_indice.Add(INPC_id.Id_indice); result_descrip_indice_base.Add(INPC_id.descripcion_indice_base); } List<List<string>> valores = new List<List<string>>(); valores.Add(result_ids_indice); valores.Add(result_descrip_indice_base); var json = JsonConvert.SerializeObject(valores); return json; } [WebMethod] public static object get_imputs_post(string id_indice_base) { try { var db = new Entidades(); var queryMax = db.INPC.Where(t => t.id_indice == id_indice_base).Select(t => new { t.Id, t.anio }).OrderByDescending(x => x.anio).FirstOrDefault(); var queryMin = db.INPC.Where(t => t.id_indice == id_indice_base).Select(t => new { t.Id, t.anio }).OrderBy(x => x.anio).FirstOrDefault(); var anonymousObjResult = from s in db.INPC where s.id_indice == id_indice_base orderby s.anio descending select new { Id = s.Id, Name = s.anio }; List<string> R1 = new List<string>(); List<string> R2 = new List<string>(); foreach (var obj in anonymousObjResult) { R1.Add(obj.Id); R2.Add(obj.Name.ToString()); } // var studentList = db.INPC.SqlQuery("Select * from INPC where id_indice= '" + id_indice_base + "' ORDER BY anio").ToList(); //Error al final de la consulta var json = ""; if (queryMax != null && queryMin != null) { string[] meses = new string[] { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" }; int anio_MAX = (int)queryMax.anio; string id_INCP_MAX = (string)queryMax.Id; int anio_MIN = (int)queryMin.anio; string id_INCP_MIN = (string)queryMin.Id; var queryMesMax = db.INPC.Where(t => t.Id == id_INCP_MAX); var queryMesMin = db.INPC.Where(t => t.Id == id_INCP_MIN); List<double> result_query = new List<double>(); List<double> result_query2 = new List<double>(); foreach (var Result in queryMesMax) { result_query.Add((double)Result.enero); result_query.Add((double)Result.febrero); result_query.Add((double)Result.marzo); result_query.Add((double)Result.abril); result_query.Add((double)Result.mayo); result_query.Add((double)Result.junio); result_query.Add((double)Result.julio); result_query.Add((double)Result.agosto); result_query.Add((double)Result.septiembre); result_query.Add((double)Result.octubre); result_query.Add((double)Result.noviembre); result_query.Add((double)Result.diciembre); } string mesMax = meses[11]; for (int i = 1; i < result_query.Count; i++) { if (anio_MAX == anio_MIN) { if (result_query[i - 1] != 0) { mesMax = meses[i - 1]; } } else { if (result_query[0] == 0) { anio_MAX = anio_MAX - 1; mesMax = meses[11]; break; } if (result_query[i] == 0) { mesMax = meses[i - 1]; break; } } } foreach (var Result in queryMesMin) { result_query2.Add((double)Result.enero); result_query2.Add((double)Result.febrero); result_query2.Add((double)Result.marzo); result_query2.Add((double)Result.abril); result_query2.Add((double)Result.mayo); result_query2.Add((double)Result.junio); result_query2.Add((double)Result.julio); result_query2.Add((double)Result.agosto); result_query2.Add((double)Result.septiembre); result_query2.Add((double)Result.octubre); result_query2.Add((double)Result.noviembre); result_query2.Add((double)Result.diciembre); } int cuentameses = 0; int posicion = 0; string mesMin = ""; for (int i = 0; i < result_query2.Count; i++) { if (result_query2[i] == 0) { cuentameses++; mesMin = meses[i]; posicion = i; } else { break; } } if (cuentameses == 0) { mesMin = meses[0]; } else { if (cuentameses != 12) { mesMin = meses[posicion + 1]; } } List<string> T1 = new List<string>(); List<string> T2 = new List<string>(); T1.Add(Convert.ToString(anio_MIN)); T1.Add(mesMin); T1.Add(id_INCP_MIN); T2.Add(Convert.ToString(anio_MAX)); T2.Add(mesMax); T2.Add(id_INCP_MAX); List<List<string>> valoresF = new List<List<string>>(); valoresF.Add(T1); valoresF.Add(T2); valoresF.Add(R1); valoresF.Add(R2); if (cuentameses != 12) { json = JsonConvert.SerializeObject(valoresF); } else { json = ""; } } return json; } catch (ArgumentNullException e) { Console.WriteLine("{0} First exception caught.", e); return e; } } [WebMethod] public static object get_imputs_post_anio(string id_periodo_select) { var db = new Entidades(); var Result = from s in db.INPC where s.Id == id_periodo_select select new { Enero = s.enero, Febrero = s.febrero, Marzo = s.marzo, Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; var json = ""; List<string> R1 = new List<string>(); foreach (var obj in Result) { if (obj.Enero.ToString() != "0") { R1.Add("Enero"); } if (obj.Febrero.ToString() != "0") { R1.Add("Febrero"); } if (obj.Marzo.ToString() != "0") { R1.Add("Marzo"); } if (obj.Abril.ToString() != "0") { R1.Add("Abril"); } if (obj.Mayo.ToString() != "0") { R1.Add("Mayo"); } if (obj.Junio.ToString() != "0") { R1.Add("Junio"); } if (obj.Julio.ToString() != "0") { R1.Add("Julio"); } if (obj.Agosto.ToString() != "0") { R1.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { R1.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { R1.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { R1.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { R1.Add("Diciembre"); } } json = JsonConvert.SerializeObject(R1); return json; } [WebMethod] public static object get_imputs_post_anio_2(string id_periodo_select_anio) { var json = ""; var db = new Entidades(); var Result = from s in db.INPC where s.Id == id_periodo_select_anio select new { id_indice_general = s.id_indice, anio=s.anio }; var id_indice=""; int anio=0; foreach (var obj in Result) { id_indice = obj.id_indice_general; anio = obj.anio.Value; } var Result2 = from s in db.INPC where (s.id_indice == id_indice && s.anio>=anio) orderby s.anio descending select new { id_resultado = s.Id, anio = s.anio }; List<string> result_query = new List<string>(); List<string> result_query2 = new List<string>(); foreach (var obj in Result2) { result_query.Add(obj.id_resultado); result_query2.Add(obj.anio.ToString()); } List<List<string>> valoresF = new List<List<string>>(); valoresF.Add(result_query); valoresF.Add(result_query2); json = JsonConvert.SerializeObject(valoresF); return json; } [WebMethod] public static object get_imputs_post_anio_3(string id_periodo_select_anio, string id_periodo_select_mes, string id_periodo_select_anio2) { var json = ""; var db = new Entidades(); if(id_periodo_select_anio == id_periodo_select_anio2) { switch (id_periodo_select_mes) { case "enero": var lst0 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Febrero = s.febrero, Marzo = s.marzo, Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query0 = new List<string>(); foreach (var obj in lst0) { if (obj.Febrero.ToString() != "0") { result_query0.Add("Febrero"); } if (obj.Marzo.ToString() != "0") { result_query0.Add("Marzo"); } if (obj.Abril.ToString() != "0") { result_query0.Add("Abril"); } if (obj.Mayo.ToString() != "0") { result_query0.Add("Mayo"); } if (obj.Junio.ToString() != "0") { result_query0.Add("Junio"); } if (obj.Julio.ToString() != "0") { result_query0.Add("Julio"); } if (obj.Agosto.ToString() != "0") { result_query0.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query0.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query0.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query0.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query0.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query0); break; case "febrero": var lst1 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Marzo = s.marzo, Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query = new List<string>(); foreach (var obj in lst1) { if (obj.Marzo.ToString() != "0") { result_query.Add("Marzo"); } if (obj.Abril.ToString() != "0") { result_query.Add("Abril"); } if (obj.Mayo.ToString() != "0") { result_query.Add("Mayo"); } if (obj.Junio.ToString() != "0") { result_query.Add("Junio"); } if (obj.Julio.ToString() != "0") { result_query.Add("Julio"); } if (obj.Agosto.ToString() != "0") { result_query.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query); break; case "marzo": var lst2 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query2 = new List<string>(); foreach (var obj in lst2) { if (obj.Abril.ToString() != "0") { result_query2.Add("Abril"); } if (obj.Mayo.ToString() != "0") { result_query2.Add("Mayo"); } if (obj.Junio.ToString() != "0") { result_query2.Add("Junio"); } if (obj.Julio.ToString() != "0") { result_query2.Add("Julio"); } if (obj.Agosto.ToString() != "0") { result_query2.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query2.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query2.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query2.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query2.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query2); break; case "abril": var lst3 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query3 = new List<string>(); foreach (var obj in lst3) { if (obj.Mayo.ToString() != "0") { result_query3.Add("Mayo"); } if (obj.Junio.ToString() != "0") { result_query3.Add("Junio"); } if (obj.Julio.ToString() != "0") { result_query3.Add("Julio"); } if (obj.Agosto.ToString() != "0") { result_query3.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query3.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query3.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query3.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query3.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query3); break; case "mayo": var lst4 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query4 = new List<string>(); foreach (var obj in lst4) { if (obj.Junio.ToString() != "0") { result_query4.Add("Junio"); } if (obj.Julio.ToString() != "0") { result_query4.Add("Julio"); } if (obj.Agosto.ToString() != "0") { result_query4.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query4.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query4.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query4.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query4.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query4); break; case "junio": var lst5 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query5 = new List<string>(); foreach (var obj in lst5) { if (obj.Julio.ToString() != "0") { result_query5.Add("Julio"); } if (obj.Agosto.ToString() != "0") { result_query5.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query5.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query5.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query5.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query5.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query5); break; case "julio": var lst6 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query6 = new List<string>(); foreach (var obj in lst6) { if (obj.Agosto.ToString() != "0") { result_query6.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { result_query6.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query6.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query6.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query6.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query6); break; case "agosto": var lst7 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query7 = new List<string>(); foreach (var obj in lst7) { if (obj.Septiembre.ToString() != "0") { result_query7.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { result_query7.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query7.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query7.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query7); break; case "septiembre": var lst8 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query8 = new List<string>(); foreach (var obj in lst8) { if (obj.Octubre.ToString() != "0") { result_query8.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { result_query8.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query8.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query8); break; case "octubre": var lst9 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> result_query9 = new List<string>(); foreach (var obj in lst9) { if (obj.Noviembre.ToString() != "0") { result_query9.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { result_query9.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query9); break; case "noviembre": var lst10 = from s in db.INPC where s.Id == id_periodo_select_anio select new { Diciembre = s.diciembre }; List<string> result_query10 = new List<string>(); foreach (var obj in lst10) { if (obj.Diciembre.ToString() != "0") { result_query10.Add("Diciembre"); } } json = JsonConvert.SerializeObject(result_query10); break; case "diciembre": List<string> result_query11 = new List<string>(); result_query11.Add("No es posible"); json = JsonConvert.SerializeObject(result_query11); break; default: Console.WriteLine("Caso por default"); break; } } else { var Result = from s in db.INPC where s.Id == id_periodo_select_anio2 select new { Enero = s.enero, Febrero = s.febrero, Marzo = s.marzo, Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre }; List<string> R1 = new List<string>(); foreach (var obj in Result) { if (obj.Enero.ToString() != "0") { R1.Add("Enero"); } if (obj.Febrero.ToString() != "0") { R1.Add("Febrero"); } if (obj.Marzo.ToString() != "0") { R1.Add("Marzo"); } if (obj.Abril.ToString() != "0") { R1.Add("Abril"); } if (obj.Mayo.ToString() != "0") { R1.Add("Mayo"); } if (obj.Junio.ToString() != "0") { R1.Add("Junio"); } if (obj.Julio.ToString() != "0") { R1.Add("Julio"); } if (obj.Agosto.ToString() != "0") { R1.Add("Agosto"); } if (obj.Septiembre.ToString() != "0") { R1.Add("Septiembre"); } if (obj.Octubre.ToString() != "0") { R1.Add("Octubre"); } if (obj.Noviembre.ToString() != "0") { R1.Add("Noviembre"); } if (obj.Diciembre.ToString() != "0") { R1.Add("Diciembre"); } } json = JsonConvert.SerializeObject(R1); } return json; } [WebMethod] public static object calcular_inflacion(string id_inpc_inicial, string id_inpc_inicial_mes, string id_inpc_final, string id_inpc_final_mes) { var json = ""; var db = new Entidades(); List<string> R1 = new List<string>(); var Result = from s in db.INPC where s.Id == id_inpc_inicial select new { Enero = s.enero, Febrero = s.febrero, Marzo = s.marzo, Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre, Anio=s.anio }; double inpcinicial=0; int anio_inicial = 0; //NUM DE MES inicial PARA CALCULAR EL PERIODO int mesI = 0; foreach (var obj in Result) { anio_inicial = (int)obj.Anio; R1.Add(anio_inicial.ToString()); switch (id_inpc_inicial_mes) { case "enero": inpcinicial = (double) obj.Enero; R1.Add("Enero"); mesI = 1;//ADDED break; case "febrero": inpcinicial = (double) obj.Febrero; R1.Add("Febrero"); mesI = 2;//ADDED break; case "marzo": inpcinicial = (double)obj.Marzo; R1.Add("Marzo"); mesI = 3;//ADDED break; case "abril": inpcinicial = (double)obj.Abril; R1.Add("Abril"); mesI = 4;//ADDED break; case "mayo": inpcinicial = (double)obj.Mayo; R1.Add("Mayo"); mesI = 5;//ADDED break; case "junio": inpcinicial = (double)obj.Junio; R1.Add("Junio"); mesI = 6;//ADDED break; case "julio": inpcinicial = (double)obj.Julio; R1.Add("Julio"); mesI = 7;//ADDED break; case "agosto": inpcinicial = (double)obj.Agosto; R1.Add("Agosto"); mesI = 8;//ADDED break; case "septiembre": inpcinicial = (double)obj.Septiembre; R1.Add("Septiembre"); mesI = 9;//ADDED break; case "octubre": inpcinicial = (double)obj.Octubre; R1.Add("Octubre"); mesI = 10;//ADDED break; case "noviembre": inpcinicial = (double)obj.Noviembre; R1.Add("Noviembre"); mesI = 11;//ADDED break; case "diciembre": inpcinicial = (double)obj.Diciembre; R1.Add("Diciembre"); mesI = 12;//ADDED break; } } var Result2 = from s in db.INPC where s.Id == id_inpc_final select new { Enero = s.enero, Febrero = s.febrero, Marzo = s.marzo, Abril = s.abril, Mayo = s.mayo, Junio = s.junio, Julio = s.julio, Agosto = s.agosto, Septiembre = s.septiembre, Octubre = s.octubre, Noviembre = s.noviembre, Diciembre = s.diciembre, Anio = s.anio }; double inpcfinal=0; int anio_final = 0; //NUM DE MES final PARA CALCULAR EL PERIODO int mesF = 0; foreach (var obj in Result2) { anio_final = (int)obj.Anio; R1.Add(anio_final.ToString()); switch (id_inpc_final_mes) { case "enero": inpcfinal = (double)obj.Enero; R1.Add("Enero"); mesF = 1;//ADDED break; case "febrero": inpcfinal = (double)obj.Febrero; R1.Add("Febrero"); mesF = 2;//ADDED break; case "marzo": inpcfinal = (double)obj.Marzo; R1.Add("Marzo"); mesF = 3;//ADDED break; case "abril": inpcfinal = (double)obj.Abril; R1.Add("Abril"); mesF = 4;//ADDED break; case "mayo": inpcfinal = (double)obj.Mayo; R1.Add("Mayo"); mesF = 5;//ADDED break; case "junio": inpcfinal = (double)obj.Junio; R1.Add("Junio"); mesF = 6;//ADDED break; case "julio": inpcfinal = (double)obj.Julio; R1.Add("Julio"); mesF = 7;//ADDED break; case "agosto": inpcfinal = (double)obj.Agosto; R1.Add("Agosto"); mesF = 8;//ADDED break; case "septiembre": inpcfinal = (double)obj.Septiembre; R1.Add("Septiembre"); mesF = 9;//ADDED break; case "octubre": inpcfinal = (double)obj.Octubre; R1.Add("Noviembre"); mesF = 10;//ADDED break; case "noviembre": inpcfinal = (double)obj.Noviembre; R1.Add("Noviembre"); mesF = 11;//ADDED break; case "diciembre": inpcfinal = (double)obj.Diciembre; R1.Add("Diciembre"); mesF = 12;//ADDED break; } } double TasaInfla = (((inpcfinal - inpcinicial) / inpcinicial) * 100); //resultado de inflacion promedio mensual int per = ((anio_final - anio_inicial)*12)+(mesF- mesI); double div = (inpcfinal / inpcinicial); double TasaPromMen = ((Math.Pow(div, (1.0 / per))) - 1) * 100; R1.Add(TasaInfla.ToString()); //RESULTADOS DE LA CALCULADORA //tasa promedio mensual R1.Add(TasaPromMen.ToString()); json = JsonConvert.SerializeObject(R1); return json; } /***************/ [WebMethod] public static string cargar_proyectos() { var db = new Entidades(); var httpContext = HttpContext.Current; /***Get the user id**/ string id_user = httpContext.User.Identity.GetUserId(); var consulta = db.Proyecto.Where(Proyect => Proyect.ID_Usuario == id_user && Proyect.Activo == true);//consulta los proyectos del usuario List<string> item = new List<string>(); string option; //option = "<option value='0'>Seleccione</option>"; //item.Add(option); foreach (Proyecto Proyect in consulta) { option = "<option value='" + Proyect.ID_Proyecto + "'>" + Proyect.Nombre_Proyecto + "</option>"; if (System.Web.HttpContext.Current.Session["ID_Proyecto"] != null) { string idProyecto = (string)System.Web.HttpContext.Current.Session["ID_Proyecto"]; if (idProyecto == Proyect.ID_Proyecto) { option = "<option value='" + Proyect.ID_Proyecto + "'>" + Proyect.Nombre_Proyecto + "</option>"; } } item.Add(option); } var json = JsonConvert.SerializeObject(item); return json; } [WebMethod] public static string guardar_inflacion(string Periodo, string[] Proyectos, decimal[] Inflaciones) { var retur = "FAIL"; bool ban = false; // GUARDAMOS A LA BASE DE DATOS for (int i = 0; i < Proyectos.Length; i++) { string id_proyecto = Proyectos[i]; var db = new Entidades(); //verificamos si el proyecto ya existe en la tabbla inflacion var projINflacion = db.Inflacion.Where(Inflacion => Inflacion.ID_Proyecto == id_proyecto); if (projINflacion.Count() > 0) { ban = true; } else { ban = false; } db.SaveChanges(); db = new Entidades(); for (int x = 0; x < Inflaciones.Length; x++) { //Verificamos que el Periodo no este calculado var query = db.Inflacion.Where(Infla => Infla.ID_Proyecto == id_proyecto && Infla.Periodo == Periodo ); if (query.Count() > 0) { retur = "OK"; } else { string Tipo = ""; if (x == 0) Tipo = "Inf_acumulada"; else Tipo = "Inf_prom_mensual"; Inflacion inflacion = new Inflacion(); string id_inflacion = System.Guid.NewGuid().ToString("D"); inflacion.ID_Inflacion = id_inflacion; inflacion.ID_Proyecto = id_proyecto; inflacion.Valor_Inflacion = Inflaciones[x]; inflacion.Tipo = Tipo; inflacion.Periodo = Periodo; System.Diagnostics.Debug.WriteLine("Inflaciones[x]->" + inflacion.Valor_Inflacion); db.Inflacion.Add(inflacion); } } db.SaveChanges(); if (ban == false) { agregar_avance(id_proyecto); } retur = "OK"; } retur = "OK"; return retur; } public static string agregar_avance(string id_proyecto) { try { var db = new Entidades(); var projAvance = db.Proyecto.Where(Proyect => Proyect.ID_Proyecto == id_proyecto).Single(); //modificamos el campo Activo projAvance.Avance = projAvance.Avance + 1; db.SaveChanges(); return "succes"; } catch (ArgumentNullException e) { Console.WriteLine("{0} First exception caught.", e); return "fail"; } } }
using System; namespace RestLogger.Tests.IntegrationTests.DI { internal interface IDependencyResolver : IDisposable { T Resolve<T>(); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Uintra.Features.Tagging.UserTags.Models; namespace Uintra.Features.Tagging.UserTags.Services { public interface IUserTagService { IEnumerable<UserTag> Get(Guid entityId); void Replace(Guid entityId, IEnumerable<Guid> tagIds); void DeleteAllFor(Guid entityId); Task<IEnumerable<UserTag>> GetAsync(Guid entityId); Task ReplaceAsync(Guid entityId, IEnumerable<Guid> tagIds); Task DeleteAllForAsync(Guid entityId); } }
using System.IO; using Newtonsoft.Json; namespace Notificator { public class Config { public string AppToken = ""; public string UserToken = ""; public string Smtp = ""; public string SmtpPort = ""; public string YourEmail = ""; public string ServerMail = ""; public string ServerMailPassword = ""; public string MailSubject = ""; public void Write(string path) { File.WriteAllText(path, JsonConvert.SerializeObject(this, Formatting.Indented)); } public static Config Read(string path) { return File.Exists(path) ? JsonConvert.DeserializeObject<Config>(File.ReadAllText(path)) : new Config(); } } }
using System.Collections.Generic; using Cradiator.Audio; using Cradiator.Config; using Cradiator.Model; using FakeItEasy; using NUnit.Framework; namespace Cradiator.Tests.Audio { [TestFixture] public class DiscJockey_Tests { IAudioPlayer _audioPlayer; DiscJockey _discJockey; ConfigSettings _configSettings; List<ProjectStatus> _projectList1Success; List<ProjectStatus> _projectList1Failure; List<ProjectStatus> _projectList2BothSuccess; List<ProjectStatus> _projectList2BothFailure; SpeechMaker _speechMaker; IBuildBuster _buildBuster; const string BrokenSound = "broken.wav"; const string FixedSound = "fixed.wav"; [SetUp] public void SetUp() { _audioPlayer = A.Fake<IAudioPlayer>(); _buildBuster = A.Fake<IBuildBuster>(); _configSettings = new ConfigSettings { BrokenBuildSound = BrokenSound, FixedBuildSound = FixedSound, PlaySounds = true }; _speechMaker = new SpeechMaker(_configSettings, new SpeechTextParser(_buildBuster)); _discJockey = new DiscJockey(_configSettings, _audioPlayer, _speechMaker); _projectList1Success = new List<ProjectStatus> { new ProjectStatus("bla") { LastBuildStatus = ProjectStatus.SUCCESS } }; _projectList1Failure = new List<ProjectStatus> { new ProjectStatus("bla") { LastBuildStatus = ProjectStatus.FAILURE } }; _projectList2BothSuccess = new List<ProjectStatus> { new ProjectStatus("bla") {LastBuildStatus = ProjectStatus.SUCCESS}, new ProjectStatus("bla2") {LastBuildStatus = ProjectStatus.SUCCESS} }; _projectList2BothFailure = new List<ProjectStatus> { new ProjectStatus("bla") {LastBuildStatus = ProjectStatus.FAILURE}, new ProjectStatus("bla2") {LastBuildStatus = ProjectStatus.FAILURE} }; } [Test] public void CanPlay_BuildStatus_If_SuccessThenFailure() { _discJockey.PlaySounds(_projectList1Success); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); _discJockey.PlaySounds(_projectList1Failure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustHaveHappened(); } [Test] public void DoesNotPlay_BuildStatus_If_2_FailuresInARow() { _discJockey.PlaySounds(_projectList1Failure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); _discJockey.PlaySounds(_projectList1Failure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); } [Test] public void CanPlay_BuildStatus_If_SuccessThenFail_WithMultipleStatus() { _discJockey.PlaySounds(_projectList2BothSuccess); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); _discJockey.PlaySounds(_projectList2BothFailure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustHaveHappened(); } [Test] public void DoesNotPlay_BuildStatus_If_OnlyFailures_WithMultipleStatus() { _discJockey.PlaySounds(_projectList2BothFailure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); _discJockey.PlaySounds(_projectList2BothFailure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); } [Test] public void CanPlaySound_ThenUpdateConfig_ThenNotPlaySound() { _discJockey = new DiscJockey(new ConfigSettings { PlaySounds = false }, _audioPlayer, _speechMaker); _discJockey.PlaySounds(_projectList1Success); _discJockey.PlaySounds(_projectList1Failure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustNotHaveHappened(); _discJockey.ConfigUpdated(new ConfigSettings { PlaySounds = true, BrokenBuildSound = BrokenSound}); _discJockey.PlaySounds(_projectList1Success); _discJockey.PlaySounds(_projectList1Failure); A.CallTo(() => _audioPlayer.Play(BrokenSound)).MustHaveHappened(); } [Test] public void CanPlay_Success_If_FailureThenSuccess() { _discJockey.PlaySounds(_projectList1Failure); A.CallTo(() => _audioPlayer.Play(FixedSound)).MustNotHaveHappened(); _discJockey.PlaySounds(_projectList1Success); A.CallTo(() => _audioPlayer.Play(FixedSound)).MustHaveHappened(); } [Test] public void DoesNotPlay_Success_If_2_SuccessesInARow() { _discJockey.PlaySounds(_projectList1Success); A.CallTo(() => _audioPlayer.Play(FixedSound)).MustNotHaveHappened(); _discJockey.PlaySounds(_projectList1Success); A.CallTo(() => _audioPlayer.Play(FixedSound)).MustNotHaveHappened(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.RoleAuthorize { public class MenuBusiness : Category.CategoryBusiness<MenuBusiness, Menu> { public static MenuBusiness Instance { get { return new MenuBusiness(); } } protected override DBExtend dbHelper { get { return GetDbHelper<MenuBusiness>(); } } /// <summary> /// 返回菜单码 /// </summary> /// <param name="systemTypeId"></param> /// <returns></returns> public string GetMenuCodeByUrl(int systemTypeId) { var item = GetMenuByUrl(systemTypeId); if (item == null) return ""; return item.SequenceCode; } public Menu GetMenuByUrl(int systemTypeId) { string url = System.Web.HttpContext.Current.Request.Path.ToLower(); var allCache = GetAllCache(systemTypeId); var items = allCache.Where(b => b.DataType == systemTypeId && !string.IsNullOrEmpty(b.Url) && url==b.Url.ToLower() && b.ParentCode != ""); return items.FirstOrDefault(); } /// <summary> /// 查询用户的菜单 /// </summary> /// <param name="systemTypeId"></param> /// <param name="userId"></param> /// <param name="userRole"></param> /// <returns></returns> public List<Menu> GetUserMenu(int systemTypeId,int userId, int userRole) { List<Menu> menus = new List<Menu>(); var controls = AccessControlBusiness.Instance.QueryList(b => b.Role == userRole || (b.RoleType == RoleType.用户 && b.Role == userId) && b.SystemTypeId == systemTypeId); var allCache = GetAllCache(systemTypeId); menus.AddRange(allCache.Where(b => b.SequenceCode.Length == 2)); foreach (var item in controls) { Menu m = Get(item.MenuCode, 0); if (m != null) { menus.Add(m); } } return menus.OrderBy(b=>b.SequenceCode).ToList() ; } static Dictionary<string, List<Menu>> userMenuCache = new Dictionary<string, List<Menu>>(); /// <summary> /// 移除用户菜单缓存 /// </summary> /// <param name="userId"></param> /// <param name="systemTypeId"></param> public void RemoveUserMenuCache(int userId, int systemTypeId) { string cacheKey = string.Format("menu_{0}_{1}", userId, systemTypeId); userMenuCache.Remove(cacheKey); } /// <summary> /// 获取用户菜单 /// 如果显示导航菜单,请判断ShowInNav /// </summary> /// <param name="userId"></param> /// <param name="systemTypeId"></param> /// <param name="fromCache"></param> /// <returns></returns> public List<Menu> GetUserMenu(int userId, int systemTypeId, bool fromCache = true) { string cacheKey = string.Format("menu_{0}_{1}", userId, systemTypeId); if (fromCache) { if (userMenuCache.ContainsKey(cacheKey)) { return userMenuCache[cacheKey]; } } var u = EmployeeBusiness.Instance.QueryItem(b => b.Id == userId); if (u == null) { throw new Exception("获取菜单出错,找不到指定的用户:" + userId); } var controls = AccessControlBusiness.Instance.QueryList(b => ((b.Role == userId && b.RoleType == RoleType.用户) || (b.Role == u.Role && b.RoleType == RoleType.角色)) && b.SystemTypeId == systemTypeId && b.Que == true); List<Menu> list = new List<Menu>(); var allCache = GetAllCache(systemTypeId); //list.AddRange(allCache.FindAll(b => b.SequenceCode.Length == 2)); foreach (var item in controls) { if (list.Find(b => b.SequenceCode==item.MenuCode) != null) { continue; } var m = Get(item.MenuCode, systemTypeId); if (m == null) continue; if (!m.Disable) { list.Add(m); var parent = list.Find(b => b.SequenceCode == m.ParentCode); if (parent == null) { list.Add(allCache.Where(b => b.SequenceCode == m.ParentCode).First()); } } } var list2 = list.OrderBy(b => b.SequenceCode).ToList(); if (!userMenuCache.ContainsKey(cacheKey)) { userMenuCache.Add(cacheKey, list2); } return list2; } /// <summary> /// 分组显示用户菜单 /// </summary> /// <param name="userId"></param> /// <param name="systemTypeId"></param> /// <returns></returns> public Dictionary<Menu, List<Menu>> GetUserMenuByGroup(int userId, int systemTypeId) { var menus = GetUserMenu(userId, systemTypeId); var dic = new Dictionary<Menu, List<Menu>>(); Menu lastMenu = null; foreach (var item in menus) { if (item.SequenceCode.Length == 2) { lastMenu = item; dic.Add(lastMenu, new List<CRL.RoleAuthorize.Menu>()); } else { if (lastMenu == null)//数据错误导致找不到之前菜单 { continue; } dic[lastMenu].Add(item); } } dic = dic.OrderByDescending(b => b.Key.Sort).ToDictionary(b => b.Key, c => c.Value.OrderByDescending(d => d.Sort).ToList()); return dic; } public List<Menu> GetFavMenus(int systemTypeId, int userId, int num = 5) { Dictionary<string, int> dic = GetFavMenuDic(systemTypeId, userId); List<Menu> menus = new List<Menu>(); foreach (var item in dic.Keys) { var menu = GetAllCache(systemTypeId).Where(b => b.SequenceCode == item).FirstOrDefault(); if (menu == null) continue; if (!menu.ShowInNav) { continue; } menu.Hit = dic[item]; menus.Add(menu); } return menus.OrderByDescending(b => b.Hit).Take(num).ToList(); } public void SaveFavMenus(Dictionary<string, int> dic, int systemTypeId, int userId) { string name = string.Format("{0}_{1}.txt", systemTypeId, userId); string folder = System.Web.HttpContext.Current.Server.MapPath("/log/userMenuCache/"); CoreHelper.EventLog.CreateFolder(folder); string fileName = folder + name; string str = ""; foreach (var key in dic.Keys) { str += string.Format("{0}:{1};", key, dic[key]); } System.IO.File.WriteAllText(fileName, str); } public Dictionary<string, int> GetFavMenuDic(int systemTypeId, int userId) { string name = string.Format("{0}_{1}.txt", systemTypeId, userId); string folder = System.Web.HttpContext.Current.Server.MapPath("/log/userMenuCache/"); string fileName = folder + name; string menus = ""; if (System.IO.File.Exists(fileName)) { menus = System.IO.File.ReadAllText(fileName); } string[] arry = menus.Split(';'); Dictionary<string, int> dic = new Dictionary<string, int>(); foreach (string s in arry) { if (s.Trim() == "") continue; string[] arry2 = s.Split(':'); if (arry2.Length < 2) continue; string menuCode = arry2[0]; int hit = Convert.ToInt32(arry2[1]); if (!dic.ContainsKey(menuCode)) { dic.Add(menuCode, hit); } } return dic; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Cdiscount.Alm.Sonar.Api.Wrapper.Core.QualityProfiles.Projects.Response { public class SonarQualityProfileProjects { /// <summary> /// Quality Profile projects /// </summary> [JsonProperty(PropertyName = "results")] public List<SonarProjet> QualityProfileProjects { get; set; } /// <summary> /// Ancestors of the quality profile /// </summary> [JsonProperty(PropertyName = "more")] public bool More { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace Hahn.ApplicatonProcess.December2020.Data.Repository { public interface IApplicantRepository { int InsertApplicant(Entities.Applicant applicant); Entities.Applicant GetApplicantByID(int applicantID); int UpdateApplicant(int applicantID, Entities.Applicant applicant); int DeleteApplicant(int applicantID); List<Entities.Applicant> GetApplicants(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Korzh.EasyQuery; using Ninject; namespace ApartmentApps.Data.DataSheet { public interface IDataSheet { } public interface IDataSheet<TModel> where TModel : class { IQueryState<TModel> Query(Query query = null); IDbSet<TModel> DbSet { get; } TViewModel Get<TViewModel>(string id) where TViewModel : class; TModel Get(string id); object StringToPrimaryKey(string id); void SaveChanges(); } public interface IFetcher<TModel> where TModel : class { IKernel Kernel { get; } IQueryable<TModel> FetchRaw(QueryState<TModel> queryState); IEnumerable<TViewModel> FetchRaw<TViewModel>(QueryState<TModel> queryState); QueryResult<TViewModel> Fetch<TViewModel>(QueryState<TModel> queryState) where TViewModel : class; QueryResult<TModel> Fetch(QueryState<TModel> queryState); } public interface IQueryState<TEntityModel> { IQueryState<TEntityModel> Search<TSearchEngine>(Func<TSearchEngine, IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper); IQueryState<TEntityModel> Order(Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper); IQueryState<TEntityModel> Navigate(Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper); IQueryState<TEntityModel> Filter(Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper); IQueryable<TEntityModel> Raw(); IEnumerable<TViewModel> Raw<TViewModel>(); QueryResult<TEntityModel> Get(); QueryResult<TViewModel> Get<TViewModel>() where TViewModel : class; } public class QueryState<TEntityModel> : IQueryState<TEntityModel> where TEntityModel : class { public IFetcher<TEntityModel> Fetcher { get; set; } public IQueryable<TEntityModel> InitialSet { get; set; } public Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> NavigationFilter { get; set; } public Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> CustomFilter { get; set; } public Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> SearchFilter { get; set; } public Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> OrderFilter { get; set; } public Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> ContextFilter { get; set; } public IQueryState<TEntityModel> Navigate(Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper) { NavigationFilter = mapper; return this; } public IQueryState<TEntityModel> Filter(Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper) { CustomFilter = mapper; return this; } public IQueryState<TEntityModel> Order(Func<IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper) { this.OrderFilter = mapper; return this; } public IQueryState<TEntityModel> Search<TSearchEngine>(Func<TSearchEngine, IQueryable<TEntityModel>, IQueryable<TEntityModel>> mapper) { SearchFilter = x => { if (!Fetcher.Kernel.CanResolve<TSearchEngine>()) throw new Exception("Search engine not found: " + typeof(TSearchEngine).Name); return mapper(Fetcher.Kernel.Get<TSearchEngine>(), x); }; return this; } public IQueryable<TEntityModel> Raw() { return this.Fetcher.FetchRaw(this); } public IEnumerable<TViewModel> Raw<TViewModel>() { return Fetcher.FetchRaw<TViewModel>(this); } public QueryResult<TEntityModel> Get() { return this.Fetcher.Fetch(this); } public QueryResult<TViewModel> Get<TViewModel>() where TViewModel : class { return this.Fetcher.Fetch<TViewModel>(this); } } public class QueryResult<T> { public int Total { get; set; } //total of all entities before navigation is applied public List<T> Result { get; set; } } public class Query { public Navigation Navigation { get; set; } public Order Order { get; set; } public Search Search { get; set; } } public class Navigation { public int Skip { get; set; } public int Take { get; set; } } public class Order { //Not yet implemented } public class Search { public string EngineId { get; set; } public List<FilterData> Filters { get; set; } } public class FilterData { public string FilterId { get; set; } public string JsonValue { get; set; } } public static class QuerystateExtensions { public static IQueryState<TModel> SkipTake<TModel>(this IQueryState<TModel> state, int skip, int take) { return state.Navigate(set => set.Skip(skip).Take(take)); } } }
using ClearBank.DeveloperTest.Types; namespace ClearBank.DeveloperTest.Services { public class AccountService : IAccountService { private readonly IAccountDataStore _dataStore; public AccountService( IDataStoreFactory dataStoreFactory, IAppConfiguration appConfiguration) { _dataStore = dataStoreFactory.CreateDataStore(appConfiguration.DataStoreType); } public Account GetAccount(string accountNumber) { return _dataStore.GetAccount(accountNumber); } public void UpdateAccount(Account account, decimal requestedAmount) { account.Deduct(requestedAmount); _dataStore.UpdateAccount(account); } } }
using eCommerceSE.Cliente; using eCommerceSE.Model; using System; using System.Configuration; using System.IO; using System.Web.UI; using System.Web.UI.WebControls; //using DocumentFormat.OpenXml.Drawing; namespace Enviosbase.Domiciliario { public partial class DomiciliarioEdit : System.Web.UI.Page { string llave = ConfigurationManager.AppSettings["Usuario"].ToString(); protected void Page_Load(object sender, EventArgs e) { if (Session["usuario"] == null) { Response.Redirect("/Login.aspx"); } if (!Page.IsPostBack) { if (Request.QueryString["Estado"] == "1") { CambioEstado(int.Parse(Request.QueryString["Id"].ToString())); } if (Request.QueryString["Notificacion"] == "1") { EnviarUsuarioContraseña(int.Parse(Request.QueryString["Id"].ToString())); } cbIdPais.DataSource = new PaisCliente(llave).GetAll(); cbIdPais.DataTextField = "Nombre"; cbIdPais.DataValueField = "Id"; cbIdPais.DataBind(); cbIdPais.Items.Insert(0, new ListItem("[Seleccione]", "")); cbIdDepto.Items.Insert(0, new ListItem("[Seleccione]", "0")); cbIdMunicipio.Items.Insert(0, new ListItem("[Seleccione]", "0")); cbIdTipoVehiculo.DataSource = new TipoVehiculoCliente(llave).GetAll(); cbIdTipoVehiculo.DataTextField = "Nombre"; cbIdTipoVehiculo.DataValueField = "Id"; cbIdTipoVehiculo.DataBind(); cbIdTipoVehiculo.Items.Insert(0, new ListItem("[Seleccione]", "")); cbIdMarca.DataSource = new MarcaCliente(llave).GetAll(); cbIdMarca.DataTextField = "Nombre"; cbIdMarca.DataValueField = "Id"; cbIdMarca.DataBind(); cbIdMarca.Items.Insert(0, new ListItem("[Seleccione]", "")); if (Request.QueryString["Id"] != null) { int id = int.Parse(Request.QueryString["Id"]); DomiciliarioModel obj = new DomiciliarioCliente(llave).GetById(id); lbId.Text = obj.Id.ToString(); txtNombre.Text = obj.Nombre; txtDocumento.Text = obj.Documento; cbIdPais.SelectedValue = obj.IdPais.ToString(); cbIdPais_SelectedIndexChanged(cbIdPais, EventArgs.Empty); cbIdDepto.SelectedValue = obj.IdDepto.ToString(); cbIdDepto_SelectedIndexChanged(cbIdDepto, EventArgs.Empty); cbIdMunicipio.SelectedValue = obj.IdMunicipio.ToString(); txtDireccion.Text = obj.Direccion; txtTelefono.Text = obj.Telefono; txtCelular.Text = obj.Celular; cbIdTipoVehiculo.SelectedValue = obj.IdTipoVehiculo.ToString(); cbIdMarca.SelectedValue = obj.IdMarca.ToString(); txtModelo.Text = obj.Modelo; txtPlaca.Text = obj.Placa; txtCorreo.Value = obj.Correo; hdEstado.Value = obj.Estado.ToString(); hdnFileDoc.Value = obj.ImagenDocumento.ToString(); hdnFileLic.Value = obj.ImagenPase.ToString(); hdnFileSoat.Value = obj.ImagenSoat.ToString(); hdnFileTar.Value = obj.ImagenTarjetaPropiedad.ToString(); hdnFoto.Value = obj.Foto.ToString(); } else { hdEstado.Value = true.ToString(); } if (Request.QueryString["View"] == "0") { Business.Utils.DisableForm(Controls); btnCancel.Enabled = true; } } } protected void btnSave_Click(object sender, EventArgs e) { try { DomiciliarioModel obj; DomiciliarioCliente business = new DomiciliarioCliente(llave); if (Request.QueryString["Id"] != null) { obj = new DomiciliarioCliente(llave).GetById(int.Parse(Request.QueryString["Id"].ToString())); } else { obj = new DomiciliarioModel(); } string hash = ""; string filePath = ""; string filePath1 = ""; string filePath2 = ""; string filePath3 = ""; string filePath4 = ""; string rutaArchivo = ""; string rutaArchivo1 = ""; string rutaArchivo2 = ""; string rutaArchivo3 = ""; string rutaArchivo4 = ""; obj.Nombre = txtNombre.Text; obj.Documento = txtDocumento.Text; obj.IdPais = int.Parse(cbIdPais.SelectedValue); obj.IdDepto = int.Parse(cbIdDepto.SelectedValue); obj.IdMunicipio = int.Parse(cbIdMunicipio.SelectedValue); obj.Direccion = txtDireccion.Text; obj.Telefono = txtTelefono.Text; obj.Celular = txtCelular.Text; obj.IdTipoVehiculo = int.Parse(cbIdTipoVehiculo.SelectedValue); obj.IdMarca = int.Parse(cbIdMarca.SelectedValue); obj.Modelo = txtModelo.Text; obj.Placa = txtPlaca.Text; obj.UserLogin = txtDocumento.Text; obj.Correo = txtCorreo.Value; obj.Estado = bool.Parse(hdEstado.Value); obj.FechaRegistro = DateTime.Now; if (fnArchivoFoto.HasFile) { if (validarTamaño(fnArchivoFoto.FileBytes.Length)) { filePath = "/ImagenesDomiciliario/" + obj.Documento + "/" + fnArchivoFoto.FileName; string rutaInterna = Server.MapPath("/Archivos" + filePath); if (!Directory.Exists(System.IO.Path.GetDirectoryName(rutaInterna))) Directory.CreateDirectory(Path.GetDirectoryName(rutaInterna)); fnArchivoFoto.SaveAs(rutaInterna); rutaArchivo = ConfigurationManager.AppSettings["RutaArchivos"].ToString() + filePath; } else { ltScripts.Text = Business.Utils.MessageBox("Atención", "El tamaño de la foto del domiciliario supera los " + System.Configuration.ConfigurationManager.AppSettings["tamañoArchivosReal"].ToString() + " kb", null, "error"); return; } } else { rutaArchivo = hdnFoto.Value; } if (fnArchivoDoc.HasFile) { if (validarTamaño(fnArchivoDoc.FileBytes.Length)) { filePath1 = "/ImagenesDomiciliario/" + obj.Documento + "/" + fnArchivoDoc.FileName; string rutaInterna = Server.MapPath("/Archivos" + filePath1); if (!Directory.Exists(Path.GetDirectoryName(rutaInterna))) Directory.CreateDirectory(Path.GetDirectoryName(rutaInterna)); fnArchivoDoc.SaveAs(rutaInterna); rutaArchivo1 = ConfigurationManager.AppSettings["RutaArchivos"].ToString() + filePath1; } else { ltScripts.Text = Business.Utils.MessageBox("Atención", "El tamaño de la foto del documento supera los " + System.Configuration.ConfigurationManager.AppSettings["tamañoArchivosReal"].ToString() + " kb", null, "error"); return; } } else { rutaArchivo1 = hdnFileDoc.Value; } if (fnArchivoPase.HasFile) { if (validarTamaño(fnArchivoPase.FileBytes.Length)) { filePath2 = "/ImagenesDomiciliario/" + obj.Documento + "/" + fnArchivoPase.FileName; string rutaInterna = Server.MapPath("/Archivos" + filePath2); if (!Directory.Exists(Path.GetDirectoryName(rutaInterna))) Directory.CreateDirectory(Path.GetDirectoryName(rutaInterna)); fnArchivoPase.SaveAs(rutaInterna); rutaArchivo2 = ConfigurationManager.AppSettings["RutaArchivos"].ToString() + filePath2; } else { ltScripts.Text = Business.Utils.MessageBox("Atención", "El tamaño de la foto de la licencia de conducción supera los " + System.Configuration.ConfigurationManager.AppSettings["tamañoArchivosReal"].ToString() + " kb", null, "error"); return; } } else { rutaArchivo2 = hdnFileLic.Value; } if (fnArchivoSoat.HasFile) { if (validarTamaño(fnArchivoSoat.FileBytes.Length)) { filePath3 = "/ImagenesDomiciliario/" + obj.Documento + "/" + fnArchivoSoat.FileName; string rutaInterna = Server.MapPath("/Archivos" + filePath3); if (!Directory.Exists(Path.GetDirectoryName(rutaInterna))) Directory.CreateDirectory(Path.GetDirectoryName(rutaInterna)); fnArchivoSoat.SaveAs(rutaInterna); rutaArchivo3 = ConfigurationManager.AppSettings["RutaArchivos"].ToString() + filePath3; } else { ltScripts.Text = Business.Utils.MessageBox("Atención", "El tamaño de la foto del SOAT supera los " + System.Configuration.ConfigurationManager.AppSettings["tamañoArchivosReal"].ToString() + " kb", null, "error"); return; } } else { rutaArchivo3 = hdnFileSoat.Value; } if (fnArchivoTarjeta.HasFile) { if (validarTamaño(fnArchivoTarjeta.FileBytes.Length)) { filePath4 = "/ImagenesDomiciliario/" + obj.Documento + "/" + fnArchivoTarjeta.FileName; string rutaInterna = Server.MapPath("/Archivos" + filePath4); if (!Directory.Exists(Path.GetDirectoryName(rutaInterna))) Directory.CreateDirectory(Path.GetDirectoryName(rutaInterna)); fnArchivoTarjeta.SaveAs(rutaInterna); rutaArchivo4 = ConfigurationManager.AppSettings["RutaArchivos"].ToString() + filePath4; } else { ltScripts.Text = Business.Utils.MessageBox("Atención", "El tamaño de la foto de la tarjeta de propiedad supera los " + System.Configuration.ConfigurationManager.AppSettings["tamañoArchivosReal"].ToString() + " kb", null, "error"); return; } } else { rutaArchivo4 = hdnFileTar.Value; } obj.ImagenDocumento = rutaArchivo1; obj.ImagenPase = rutaArchivo2; obj.ImagenSoat = rutaArchivo3; obj.ImagenTarjetaPropiedad = rutaArchivo4; obj.Foto = rutaArchivo; // obj.IdUsuarioRegistro = int.Parse(this.txtIdUsuarioRegistro.Text); if (Request.QueryString["Id"] != null) { obj.Id = int.Parse(Request.QueryString["Id"]); business.Update(obj); } else { int longitud = 7; Guid miGuid = Guid.NewGuid(); string token = miGuid.ToString().Replace("-", string.Empty).Substring(0, longitud); hash = RationalSWUtils.Criptography.CreateMD5(token); obj.PasswordLogin = hash; obj = business.Create(obj); if (obj.Id == 0) { ltScripts.Text = Business.Utils.MessageBox("Atención", "Hay un domiciliario creado con la misma información, por favor verifique la información e intente nuevamente", null, "error"); return; } new Business.EmailBussines().SendMailCreateUserDom(txtDocumento.Text, token, obj.Nombre, txtCorreo.Value); } ltScripts.Text = Business.Utils.MessageBox("Atención", "El registro ha sido guardado exitósamente", "DomiciliarioList.aspx", "success"); } catch (Exception ex) { ltScripts.Text = Business.Utils.MessageBox("Atención", "No pudo ser guardado el registro, por favor verifique su información e intente nuevamente", null, "error"); } } public bool validarTamaño(int tamaño) { if (tamaño > int.Parse(System.Configuration.ConfigurationManager.AppSettings["tamañoArchivos"].ToString())) return false; else return true; } protected void btnCancel_Click(object sender, EventArgs e) { Response.Redirect("DomiciliarioList.aspx"); } protected void cbIdPais_SelectedIndexChanged(object sender, EventArgs e) { cbIdDepto.DataSource = new DepartamentoCliente(llave).GetByPais(int.Parse(cbIdPais.SelectedValue)); cbIdDepto.DataTextField = "Nombre"; cbIdDepto.DataValueField = "Id"; cbIdDepto.DataBind(); cbIdDepto.Items.Insert(0, new ListItem("[Seleccione]", "0")); cbIdMunicipio.DataSource = null; cbIdMunicipio.Items.Clear(); cbIdMunicipio.Items.Insert(0, new ListItem("[Seleccione]", "0")); } protected void cbIdDepto_SelectedIndexChanged(object sender, EventArgs e) { cbIdMunicipio.DataSource = new MunicipioCliente(llave).GetByDepartamento(int.Parse(cbIdDepto.SelectedValue)); cbIdMunicipio.DataTextField = "Nombre"; cbIdMunicipio.DataValueField = "Id"; cbIdMunicipio.DataBind(); cbIdMunicipio.Items.Insert(0, new ListItem("[Seleccione]", "0")); } public void EnviarUsuarioContraseña(int idDomiciliario) { DomiciliarioCliente usuarioBusiness = new DomiciliarioCliente(llave); DomiciliarioModel model = new DomiciliarioCliente(llave).GetById(idDomiciliario); int longitud = 7; Guid miGuid = Guid.NewGuid(); string token = miGuid.ToString().Replace("-", string.Empty).Substring(0, longitud); model.PasswordLogin = RationalSWUtils.Criptography.CreateMD5(token); usuarioBusiness.Update(model); new Business.EmailBussines().SendMailRememberUserDom(model.Documento, token, model.Nombre, model.Correo); ltScripts.Text = Business.Utils.MessageBox("Atención", "Se ha enviado el correo de notificación a " + model.Correo, "DomiciliarioList.aspx", "success"); } public void CambioEstado(int id) { new DomiciliarioCliente(llave).CambiarEstadoDomiciliario(id); ltScripts.Text = Business.Utils.MessageBox("Atención", "El cambio de estado se realizo exitósamente", "DomiciliarioList.aspx", "success"); } } }
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using OrchardCore.ContentManagement; using OrchardCore.ContentManagement.Display; using OrchardCore.ContentManagement.Records; using OrchardCore.DisplayManagement.ModelBinding; using StockAndShare.OrchardCoreDemo.Models; using StockAndShare.OrchardCoreDemo.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using YesSql; namespace StockAndShare.OrchardCoreDemo.Controllers { public class StockController : Controller { private readonly ISession _session; private readonly IContentManager _contentManager; private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly IUpdateModelAccessor _updateModelAccessor; public StockController(ISession session, IContentManager contentManager, IContentItemDisplayManager contentItemDisplayManager, IUpdateModelAccessor updateModelAccessor) { _session = session; _contentManager = contentManager; _contentItemDisplayManager = contentItemDisplayManager; _updateModelAccessor = updateModelAccessor; } [HttpGet, ActionName("Records")] public async Task<IActionResult> Records() { return Ok("HEy"); } [HttpPost, ActionName("Post")] public async Task<IActionResult> Post() { return Ok("HEy"); } public async Task<ActionResult> SaveTop10() { List<StockViewModel> stocks = new List<StockViewModel>(); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("https://613645c28700c50017ef550c.mockapi.io/stocks")) { string apiResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(apiResponse); stocks = JsonConvert.DeserializeObject<List<StockViewModel>>(apiResponse); } } var tobeDeleted = await _session .Query<StockViewModel>() .ListAsync(); foreach (var item in tobeDeleted) { _session.Delete(item); } //List<StockViewModel> result = new List<StockViewModel>(); for (int i = 0; i < 10; i++) { if (i < stocks.Count) { _session.Save(stocks[i]); } } return RedirectToAction("Saved"); } public async Task<ActionResult> Saved() { var stocks = await _session .Query<StockViewModel>() .ListAsync(); return View(stocks); } public async Task<ActionResult> Index() { /*var stocks = await _session .Query<ContentItem, ContentItemIndex>(index => index.ContentType == "StockPage") .ListAsync();*/ List<StockViewModel> stocks = new List<StockViewModel>(); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("https://613645c28700c50017ef550c.mockapi.io/stocks")) { string apiResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(apiResponse); stocks = JsonConvert.DeserializeObject<List<StockViewModel>>(apiResponse); } } /* var shapes = await Task.WhenAll(stocks.Select(async stock => { // When you retrieve content items via ISession then you also need to run LoadAsync() on them to // initialize everything. var st = new StockPart() { CompanyName = stock.CompanyName, CurrentStockPrice = stock.CurrentStockPrice, RecordedDate = stock.RecordedDate, }; var sd = await _contentManager.NewAsync(nameof(StockPart)); var s = sd.As<StockPart>(); s.As<StockPart>().CompanyName = stock.CompanyName; s.As<StockPart>().CurrentStockPrice = stock.CurrentStockPrice; s.As<StockPart>().RecordedDate = stock.RecordedDate; s.As<StockPart>().Show = true; await _contentManager.LoadAsync(); return await _contentItemDisplayManager.BuildDisplayAsync(s, _updateModelAccessor.ModelUpdater, "Detail"); }));*/ //return View(shapes); return View(stocks); } public async Task<ActionResult> List() { var stocks = await _session .Query<ContentItem, ContentItemIndex>(index => index.ContentType == "StockPage") .ListAsync(); /* foreach (var stock in stocks) { await _contentManager.LoadAsync(stock); } return string.Join(',', stocks.Select(stock => stock.As<StockPart>().CompanyName)); */ var shapes = await Task.WhenAll(stocks.Select(async stock => { // When you retrieve content items via ISession then you also need to run LoadAsync() on them to // initialize everything. await _contentManager.LoadAsync(stock); return await _contentItemDisplayManager.BuildDisplayAsync(stock, _updateModelAccessor.ModelUpdater, "Detail"); })); // Now assuming that you've already created a few Person content items on the dashboard and some of these // persons are more than 30 years old then this query will contain items to display. // NEXT STATION: Go to Views/PersonList/OlderThan30.cshtml and then come back here please. return View(shapes); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Reflection; using System.ServiceModel; using Phenix.Core.Log; using Phenix.Core.Mapping; using Phenix.Core.Net; using Phenix.Services.Contract; namespace Phenix.Services.Client.Library.Wcf { internal class PermanentLogProxy : IPermanentLog { #region 方法 private static ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> GetChannelFactory() { return new ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog>(WcfHelper.CreateBinding(), new EndpointAddress(WcfHelper.CreateUrl(NetConfig.ServicesAddress, ServicesInfo.PERMANENT_LOG_URI))); } #region IPermanentLog 成员 public void Save(string userNumber, string typeName, string message, Exception error) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); try { channel.Save(userNumber, typeName, message, error); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } break; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public IList<EventLogInfo> Fetch(string userNumber, string typeName, DateTime startTime, DateTime finishTime) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); object result = null; try { result = channel.Fetch(userNumber, typeName, startTime, finishTime); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } Exception exception = result as Exception; if (exception != null) throw exception; return (IList<EventLogInfo>)result; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public void Clear(string userNumber, string typeName, DateTime startTime, DateTime finishTime) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); try { channel.Clear(userNumber, typeName, startTime, finishTime); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } break; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public void SaveExecuteAction(string userNumber, string typeName, string primaryKey, ExecuteAction action, string log) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); try { channel.SaveExecuteAction(userNumber, typeName, primaryKey, action, log); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } break; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public IList<string> FetchExecuteAction(string typeName, string primaryKey) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); object result = null; try { result = channel.FetchExecuteAction(typeName, primaryKey); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } Exception exception = result as Exception; if (exception != null) throw exception; return (IList<string>)result; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public IList<string> FetchExecuteAction(string userNumber, string typeName, ExecuteAction action, DateTime startTime, DateTime finishTime) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); object result = null; try { result = channel.FetchUserExecuteAction(userNumber, typeName, action, startTime, finishTime); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } Exception exception = result as Exception; if (exception != null) throw exception; return (IList<string>)result; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public void ClearExecuteAction(string userNumber, string typeName, ExecuteAction action, DateTime startTime, DateTime finishTime) { NetConfig.InitializeSwitch(); do { try { ChannelFactory<Phenix.Services.Contract.Wcf.IPermanentLog> channelFactory = GetChannelFactory(); Phenix.Services.Contract.Wcf.IPermanentLog channel = channelFactory.CreateChannel(); try { channel.ClearUserExecuteAction(userNumber, typeName, action, startTime, finishTime); channelFactory.Close(); } catch { channelFactory.Abort(); throw; } break; } catch (EndpointNotFoundException) { if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } #region 应用服务不支持传事务 public void SaveRenovate(DbTransaction transaction, string tableName, ExecuteAction action, IList<FieldValue> fieldValues) { throw new NotSupportedException(MethodBase.GetCurrentMethod().Name); } #endregion #endregion #endregion } }
using Phenix.Core.Plugin; namespace Phenix.Security.Windows.ResetPassword { public class Plugin : PluginBase<Plugin> { /// <summary> /// 分析消息 /// 由 PluginHost 调用 /// </summary> /// <param name="message">消息</param> /// <returns>按需返回</returns> public override object AnalyseMessage(object message) { return Phenix.Services.Client.Security.ChangePasswordDialog.Execute(); } } }