text
stringlengths
13
6.01M
using TestWebService.Helpers; using TestWebService.Model; using System.Web.Script.Serialization; using System; namespace TestWebService.Data { /// <summary> /// Репозиторий /// </summary> internal class RepositoryLoginet : IRepository { public User[] GetUsers() { return new JavaScriptSerializer().Deserialize<User[]>(ResponseApiHelper.GetResponseJson("http://jsonplaceholder.typicode.com/users")); } public User GetUserById(int id) { return new JavaScriptSerializer().Deserialize<User>(ResponseApiHelper.GetResponseJson("http://jsonplaceholder.typicode.com/users/" + id)); } public Album[] GetAlbums() { return new JavaScriptSerializer().Deserialize<Album[]>(ResponseApiHelper.GetResponseJson("http://jsonplaceholder.typicode.com/albums")); } public Album GetAlbumById(int id) { return new JavaScriptSerializer().Deserialize<Album>(ResponseApiHelper.GetResponseJson("http://jsonplaceholder.typicode.com/albums/" + id)); } public Album[] GetAlbumsByUserId(int userId) { return new JavaScriptSerializer().Deserialize<Album[]>(ResponseApiHelper.GetResponseJson("http://jsonplaceholder.typicode.com/albums?userId=" + userId)); } } }
namespace FamousQuoteQuiz.Data.RepositoryModels { public class Quote { public int Id { get; set; } public string Text { get; set; } public byte Mode { get; set; } public bool? Correct { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Reflection; namespace CRL.DicConfig { /// <summary> /// 字典设置维护 /// 通过TYPE区分不同的用途 /// </summary> public class DicConfigBusiness<TType> : BaseProvider<IDicConfig> where TType : class { public static DicConfigBusiness<TType> Instance { get { return new DicConfigBusiness<TType>(); } } protected override DBExtend dbHelper { get { return GetDbHelper<TType>(); } } /// <summary> /// 添加一项 /// </summary> /// <param name="dic"></param> /// <returns></returns> public int Add(IDicConfig dic) { if (QueryItem(b => b.Name == dic.Name && b.DicType == dic.DicType) != null) { return 0; } int id = base.Add(dic); //ClearCache(); return id; } /// <summary> /// 取名称 /// </summary> /// <param name="id"></param> /// <returns></returns> public string GetName(int id) { DicConfig dic = Get(id); if (dic == null) return ""; return dic.Name; } /// <summary> /// 取值 /// </summary> /// <param name="id"></param> /// <returns></returns> public string GetValue(int id) { DicConfig dic = Get(id); if (dic == null) return ""; return dic.Value; } /// <summary> /// 取对象 /// </summary> /// <param name="id"></param> /// <returns></returns> public IDicConfig Get(int id, bool noCache = false) { if (noCache) { return QueryItem(b => b.Id == id); } else { var items = AllCache.Where(b => b.Id == id); return items.FirstOrDefault(); } } /// <summary> /// 取该类型的对象 /// </summary> /// <param name="type"></param> /// <returns></returns> public List<IDicConfig> Get(string type, bool noCache = false) { if (noCache) { return QueryList(b => b.DicType == type); } return AllCache.Where(b => b.DicType == type).ToList(); } public string GetName(Enum type, string value) { return GetName(type.ToString(), value); } public string GetName(string type, string value) { var dic = QueryItemFromAllCache(b => b.DicType == type && b.Value == value); if (dic == null) return ""; return dic.Name; } public List<CRL.DicConfig.IDicConfig> Get(Enum dType) { return Get(dType.ToString()); } public CRL.DicConfig.IDicConfig Get(Enum dType, string name, bool nocache = false) { return Get(dType.ToString(), name, nocache); } public CRL.DicConfig.IDicConfig Get(string type, string dName, bool noCache = false) { IDicConfig dic; if (noCache) { dic = QueryItem(b => b.DicType == type && b.Name == dName); } else { dic = AllCache.Where(b => b.DicType == type && b.Name == dName).FirstOrDefault(); } if (dic == null) { throw new Exception(string.Format("找不到对应的字典 类型:{0} 名称:{1}", type, dName)); } return dic; } /// <summary> /// 获取对象分组 /// </summary> /// <returns></returns> public List<string> GetTypeGroup() { List<string> list = new List<string>(); foreach (IDicConfig v in AllCache) { if (!list.Contains(v.DicType)) { list.Add(v.DicType); } } return list; } /// <summary> /// 更新值 /// </summary> /// <param name="id"></param> /// <param name="value"></param> /// <returns></returns> public bool Update(int id,string name,string value,string remark="") { CRL.ParameCollection c = new ParameCollection(); c["name"] = name; c["value"] = value; if (!string.IsNullOrEmpty(remark)) { c["remark"] = remark; } Update(b => b.Id == id, c); //ClearCache(); return true; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Windows_Project { public partial class Categories : Form { SqlConnection conn = new SqlConnection(Properties.Settings.Default.NorthwindConnectionString); // hold id number int categoryID; // For add or edit decider bool isAdd = false; public Categories() { InitializeComponent(); } private void Categories_Load(object sender, EventArgs e) { //Load data to combo on load form loadcboCategories(); } // method to gather info for combox read data to combobox private void loadcboCategories() { try { SqlDataReader rd; if (conn.State != ConnectionState.Open) { conn.Open(); } cboCategories.DataSource = null; cboCategories.Items.Clear(); SqlCommand comm = new SqlCommand(); comm.CommandText = "usp_SSelectCategories"; comm.CommandType = CommandType.StoredProcedure; comm.Connection = conn; rd = comm.ExecuteReader(); DataTable tblCat = new DataTable(); tblCat.Load(rd); cboCategories.DataSource = tblCat; cboCategories.DisplayMember = "CategoryName"; cboCategories.ValueMember = "CategoryID"; if (rd.IsClosed == false) { rd.Close(); } } catch (SqlException ex) { MessageBox.Show(ex.Message); } } private void btnAdd_Click(object sender, EventArgs e) { isAdd = true; txtDescription.Clear(); txtName.Clear(); txtName.Select(); } private void cboCategories_SelectedIndexChanged(object sender, EventArgs e) { isAdd = false; if (cboCategories.SelectedIndex > 0) { loadCategoryDetails(); } } //method Load details onto form private void loadCategoryDetails() { try { categoryID = int.Parse(cboCategories.SelectedValue.ToString()); SqlDataReader rd; //Load data of selected record SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "usp_SSelectCategoryByID"; comm.CommandType = CommandType.StoredProcedure; comm.Parameters.Add("@CategoryID", SqlDbType.Int).Value = categoryID; rd = comm.ExecuteReader(); while (rd.Read()) { txtName.Text = rd["CategoryName"].ToString(); txtDescription.Text = rd["Description"].ToString(); } if (rd.IsClosed == false) rd.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception Info", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void btnCancel_Click(object sender, EventArgs e) { this.Hide(); } //Validate data private bool ValidateData() { try { if (txtName.Text == "") { err.SetError(txtName, "Please enter a Category Name"); return false; } else err.SetError(txtName, ""); if (txtDescription.Text == "") { err.SetError(txtDescription, "Please enter a Description"); return false; } else err.SetError(txtDescription, ""); return true; } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } } //Method insert private void InsertCategory() { try { if (conn.State != ConnectionState.Open) conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "usp_SInsertCategory"; comm.CommandType = CommandType.StoredProcedure; comm.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 15).Value = txtName.Text.ToString(); comm.Parameters.Add("@Description", SqlDbType.NText).Value = txtDescription.Text.ToString(); comm.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Record not saved", MessageBoxButtons.OK, MessageBoxIcon.Information); } } //Method Update private void UpdateCategory() { try { if (conn.State != ConnectionState.Open) conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; comm.CommandText = "usp_SUpdateCategory"; comm.CommandType = CommandType.StoredProcedure; comm.Parameters.Add("@CategoryID", SqlDbType.Int).Value = categoryID; comm.Parameters.Add("@CategoryName", SqlDbType.NVarChar, 15).Value = txtName.Text.Trim(); comm.Parameters.Add("@Description", SqlDbType.NText).Value = txtDescription.Text.Trim(); comm.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Record not saved", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnAccept_Click(object sender, EventArgs e) { if (ValidateData() == false) return; if (isAdd == true) InsertCategory(); else UpdateCategory(); MessageBox.Show("Record successfully saved", "Save Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information); loadcboCategories(); } private void panel1_Paint(object sender, PaintEventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class Spawner : MonoBehaviour { public static Spawner instance; public int count; public Vector3 startPoint; public Vector3 endPoint; public GameObject road; public GameObject parent; public GameObject infoBar; public TextMeshProUGUI infoBarText; public int generation; public bool overlay; void Start() { instance = this; infoBar.SetActive(false); } // Update is called once per frame void Update() { setPoints(); } void setPoints() { Vector2 mousePos = Input.mousePosition; mousePos = Camera.main.ScreenToWorldPoint(mousePos); if (Input.GetMouseButtonDown(1)) { if(count == 0) { startPoint = mousePos; count++; } else if(count == 1) { endPoint = mousePos; count = 0; createRoad(); } } } void createRoad() { GameObject newRoad = Instantiate(road, transform.position, transform.rotation); newRoad.transform.SetParent(parent.transform); newRoad.transform.localScale = new Vector3(1, 1, 1); newRoad.GetComponent<Road>().startPoint.transform.position = startPoint; newRoad.GetComponent<Road>().endPoint.transform.position = endPoint; } public void populateRoads() { GameObject[] roads = GameObject.FindGameObjectsWithTag("Road"); foreach(GameObject road in roads) { road.GetComponent<Road>().setUpHouses(); } } public void createJunctions() { GameObject[] roads = GameObject.FindGameObjectsWithTag("Road"); foreach (GameObject road in roads) { road.GetComponent<Road>().createJunction(); } generation++; } public void switchOverlay() { overlay = !overlay; } }
namespace LeapYear.Src { public class LeapYear { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace BList { [Serializable] class Person { private string firstName; private string lastName; private string phoneNumber; private string reason; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public string PhoneNumber { get { return phoneNumber; } set { Regex regex = new Regex(@"^\d{10}$"); if (regex.IsMatch(value)) { phoneNumber = value; } else { phoneNumber = "0000000000"; } } } public string Reason { get { return reason; } set { reason = value; } } public override string ToString() { return "" + firstName + " " + lastName + " was blacklisted because " + reason +" Phone number: "+phoneNumber; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Repulsion_Field : MonoBehaviour { public float activationTime = 5; public Image inRepulsorWarning; public Image inRepulsorDamaged; public GameObject sfx; private float timer = 0; private Hitbox hitbox; // Use this for initialization void Start () { if (!GetComponent<Hitbox>()) { gameObject.AddComponent<Hitbox>(); } hitbox = GetComponent<Hitbox>(); hitbox.enabled = false; gameObject.SetActive(false); } // Update is called once per frame void Update () { timer += Time.deltaTime; if (timer <= activationTime) { GetComponent<Collider>().enabled = true; //GetComponent<Renderer>().enabled = true; hitbox.enabled = false; sfx.SetActive(true); sfx.transform.GetChild(0).gameObject.SetActive(false); } else { hitbox.enabled = true; //GetComponent<Renderer>().enabled = false; sfx.SetActive(true); sfx.transform.GetChild(0).gameObject.SetActive(true); if (timer > (activationTime + hitbox.disappearTime)) { hitbox.enabled = false; timer = 0; inRepulsorWarning.enabled = false; inRepulsorDamaged.enabled = false; sfx.SetActive(false); gameObject.SetActive(false); } } } private void OnTriggerStay(Collider other) { if (other.gameObject.tag == "Player" && timer <= activationTime) { inRepulsorWarning.enabled = true; inRepulsorDamaged.enabled = false; } else if (other.gameObject.tag == "Player" && timer > activationTime) { inRepulsorWarning.enabled = false; inRepulsorDamaged.enabled = true; } } private void OnTriggerExit(Collider other) { if (other.gameObject.tag == "Player") { inRepulsorWarning.enabled = false; inRepulsorDamaged.enabled = false; } } }
/* * Created by SharpDevelop. * User: User * Date: 4/2/2016 * Time: 6:03 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Robot { /// <summary> /// Description of EditRecipe. /// </summary> public partial class frmEditRecipe : Form { WeightValue _oldWeight = new WeightValue(); WeightValue _newWeight = new WeightValue(); WeightValue _ptrCurrentWeightDB; public frmEditRecipe() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); ctrl2ValuesDisplay1.LblTitle1.Text = "Courante:"; ctrl2ValuesDisplay1.LblTitle2.Text = "Nouvelle:"; this.ResizeChildrenText(); _oldWeight.WeightChangedDel += eOldWeightChange; _newWeight.WeightChangedDel += eNewWeightChange; ctrlNumPad.BtnClickDel += eNumPadClick; ctrlIngredientSelect.IngredientChangeOccurred += eIngredientSelectedChange; ctrlGroupSelect.GroupChangeOccurred += eGroupSelectedChange; LoadSelectedValue(); } void eOldWeightChange(WeightValue wv) { //this.lblOldValue.Text = wv.FormatKg(); ctrl2ValuesDisplay1.LblValue1.Text = wv.FormatKg(); } void eNewWeightChange(WeightValue wv) { //this.lblNewValue.Text = wv.FormatKg(); ctrl2ValuesDisplay1.LblValue2.Text = wv.FormatKg(); } void eNumPadClick(PadCommand pCommand) { _newWeight.HandleKey(pCommand); } void eIngredientSelectedChange(object sender, CtrlIngredientSelectEventArgs e) { WriteToDBCurrentIngredient(); LoadSelectedValue(); } public delegate void InvokeDelegate(); public void eGroupSelectedChange(object sender, CtrlGroupSelectEventArgs e) { WriteToDBCurrentIngredient(); ctrlIngredientSelect.BeginInvoke(new InvokeDelegate(InvokeMethod)); LoadSelectedValue(); } public void InvokeMethod() { ctrlIngredientSelect.SelectIngredient(1); } void LoadSelectedValue() { var groupID = ctrlGroupSelect.SelectedGroup; var ingredientID = ctrlIngredientSelect.SelectedIngredient; _ptrCurrentWeightDB = GR.Instance.IngBD.GetWeightValue(groupID, ingredientID); _oldWeight.Value = _ptrCurrentWeightDB.Value; _newWeight.Value = _oldWeight.Value; } void BtnQuitClick(object sender, EventArgs e) { this.Close(); } void FrmEditRecipeFormClosing(object sender, FormClosingEventArgs e) { WriteToDBCurrentIngredient(); GR.Instance.IngBD.SaveFile(); } void WriteToDBCurrentIngredient() { _ptrCurrentWeightDB.Value = _newWeight.Value; } // IEnumerable<Control> GetAll(Control control,Type type) // { // var controls = control.Controls.Cast<Control>(); // // return controls.SelectMany(ctrl => GetAll(ctrl,type)) // .Concat(controls) // .Where(type.IsInstanceOfType); // } // // void ResizeChildrenText() // { // var ctrl = GetAll(this,typeof(ICtrlAutoResizable)); // foreach (var element in ctrl) // { // ((ICtrlAutoResizable)element).ResizeControlText(); // } // } void FrmEditRecipeClientSizeChanged(object sender, EventArgs e) { this.ResizeChildrenText(); } } }
using System.ComponentModel.DataAnnotations; namespace Airelax.Application.ManageHouses.Request { public class HouseTitleInput { [MaxLength(50)] public string Title { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Health : MonoBehaviour { public SpriteSlider hp; private uint value=1;//uint 表示值不可能为负 // Use this for initialization void Start () { hp=GetComponentInChildren<SpriteSlider>();//代码找到组建,不用一个个拖拽 Init(); } public void Init() { hp.Value = value;//血条初始化值为1 } //减血的方法 public void TakeDamage(float damage) { hp.Value -= damage; } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { public class Ticket { private SqlConnection con; private SqlDataReader reader; private SqlDataAdapter da; SqlCommandBuilder cmdBuilder; DataSet TicketDataSet = new DataSet(); public String from, destination; public int id , fromZone, destinationZone; public double price; public Ticket() { } public Ticket(int id) { this.id = id; } public Ticket(String from, String destination, int fromZone, int destinationZone, double price) { this.from = from; this.destination = destination; this.fromZone = fromZone; this.destinationZone = destinationZone; this.price = price; } public void Get(int id) { con = new SqlConnection(Properties.Settings.Default.connectionString); con.Open(); reader = new SqlCommand("select * from Ticket where ID=" + id, con).ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { this.id = reader.GetInt32(0); from = reader.GetString(1); destination = reader.GetString(2); fromZone = reader.GetInt32(3); destinationZone = reader.GetInt32(4); price = reader.GetDouble(5); Console.WriteLine("ID | From (zone): | To:(zone) | Price \n {0} | {1} ({3}) | {2} ({4}) | {5}", this.id, from, destination, fromZone, destinationZone, price); } reader.Close(); con.Close(); } else { Console.WriteLine("No rows found."); reader.Close(); con.Close(); throw new NullReferenceException(); } } public List<Ticket> GetAll() { List<Ticket> result = new List<Ticket>(); Ticket temp; con = new SqlConnection(Properties.Settings.Default.connectionString); con.Open(); reader = new SqlCommand("select * from Ticket", con).ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { temp = new Ticket(reader.GetString(1), reader.GetString(2), reader.GetInt32(3), reader.GetInt32(4), reader.GetDouble(5)); temp.id = reader.GetInt32(0); result.Add(temp); } } reader.Close(); con.Close(); return result; } public void Insert() { con = new SqlConnection(Properties.Settings.Default.connectionString); con.Open(); da = new SqlDataAdapter("select * from Ticket where ID=" + id, con); cmdBuilder = new SqlCommandBuilder(da); da.Fill(TicketDataSet, "Ticket"); DataRow newRow = TicketDataSet.Tables["Ticket"].NewRow(); newRow[1] = this.from; newRow[2] = this.destination; newRow[3] = this.fromZone; newRow[4] = this.destinationZone; newRow[5] = this.price; TicketDataSet.Tables["Ticket"].Rows.Add(newRow); da.Update(TicketDataSet, "Ticket"); reader = new SqlCommand("SELECT * FROM Ticket WHERE ID = (SELECT MAX(ID) FROM Ticket)", con).ExecuteReader(); reader.Read(); this.id = reader.GetInt32(0); reader.Close(); con.Close(); } public void Remove() { con = new SqlConnection(Properties.Settings.Default.connectionString); con.Open(); reader = new SqlCommand("delete from Ticket where ID=" + id, con).ExecuteReader(); reader.Close(); con.Close(); } public void RemoveAll() { con = new SqlConnection(Properties.Settings.Default.connectionString); con.Open(); reader = new SqlCommand("delete from Ticket", con).ExecuteReader(); reader.Close(); con.Close(); } public void Update(Ticket data) { con = new SqlConnection(Properties.Settings.Default.connectionString); con.Open(); reader = new SqlCommand("UPDATE Ticket SET [From] = '"+ data.from +"',Destination ='"+ data.destination +"',FromZone = '" + data.fromZone +"',DestinationZone = '" + data.destinationZone +"',Price = '" + data.price +"' WHERE ID=" + id, con).ExecuteReader(); reader.Close(); con.Close(); Ticket.Set(this, data); } public static void Set(Ticket ticket, Ticket data) { ticket.from = data.from; ticket.destination = data.destination; ticket.fromZone = data.fromZone; ticket.destinationZone = data.destinationZone; ticket.price = data.price; } } }
using Accessor; using Modules; using UnityEngine; public class EatEdibleScript : MonoBehaviour { private void OnCollisionEnter(Collision other) { if (other.gameObject.layer == 11) { // point/fruit var scoreModule = TAccessor<ScoreModule>.Instance.Get(this); var edible = other.gameObject.GetComponent<EdibleModule>(); switch (edible.edibleType) { case EdibleType.Fruit: scoreModule.score += 500; GameManager.Instance.ActivateFruitMode(); break; case EdibleType.Point: AudioManager.Instance.PlayEating(); scoreModule.score += 100; break; } Destroy(edible.gameObject); } } }
// <copyright file="BaseController.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace SmartLibrary.Admin.Pages { using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; using Infrastructure.Code; using Infrastructure.Filters; using SmartLibrary.Admin.Classes; using SmartLibrary.Infrastructure; using SmartLibrary.Models; using static Infrastructure.SystemEnumList; /// <summary> /// Areas Name /// <CreatedBy>Tirthak SHah</CreatedBy> /// <CreatedDate>14-Aug-2018</CreatedDate> /// <ModifiedBy></ModifiedBy> /// <ModifiedDate></ModifiedDate> /// <ReviewBy>Hardik Panchal</ReviewBy> /// <ReviewDate>14-Aug-2018</ReviewDate> /// </summary> [SmartLibraryValidateAntiforgery] public abstract class BaseController : Controller { /// <summary> /// The access right /// </summary> private PageAccessRight pageAccessRight; /// <summary> /// Gets the access right. /// </summary> /// <value> /// The access right. /// </value> protected PageAccessRight PageAccessRight { get { return this.pageAccessRight; } } /// <summary> /// Gets a value indicating whether gets Disable Async Support /// </summary> protected override bool DisableAsyncSupport { get { return true; } } /// <summary> /// GetPageAccessRight /// </summary> /// <param name="controllerName">controllerName</param> /// <param name="actionName">actionName</param> public void GetPageAccessRight(string controllerName, string actionName = "") { this.pageAccessRight = new PageAccessRight(); this.pageAccessRight.PageName = actionName; this.pageAccessRight.Controller = controllerName; this.pageAccessRight.Delete = false; this.pageAccessRight.AddUpdate = false; this.pageAccessRight.View = false; List<PageAccess> lstRights = (List<PageAccess>)ProjectSession.UserRoleRights; PageAccess rights = lstRights.Where(x => x.ActionName.ToLower() == actionName.ToLower()).FirstOrDefault(); if (rights != null) { if (rights?.IsView ?? false) { this.pageAccessRight.View = true; } if (rights?.IsAddUpdate ?? false) { this.pageAccessRight.AddUpdate = true; } if (rights?.IsDelete ?? false) { this.pageAccessRight.Delete = true; } } if (ProjectSession.UserId > 0 && ProjectSession.SuperAdmin) { this.pageAccessRight.AddUpdate = true; this.pageAccessRight.View = true; this.pageAccessRight.Delete = true; } } /// <summary> /// override base class method, it will be called before every action initialize. /// </summary> protected override void ExecuteCore() { CultureInfo cultureInfo = new CultureInfo(General.GetCultureName(ProjectSession.AdminPortalLanguageId), true); cultureInfo.DateTimeFormat.FullDateTimePattern = ProjectConfiguration.DateTimeFormat; cultureInfo.DateTimeFormat.ShortDatePattern = ProjectConfiguration.DateFormat; System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo; System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; base.ExecuteCore(); } /// <summary> /// override base class method, it will be called for every action method in the class. /// </summary> /// <param name="filterContext">filter Context</param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { string permissionName = string.Empty; string actionName = filterContext.ActionDescriptor.ActionName; if (filterContext.ActionDescriptor.IsDefined(typeof(PageAccessAttribute), true)) { PageAccessAttribute pageAccessAttibute = (PageAccessAttribute)filterContext.ActionDescriptor.GetCustomAttributes(true).Where(x => x.GetType() == typeof(PageAccessAttribute)).FirstOrDefault(); permissionName = pageAccessAttibute.PermissionName; actionName = pageAccessAttibute.ActionName; } if (ProjectSession.UserId <= 0) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 403; filterContext.Result = new JsonResult { Data = Resources.Messages.SessionExpiredMessage, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { this.AddToastMessage(Resources.General.SessionExpired, Resources.Account.SessionTimeOut, MessageBoxType.Info, true); filterContext.Result = this.RedirectToAction(Actions.ActiveDirectoryLogin, Controllers.ActiveDirectory, new { returnUrl = ProjectConfiguration.CurrentRawUrl }); } } else if (ProjectSession.UserId > 0) { if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(SkipAuthorizationAttribute), true).Length > 0 || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(SkipAuthorizationAttribute), true).Length > 0) { return; } // no need to check for manage profile and change password. if ((filterContext.ActionDescriptor.ControllerDescriptor.ControllerName == Controllers.User && !(actionName == Actions.ChangePassword || actionName == Actions.MyProfile || actionName == Actions.UserProfile)) || filterContext.ActionDescriptor.ControllerDescriptor.ControllerName != Controllers.User) { this.GetPageAccessRight(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, actionName); if (filterContext.HttpContext.Request.IsAjaxRequest()) { if (filterContext.HttpContext.Request.RequestType.ToLower() != "post") { if (!Rights.HasAccess(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, actionName: actionName, permissionName: permissionName)) { filterContext.Result = this.RedirectToAction(Actions.AccessDenied, Controllers.Account); } } } else { if (!Rights.HasAccess(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, actionName: actionName, permissionName: permissionName)) { filterContext.Result = this.RedirectToAction(Actions.AccessDenied, Controllers.Account); } } } } base.OnActionExecuting(filterContext); } /// <summary> /// Max JSON Length /// </summary> /// <param name="data">data value</param> /// <param name="contentType">content Type value</param> /// <param name="contentEncoding">content Encoding</param> /// <param name="behavior">behavior value</param> /// <returns>This ActionResult will override the existing JSONResult and will automatically set the</returns> protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior) { return new JsonResult() { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior, MaxJsonLength = int.MaxValue //// Use this value to set your maximum size for all of your Requests }; } } }
using AHAO.TPLMS.Entitys; using System; using System.Collections.Generic; using System.Text; namespace AHAO.TPLMS.Contract { public interface IUserRepository:IRepository<User> { IEnumerable<User> LoadUsers(int pageindex, int pagesize); User GetUser(string userName); bool Delete(string ids); } }
using UnityEngine; public class HorrorMeter : MonoBehaviour { public GameObject Player; public Texture2D bgImage; public Texture2D fgImage; void Start() { if (Player == null) Player = GameObject.FindGameObjectWithTag ("Player"); } void OnGUI () { // Create one Group to contain both images // Adjust the first 2 coordinates to place it somewhere else on-screen GUI.BeginGroup (new Rect (Screen.width / 10.0f, 10, 1024, 32)); // Draw the background image GUI.Box (new Rect (0, 0, 800, 32), bgImage); // Create a second Group which will be clipped // We want to clip the image and not scale it, which is why we need the second Group GUI.BeginGroup (new Rect (0, 0, Player.GetComponent<PlayerScript>().HorrorMeter * 8, 32)); // Draw the foreground image GUI.Box (new Rect (0, 0, 800, 32), fgImage); // End both Groups GUI.EndGroup (); GUI.EndGroup (); } }
using gView.Framework.IO; using gView.Framework.system; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace gView.Framework.UI { public class MyFavorites { public MyFavorites() { } public bool AddFavorite(string name, string path, Image image) { try { RemoveFavorite(name, path); FileInfo fi = new FileInfo(ConfigPath); XmlStream stream = new XmlStream("Favorites"); FavoriteList favList = new FavoriteList(); if (fi.Exists) { stream.ReadStream(fi.FullName); favList = (FavoriteList)stream.Load("favlist", null, favList); if (favList == null) { favList = new FavoriteList(); } } favList.Add(new Favorite(name, path, image)); stream = new XmlStream("Favorites"); stream.Save("favlist", favList); stream.WriteStream(fi.FullName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error - Add Favorite"); } return false; } public bool RemoveFavorite(string name, string path) { try { FileInfo fi = new FileInfo(ConfigPath); if (!fi.Exists) { return false; } XmlStream stream = new XmlStream("Favorites"); stream.ReadStream(fi.FullName); FavoriteList favList = (FavoriteList)stream.Load("favlist", null, new FavoriteList()); if (favList == null) { return false; } favList.Remove(name, path); stream = new XmlStream("Favorites"); stream.Save("favlist", favList); stream.WriteStream(fi.FullName); return true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Error - Remove Favorite"); } return false; } public List<Favorite> Favorites { get { try { FileInfo fi = new FileInfo(ConfigPath); if (fi.Exists) { XmlStream stream = new XmlStream("Favorites"); stream.ReadStream(fi.FullName); return (FavoriteList)stream.Load("favlist", new FavoriteList(), new FavoriteList()); } else { return new FavoriteList(); } } catch { return new FavoriteList(); } } } private string ConfigPath { get { return SystemVariables.MyApplicationData + @"\Favorites.xml"; } } #region HelperClasses private class FavoriteList : List<Favorite>, IPersistable { public void Remove(string name, string path) { foreach (Favorite fav in ListOperations<Favorite>.Clone(this)) { if (fav.Name == name && fav.Path == path) { this.Remove(fav); } } } #region IPersistable Member public void Load(IPersistStream stream) { Favorite fav; while ((fav = (Favorite)stream.Load("fav", null, new Favorite())) != null) { this.Add(fav); } } public void Save(IPersistStream stream) { foreach (Favorite fav in this) { stream.Save("fav", fav); } } #endregion } public class Favorite : IPersistable { string _name = String.Empty, _path = String.Empty; Image _image = null; public Favorite() { } public Favorite(string name, string path, Image image) { _name = name; _path = path; _image = image; } public string Name { get { return _name; } } public string Path { get { return _path; } } public Image Image { get { return _image; } } #region IPersistable Member public void Load(IPersistStream stream) { _name = (string)stream.Load("name", String.Empty); _path = (string)stream.Load("path", String.Empty); if (_image != null) { _image.Dispose(); _image = null; } string imageBase64 = (string)stream.Load("image", String.Empty); if (!String.IsNullOrEmpty(imageBase64)) { try { _image = MyFavorites.Base64StringToImage(imageBase64); } catch { } } } public void Save(IPersistStream stream) { stream.Save("name", _name); stream.Save("path", _path); if (_image != null) { stream.Save("image", MyFavorites.ImageToBase64String(_image, ImageFormat.Png)); } } #endregion } #endregion #region Helper private static string ImageToBase64String(Image imageData, ImageFormat format) { string base64; MemoryStream memory = new MemoryStream(); imageData.Save(memory, format); base64 = System.Convert.ToBase64String(memory.ToArray()); memory.Close(); memory = null; return base64; } private static Image Base64StringToImage(string base64) { MemoryStream memory = new MemoryStream(Convert.FromBase64String(base64)); Image imageData = Image.FromStream(memory); memory.Close(); memory = null; return imageData; } #endregion } internal class FavoriteMenuItem : ToolStripMenuItem { MyFavorites.Favorite _fav; public FavoriteMenuItem(MyFavorites.Favorite fav) { _fav = fav; if (_fav != null) { this.Text = _fav.Name; if (fav.Image == null) { this.Image = global::gView.Win.Explorer.UI.Properties.Resources.folder_go; } else { this.Image = fav.Image; } } } public MyFavorites.Favorite Favorite { get { return _fav; } } } }
 using Xamarin.Forms; namespace RRExpress.Views { public partial class ForgetPwdView : ContentPage { public ForgetPwdView() { InitializeComponent(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using EPI.Strings; using FluentAssertions; namespace EPI.UnitTests.Strings { [TestClass] public class EliasGammaEncodingUnitTest { [TestMethod] public void EliasGammaEncode_Cases() { EliasGammaEncoding.EliasGammaEncode(new[] {13}).Should().Be("0001101"); EliasGammaEncoding.EliasGammaEncode(new[] { 1, 2, 3 }).Should().Be("1010011"); EliasGammaEncoding.EliasGammaEncode(new[] { 10, 100, 1000 }).Should().Be("000101000000011001000000000001111101000"); } [TestMethod] public void EliasGammaDecode_Cases() { EliasGammaEncoding.EliasGammaDecode("0001101").ShouldBeEquivalentTo(new[] { 13}); EliasGammaEncoding.EliasGammaDecode("000101000000011001000000000001111101000").ShouldBeEquivalentTo(new[] { 10, 100, 1000 }); EliasGammaEncoding.EliasGammaDecode("1010011").ShouldBeEquivalentTo(new[] { 1, 2,3 }); } } }
namespace ForumSystem.Web.ViewModels.Administration.Categories { using System.Collections.Generic; using ForumSystem.Web.ViewModels.PartialViews; public class CategoryCrudModelList { public IEnumerable<CategoryCrudModel> Categories { get; set; } public PaginationViewModel PaginationModel { get; set; } public string SearchTerm { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using FXB.Common; using FXB.Data; using FXB.DataManager; namespace FXB.Dialog { public partial class PersonnelDataDlg : Form, DBUpdateInterface { public PersonnelDataDlg() { SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); UpdateStyles(); InitializeComponent(); } private bool jobNumberOrNameInquire(BasicDataInterface bd) { EmployeeData data = bd as EmployeeData; if (gonghaoEdi.Text != "") { if (data.JobNumber.IndexOf(gonghaoEdi.Text) == -1 && data.Name.IndexOf(gonghaoEdi.Text) == -1) { return false; } } if (jobStateCb.SelectedIndex != 0) { if (jobStateCb.SelectedIndex == 1 && !data.JobState) { return false; } if (jobStateCb.SelectedIndex == 2 && data.JobState) { return false; } } if (ruzhiCb.CheckState == CheckState.Checked) { //入职时间做为查询条件了 UInt32 minTime = TimeUtil.DateTimeToTimestamp(ruzhiMinTime.Value); UInt32 maxTime = TimeUtil.DateTimeToTimestamp(ruzhiMaxTime.Value); if (data.EnteryTime < minTime || data.EnteryTime > maxTime) { return false; } } if (lizhiCb.CheckState == CheckState.Checked) { //入职时间做为查询条件了 UInt32 minTime = TimeUtil.DateTimeToTimestamp(lizhiMinTime.Value); UInt32 maxTime = TimeUtil.DateTimeToTimestamp(lizhiMaxTime.Value); if (data.DimissionTime < minTime || data.DimissionTime > maxTime) { return false; } } TreeNode selectNode = departmentTreeView.SelectedNode; if (selectNode != null) { Int64 departmentId = Convert.ToInt64(selectNode.Name); if (!DepartmentUtil.FindEmployeeByDepartment(departmentId, data.JobNumber)) { return false; } } return true; } private void InquireBtn_Click(object sender, EventArgs e) { EmployeeDataMgr.Instance().SetDataGridView(dataGridView1, jobNumberOrNameInquire); } private void PersonnelDataDlg_Load(object sender, EventArgs e) { WindowState = FormWindowState.Maximized; //禁止改变窗口大小 //this.FormBorderStyle = FormBorderStyle.FixedSingle; //this.DoubleBuffered = true; jobStateCb.Items.Insert(0, "所有"); jobStateCb.Items.Insert(1, "在职"); jobStateCb.Items.Insert(2, "离职"); jobStateCb.SelectedIndex = 0; //禁止改变表格的大小 dataGridView1.AllowUserToAddRows = false; //不显示插入行 dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing; dataGridView1.AllowUserToResizeColumns = false; dataGridView1.AllowUserToResizeRows = false; dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView1.MultiSelect = false; dataGridView1.ReadOnly = true; SetDataGridViewColumn(); DepartmentDataMgr.Instance().SetTreeView(departmentTreeView); EmployeeDataMgr.Instance().SetDataGridView(dataGridView1); } private void AddDepartmentBtn_Click(object sender, EventArgs e) { TreeNode n = departmentTreeView.SelectedNode; DepartmentData selectDepartment = null; if (n != null) { Int64 selectDepartmentId = Convert.ToInt64(n.Name); selectDepartment = DepartmentDataMgr.Instance().AllDepartmentData[selectDepartmentId]; if (selectDepartment.IsMaxLayer()) { MessageBox.Show("只能有四层部门"); return; } if (selectDepartment.QTLevel == QtLevel.ZhuchangZhuguan) { MessageBox.Show("驻场只能有三层部门"); return; } } DepartmentOperDlg dlg = new DepartmentOperDlg(EditMode.EM_ADD, selectDepartment); if (dlg.ShowDialog() == DialogResult.OK) { //重新刷新树 if (dlg.NewDepartmentId != 0) { DepartmentData newDepartmentData = DepartmentDataMgr.Instance().AllDepartmentData[dlg.NewDepartmentId]; var allTreeNode = departmentTreeView.Nodes.Find(newDepartmentData.SuperiorId.ToString(), true); //因为ID是不重复的所以返回的是只有一个数组的元素 int childCount = allTreeNode.Count<TreeNode>(); if (childCount != 1) { MessageBox.Show("部门关系发生异常,请重新启动程序"); System.Environment.Exit(0); } TreeNode parentNode = allTreeNode[0]; parentNode.Nodes.Add(newDepartmentData.Id.ToString(), newDepartmentData.Name); } //DepartmentDataMgr.Instance().SetTreeView(treeView1); } } private void ModifyDepartmentBtn_Click(object sender, EventArgs e) { ModifyDepartment(); } public void DbRefresh() { } private void AddPersonnelBtn_Click(object sender, EventArgs e) { Int64 selectDepartmentId = 0; TreeNode n = departmentTreeView.SelectedNode; if (n != null) { selectDepartmentId = Convert.ToInt64(n.Name); } EmployeeOperDlg dlg = new EmployeeOperDlg(selectDepartmentId); if (dlg.ShowDialog() == DialogResult.OK) { if (dlg.NewEmployeeId != "") { EmployeeData newProjectData = EmployeeDataMgr.Instance().AllEmployeeData[dlg.NewEmployeeId]; int newLine = dataGridView1.Rows.Add(); UpdateGridViewRow(dataGridView1.Rows[newLine], newProjectData); } } } private void RemoveDepartmentBtn_Click(object sender, EventArgs e) { TreeNode n = departmentTreeView.SelectedNode; if (n == null) { return; } if (n.Nodes.Count != 0) { MessageBox.Show("部门还有子部门,不能删除"); return; } Int64 departmentId = Convert.ToInt64(n.Name); try { DepartmentDataMgr.Instance().DeleteDepartment(departmentId); n.Remove(); } catch (ConditionCheckException ex1) { MessageBox.Show(ex1.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); System.Environment.Exit(0); } } private void treeView1_DoubleClick(object sender, EventArgs e) { // ModifyDepartment(); } private void ModifyDepartment() { TreeNode n = departmentTreeView.SelectedNode; if (n == null) { return; } Int64 selectDepartmentId = Convert.ToInt64(n.Name); DepartmentData selectDepartment = DepartmentDataMgr.Instance().AllDepartmentData[selectDepartmentId]; DepartmentOperDlg dlg = new DepartmentOperDlg(EditMode.EM_EDIT, selectDepartment); if (dlg.ShowDialog() == DialogResult.OK) { //重新刷新树 //DepartmentDataMgr.Instance().SetTreeView(treeView1); //只能修改部门名字 //n.Name = selectDepartment.Name; n.Text = selectDepartment.Name; } } private void SetDataGridViewColumn() { DataGridViewTextBoxColumn gonghao = new DataGridViewTextBoxColumn(); gonghao.Name = "gonghao"; gonghao.HeaderText = "工号"; gonghao.Width = 100; dataGridView1.Columns.Add(gonghao); DataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn(); name.Name = "name"; name.HeaderText = "姓名"; name.Width = 70; dataGridView1.Columns.Add(name); DataGridViewTextBoxColumn qt = new DataGridViewTextBoxColumn(); qt.Name = "qt"; qt.HeaderText = "QT级别"; qt.Width = 100; dataGridView1.Columns.Add(qt); DataGridViewTextBoxColumn departmentName = new DataGridViewTextBoxColumn(); departmentName.Name = "departmentName"; departmentName.HeaderText = "部门"; departmentName.Width = 250; dataGridView1.Columns.Add(departmentName); DataGridViewCheckBoxColumn isOwner = new DataGridViewCheckBoxColumn(); isOwner.Name = "isOwner"; isOwner.HeaderText = "主管"; isOwner.Width = 40; dataGridView1.Columns.Add(isOwner); DataGridViewTextBoxColumn zhiji = new DataGridViewTextBoxColumn(); zhiji.Name = "zhiji"; zhiji.HeaderText = "职级"; zhiji.Width = 60; dataGridView1.Columns.Add(zhiji); DataGridViewTextBoxColumn dianhua = new DataGridViewTextBoxColumn(); dianhua.Name = "dianhua"; dianhua.HeaderText = "电话"; dianhua.Width = 80; dataGridView1.Columns.Add(dianhua); DataGridViewTextBoxColumn ruzhiTime = new DataGridViewTextBoxColumn(); ruzhiTime.Name = "ruzhiTime"; ruzhiTime.HeaderText = "入职时间"; ruzhiTime.Width = 80; dataGridView1.Columns.Add(ruzhiTime); DataGridViewCheckBoxColumn jobState = new DataGridViewCheckBoxColumn(); jobState.Name = "jobState"; jobState.HeaderText = "在职状态"; jobState.Width = 60; dataGridView1.Columns.Add(jobState); DataGridViewTextBoxColumn lizhiTime = new DataGridViewTextBoxColumn(); lizhiTime.Name = "lizhiTime"; lizhiTime.HeaderText = "离职时间"; lizhiTime.Width = 80; dataGridView1.Columns.Add(lizhiTime); DataGridViewTextBoxColumn shenfenzheng = new DataGridViewTextBoxColumn(); shenfenzheng.Name = "shenfenzheng"; shenfenzheng.HeaderText = "身份证"; shenfenzheng.Width = 120; dataGridView1.Columns.Add(shenfenzheng); DataGridViewTextBoxColumn shengriTime = new DataGridViewTextBoxColumn(); shengriTime.Name = "shengriTime"; shengriTime.HeaderText = "生日"; shengriTime.Width = 80; dataGridView1.Columns.Add(shengriTime); DataGridViewTextBoxColumn xingbie = new DataGridViewTextBoxColumn(); xingbie.Name = "xingbie"; xingbie.HeaderText = "性别"; xingbie.Width = 40; dataGridView1.Columns.Add(xingbie); DataGridViewTextBoxColumn mingzujiguan = new DataGridViewTextBoxColumn(); mingzujiguan.Name = "mingzujiguan"; mingzujiguan.HeaderText = "名族籍贯"; mingzujiguan.Width = 80; dataGridView1.Columns.Add(mingzujiguan); DataGridViewTextBoxColumn juzhudizhi = new DataGridViewTextBoxColumn(); juzhudizhi.Name = "juzhudizhi"; juzhudizhi.HeaderText = "居住地址"; juzhudizhi.Width = 150; dataGridView1.Columns.Add(juzhudizhi); DataGridViewTextBoxColumn xueli = new DataGridViewTextBoxColumn(); xueli.Name = "xueli"; xueli.HeaderText = "学历"; xueli.Width = 60; dataGridView1.Columns.Add(xueli); DataGridViewTextBoxColumn biyexuexiao = new DataGridViewTextBoxColumn(); biyexuexiao.Name = "biyexuexiao"; biyexuexiao.HeaderText = "毕业学校"; biyexuexiao.Width = 100; dataGridView1.Columns.Add(biyexuexiao); DataGridViewTextBoxColumn zhuanye = new DataGridViewTextBoxColumn(); zhuanye.Name = "zhuanye"; zhuanye.HeaderText = "专业"; zhuanye.Width = 110; dataGridView1.Columns.Add(zhuanye); DataGridViewTextBoxColumn jjLianxiren = new DataGridViewTextBoxColumn(); jjLianxiren.Name = "jjLianxiren"; jjLianxiren.HeaderText = "紧急联系人"; jjLianxiren.Width = 110; dataGridView1.Columns.Add(jjLianxiren); DataGridViewTextBoxColumn jjLianxidianhua = new DataGridViewTextBoxColumn(); jjLianxidianhua.Name = "jjLianxidianhua"; jjLianxidianhua.HeaderText = "紧急联系电话"; jjLianxidianhua.Width = 110; dataGridView1.Columns.Add(jjLianxidianhua); DataGridViewTextBoxColumn jieshaoren = new DataGridViewTextBoxColumn(); jieshaoren.Name = "jieshaoren"; jieshaoren.HeaderText = "介绍人"; jieshaoren.Width = 70; dataGridView1.Columns.Add(jieshaoren); DataGridViewTextBoxColumn beizhu = new DataGridViewTextBoxColumn(); beizhu.Name = "beizhu"; beizhu.HeaderText = "备注"; beizhu.Width = 599; dataGridView1.Columns.Add(beizhu); } private void dataGridView1_DoubleClick(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count == 0) { return; } //只能选择一行 DataGridViewTextBoxCell selectCell = (DataGridViewTextBoxCell)dataGridView1.SelectedRows[0].Cells["gonghao"]; string gonghao = (string)selectCell.Value; EmployeeData employeeData = EmployeeDataMgr.Instance().AllEmployeeData[gonghao]; EmployeeOperDlg dlg = new EmployeeOperDlg(employeeData); //JobGradeOperDlg dlg = new JobGradeOperDlg(selectData); if (dlg.ShowDialog() == DialogResult.OK) { //更新选中的行 UpdateGridViewRow(dataGridView1.SelectedRows[0], employeeData); } } private void UpdateGridViewRow(DataGridViewRow row, EmployeeData data) { row.Cells["gonghao"].Value = data.JobNumber; row.Cells["name"].Value = data.Name; row.Cells["qt"].Value = QtUtil.GetQTLevelString(data.QTLevel); row.Cells["departmentName"].Value = DepartmentUtil.GetDepartmentShowText(data.DepartmentId); row.Cells["isOwner"].Value = data.IsOwner; row.Cells["zhiji"].Value = data.JobGradeName; row.Cells["dianhua"].Value = data.PhoneNumber; //row.Cells["ruzhiTime"].Value = TimeUtil.TimestampToDateTime(data.EnteryTime).ToShortDateString(); //row.Cells["jobState"].Value = data.JobState; //row.Cells["lizhiTime"].Value = TimeUtil.TimestampToDateTime(data.DimissionTime).ToShortDateString(); row.Cells["jobState"].Value = data.JobState; row.Cells["ruzhiTime"].Value = TimeUtil.TimestampToDateTime(data.EnteryTime).ToShortDateString(); if (!data.JobState) { row.Cells["lizhiTime"].Value = TimeUtil.TimestampToDateTime(data.DimissionTime).ToShortDateString(); } else { row.Cells["lizhiTime"].Value = ""; } row.Cells["shenfenzheng"].Value = data.IdCard; row.Cells["shengriTime"].Value = TimeUtil.TimestampToDateTime(data.Birthday).ToShortDateString(); row.Cells["xingbie"].Value = data.Sex ? "男" : "女"; row.Cells["mingzujiguan"].Value = data.EthnicAndOrigin; row.Cells["juzhudizhi"].Value = data.ResidentialAddress; row.Cells["xueli"].Value = data.Education; row.Cells["biyexuexiao"].Value = data.SchoolTag; row.Cells["zhuanye"].Value = data.Specialities; row.Cells["jjLianxiren"].Value = data.EmergencyContact; row.Cells["jjLianxidianhua"].Value = data.EmergencyTelephoneNumber; row.Cells["jieshaoren"].Value = data.Introducer; row.Cells["beizhu"].Value = data.Comment; } private void treeView1_Click(object sender, EventArgs e) { Int64 s1 = TimeUtil.DateTimeToMs(DateTime.Now); EmployeeDataMgr.Instance().SetDataGridView(dataGridView1, jobNumberOrNameInquire); Int64 s2 = TimeUtil.DateTimeToMs(DateTime.Now); Console.WriteLine((s2-s1).ToString()); } private void departmentTreeView_MouseDown(object sender, MouseEventArgs e) { if ((sender as TreeView) != null) { departmentTreeView.SelectedNode = departmentTreeView.GetNodeAt(e.X, e.Y); } } private void ExportBtn_Click(object sender, EventArgs e) { ExcelUtil.ExportData(dataGridView1); } private void RemovePersonnelBtn_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count == 0) { return; } //只能选择一行 DataGridViewRow selectRow = dataGridView1.SelectedRows[0]; DataGridViewTextBoxCell selectCell = (DataGridViewTextBoxCell)selectRow.Cells["gonghao"]; string gonghao = (string)selectCell.Value; //检测工号是否能删除 try { EmployeeData curEmployeeData = AuthMgr.Instance().CurLoginEmployee; if (curEmployeeData.JobNumber == gonghao) { throw new ConditionCheckException(string.Format("当前登陆用户不能删除")); } foreach (var item in QtMgr.Instance().AllQtTask) { QtTask qtTask = item.Value; foreach (var orderItem in qtTask.AllQtOrder) { QtOrder qtOrder = orderItem.Value; if (qtOrder.YxJob.Exist(gonghao)) { throw new ConditionCheckException(string.Format("工号[{0}]在QT任务[{1}]的订单[{2}]里被指定为营销顾问,不能删除", gonghao, item.Key, orderItem.Key)); } if (qtOrder.KyfConsultanJobNumber == gonghao) { throw new ConditionCheckException(string.Format("工号[{0}]在QT任务[{1}]的订单[{2}]里被指定为客源方,不能删除", gonghao, item.Key, orderItem.Key)); } if (qtOrder.Zc1JobNumber == gonghao) { throw new ConditionCheckException(string.Format("工号[{0}]在QT任务[{1}]的订单[{2}]里被指定为驻场1,不能删除", gonghao, item.Key, orderItem.Key)); } if (qtOrder.Zc2JobNumber == gonghao) { throw new ConditionCheckException(string.Format("工号[{0}]在QT任务[{1}]的订单[{2}]里被指定为驻场2,不能删除", gonghao, item.Key, orderItem.Key)); } } } EmployeeDataMgr.Instance().RemoveEmployeeData(gonghao); dataGridView1.Rows.RemoveAt(selectRow.Index); } catch (ConditionCheckException ex1) { MessageBox.Show(ex1.Message); } catch (Exception ex2) { MessageBox.Show(ex2.Message); System.Environment.Exit(0); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebUI.Data.Abstract; using WebUI.Entity; namespace WebUI.Data.Concrete.EfCore { public class EfImageRepository : IImageRepository { private ApplicationIdentityDbContext _context; public EfImageRepository(ApplicationIdentityDbContext context) { _context = context; } public void AddImage(string Name, int postId, int type) { bool cover = false; if (GetAll().Where(i => i.PostId == postId).ToList().Count == 0) { cover = true; } var images = new Image() { Name = Name, IsCoverImage = cover, PostId = postId, Type = type, Status = true }; _context.Add(images); _context.SaveChanges(); } public void ChangeCoverImage(int imageId) { var coverImage = GetById(imageId); int type = GetById(imageId).Type; var images = GetAll().Where(i => i.PostId == coverImage.PostId).Where(i => i.Type == type); foreach (var img in images) { img.IsCoverImage = false; } if (coverImage != null) { coverImage.IsCoverImage = true; } _context.SaveChanges(); } public void DeleteImage(int imageId) { var image = _context.Images.FirstOrDefault(i => i.ImageId == imageId); if (image != null) { _context.Images.Remove(image); _context.SaveChanges(); } } public IQueryable<Image> GetAll() { return _context.Images; } public Image GetById(int imageId) { return _context.Images.FirstOrDefault(i => i.ImageId == imageId); } public void SaveImage(Image image) { if (image.ImageId == 0) { _context.Images.Add(image); } else { var data = GetById(image.ImageId); if (data != null) { data.Name = image.Name; data.IsCoverImage = image.IsCoverImage; data.Status = image.Status; } } _context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Szab.Scheduling.Representation { public class TaskAssignment { public Task Task { get; protected set; } public Resource Resource { get; set; } public int StartOffset { get; set; } public int EndOffset { get { return StartOffset + this.Task.Length; } } public float Cost { get { return this.Task.Length * this.Resource.Cost; } } public int Length { get { return this.Task.Length; } } public TaskAssignment(Task task, Resource resource, int offset) { if(task == null || resource == null) { throw new ArgumentNullException(); } this.Task = task; this.Resource = resource; this.StartOffset = offset; } public TaskAssignment(TaskAssignment assignment) : this(assignment.Task, assignment.Resource, assignment.StartOffset) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CodeGeneration { static class StringUtils { public static void AppendLine(this StringBuilder sb, string str, int n) { var s = "\t".Repeat (n) + str; sb.AppendLine (s); } public static string Repeat(this string s, int n) { var sb = new StringBuilder (); for (var i = 0; i < n; i++) sb.Append (s); return sb.ToString (); } public static string Repeat(this char c, int n) { var array = new char[n]; for (var i = 0; i < n; i++) array[i] = c; return new String (array); } public static string Join(this IEnumerable<string> xs, string sep) { return string.Join (sep, xs); } } }
using System; namespace NGeoNames.Entities { /// <summary> /// Represents an administrative division. /// </summary> public class Admin1Code { /// <summary> /// Gets/sets the code of the administrative division. /// </summary> public string Code { get; set; } /// <summary> /// Gets/sets the name of the administrative division. /// </summary> public string Name { get; set; } /// <summary> /// Gets/sets the name of the administrative division in plain ASCII. /// </summary> /// <remarks> /// Non-ASCII values have been found in the data; it is unfortunately (currently) *NOT* guaranteed that this /// property contains ASCII-only strings. /// </remarks> public string NameASCII { get; set; } /// <summary> /// Gets/sets the geoname database Id of the administrative division. /// </summary> public int GeoNameId { get; set; } } }
using System; using System.Collections.Generic; using Xamarin.Forms; using Pasasoft.Crm.ViewModels; namespace Pasasoft.Crm { public partial class CustomerDetailPage : ContentPage { public CustomerViewModel CustomerViewModel { get{ return BindingContext as CustomerViewModel; } } public CustomerDetailPage () { InitializeComponent (); } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); Title = CustomerViewModel.Customer.Company.Name; } } }
#if UNITY_2019_1_OR_NEWER using UnityEditor; using UnityAtoms.Editor; namespace UnityAtoms.Mobile.Editor { /// <summary> /// Value List property drawer of type `TouchUserInput`. Inherits from `AtomDrawer&lt;TouchUserInputValueList&gt;`. Only availble in `UNITY_2019_1_OR_NEWER`. /// </summary> [CustomPropertyDrawer(typeof(TouchUserInputValueList))] public class TouchUserInputValueListDrawer : AtomDrawer<TouchUserInputValueList> { } } #endif
using System; namespace Animals { class Program { // En POO, las funciones y procedimientos se llaman métodos // En todo programa, se debe incluir un punto inicial // El nombre estándar para el método que inicia un programa // es "main": static void Main // // void -> no devuelve ningún valor (es un procedimiento) // static -> entorno estático; trabajando a nivel clase en vez de objeto static void Main(string[] args) { // Console.WriteLine("Hello World!"); DecirHolaMundo(); Mapache mapache1 = new Mapache(false, 40f, 3.5f, "gris", "ALUCARD"); Mapache mapache2 = new Mapache(false, 45f, 4f, "Cafe", "Carlos"); Mapache mapache3 = new Mapache(true, 30f, 7f, "Negro", "Joanna"); { mapache3.DitunombreJoanna(); mapache3.DitucolorJoanna(); mapache3.ComerJoanna(); mapache3.HablarJoanna(); mapache3.MoverseJoanna(); mapache3.TreparJoanna(); mapache3.informacionJoanna(); } Mapache Mapache4 = new Mapache(false, 60f, 20f, "Cafe con negro", "Jorge"); { Mapache4.DitunombreJorge(); Mapache4.ditucolorjorge(); Mapache4.ComerJorge(); Mapache4.HablarJorge(); Mapache4.MoverseJorge(); Mapache4.TreparJorge(); Mapache4.informacionJorge(); } } static string ObtenerTextoAMostrar() { return "Hello World!"; } static void DecirHolaMundo() { string textoAMostrar = ObtenerTextoAMostrar(); Console.WriteLine(textoAMostrar); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Voluntariat.Data; using Voluntariat.Framework.Identity; using Voluntariat.Models; namespace Voluntariat.Controllers { [Route("api/[controller]")] [ApiController] [Authorize(Roles = CustomIdentityRole.Volunteer)] public class BeneficiariesAPITestController : ControllerBase { private readonly ApplicationDbContext _context; public BeneficiariesAPITestController(ApplicationDbContext context) { _context = context; } // GET: api/BeneficiariesAPITest [HttpGet] public async Task<ActionResult<IEnumerable<Beneficiary>>> GetBeneficiaries() { var result = await _context.Beneficiaries.ToListAsync(); return result; } // GET: api/BeneficiariesAPITest/5 [HttpGet("{id}")] public async Task<ActionResult<Beneficiary>> GetBeneficiary(Guid id) { var beneficiary = await _context.Beneficiaries.FindAsync(id); if (beneficiary == null) { return NotFound(); } return beneficiary; } // PUT: api/BeneficiariesAPITest/5 // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPut("{id}")] public async Task<IActionResult> PutBeneficiary(Guid id, Beneficiary beneficiary) { if (id != beneficiary.ID) { return BadRequest(); } _context.Entry(beneficiary).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BeneficiaryExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/BeneficiariesAPITest // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://go.microsoft.com/fwlink/?linkid=2123754. [HttpPost] public async Task<ActionResult<Beneficiary>> PostBeneficiary(Beneficiary beneficiary) { _context.Beneficiaries.Add(beneficiary); await _context.SaveChangesAsync(); return CreatedAtAction("GetBeneficiary", new { id = beneficiary.ID }, beneficiary); } // DELETE: api/BeneficiariesAPITest/5 [HttpDelete("{id}")] public async Task<ActionResult<Beneficiary>> DeleteBeneficiary(Guid id) { var beneficiary = await _context.Beneficiaries.FindAsync(id); if (beneficiary == null) { return NotFound(); } _context.Beneficiaries.Remove(beneficiary); await _context.SaveChangesAsync(); return beneficiary; } private bool BeneficiaryExists(Guid id) { return _context.Beneficiaries.Any(e => e.ID == id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem201 : ProblemBase { public override string ProblemName { get { return "201: Subsets with a unique sum"; } } public override string GetAnswer() { Test(); return BruteForce(8).ToString(); return ""; } private void Test() { var result = new Dictionary<int, List<Tuple>>(); for (int x = 1; x <= 50; x++) { for (int y = x + 1; y <= 50; y++) { var sum = x * x + y * y; if (!result.ContainsKey(sum)) { result.Add(sum, new List<Tuple>()); } result[sum].Add(new Tuple() { X = x, Y = y }); } } var final = result.Where(x => x.Value.Count > 1).ToList(); bool stop = true; } private class Tuple { public int X { get; set; } public int Y { get; set; } } private ulong BruteForce(ulong m) { Recursive(1, 0, m, m / 2); ulong sum = 0; _counts.Where(x => x.Value == 1).Select(x => x.Key).ToList().ForEach(x => sum += x); return sum; } private Dictionary<ulong, ulong> _counts = new Dictionary<ulong, ulong>(); private void Recursive(ulong last, ulong sum, ulong m, ulong remain) { for (ulong next = last; next <= m; next++) { var nextSum = sum + (next * next); if (remain > 1) { Recursive(next + 1, nextSum, m, remain - 1); } else if (remain == 1) { if (!_counts.ContainsKey(nextSum)) { _counts.Add(nextSum, 1); } else { _counts[nextSum]++; } } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ManChain : MonoBehaviour { [SerializeField] private Transform _targetPoint = null; [SerializeField] private float _distance = 1f; private List<Player> _players = new List<Player>(); public void AddPlayer(Player player) { if (!_players.Contains(player)) _players.Add(player); } public void RemovePlayer(Player player) { if (_players.Contains(player)) _players.Remove(player); } public bool Contains(Player player) => _players.Contains(player); public Vector3 GetDestination(Player player) { if (!_players.Contains(player)) return Vector3.zero; int index = _players.IndexOf(player); return _targetPoint.position - _targetPoint.forward * index * _distance; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebsiteManagerPanel.Framework.RoleEnums { public class Enum { public enum RoleGroup { Employee = 1, Admin = 2 } public enum AdminRole { ShowSite = 1, CanChangeSite = 2, ShowDefinition = 4, CanChangeDefinition = 8, ShowField = 16, CanChangeField = 32, } public enum EmployeeRole { GetEmployees = 1, CanChangeEmployee = 2 } } }
using System; using System.Collections.Generic; namespace IrsMonkeyApi.Models.DB { public partial class MemberStatus { public MemberStatus() { Member = new HashSet<Member>(); } public int MemberStatusId { get; set; } public string MemberStatusName { get; set; } public ICollection<Member> Member { get; set; } } }
using Microsoft.Extensions.Logging; using Sentry.Infrastructure; namespace Sentry.Extensions.Logging; internal sealed class SentryLogger : ILogger { private readonly IHub _hub; private readonly ISystemClock _clock; private readonly SentryLoggingOptions _options; internal string CategoryName { get; } internal SentryLogger( string categoryName, SentryLoggingOptions options, ISystemClock clock, IHub hub) { CategoryName = categoryName; _options = options; _clock = clock; _hub = hub; } public IDisposable BeginScope<TState>(TState state) => _hub.PushScope(state); public bool IsEnabled(LogLevel logLevel) => _hub.IsEnabled && logLevel != LogLevel.None && (logLevel >= _options.MinimumBreadcrumbLevel || logLevel >= _options.MinimumEventLevel); public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string>? formatter) { if (!IsEnabled(logLevel)) { return; } var message = formatter?.Invoke(state, exception); if (ShouldCaptureEvent(logLevel, eventId, exception)) { var @event = CreateEvent(logLevel, eventId, state, exception, message, CategoryName); _ = _hub.CaptureEvent(@event); } // Even if it was sent as event, add breadcrumb so next event includes it if (ShouldAddBreadcrumb(logLevel, eventId, exception)) { var data = eventId.ToDictionaryOrNull(); if (exception != null && message != null) { // Exception.Message won't be used as Breadcrumb message // Avoid losing it by adding as data: data ??= new Dictionary<string, string>(); data.Add("exception_message", exception.Message); } _hub.AddBreadcrumb( _clock, message ?? exception?.Message!, CategoryName, null, data, logLevel.ToBreadcrumbLevel()); } } internal static SentryEvent CreateEvent<TState>( LogLevel logLevel, EventId id, TState state, Exception? exception, string? message, string category) { var @event = new SentryEvent(exception) { Logger = category, Message = message, Level = logLevel.ToSentryLevel() }; if (state is IEnumerable<KeyValuePair<string, object>> pairs) { foreach (var property in pairs) { if (property.Key == "{OriginalFormat}" && property.Value is string template) { // Original format found, use Sentry logEntry interface @event.Message = new SentryMessage { Formatted = message, Message = template }; continue; } switch (property.Value) { case string stringTagValue: @event.SetTag(property.Key, stringTagValue); break; case Guid guidTagValue when guidTagValue != Guid.Empty: @event.SetTag(property.Key, guidTagValue.ToString()); break; case Enum enumValue: @event.SetTag(property.Key, enumValue.ToString()); break; default: { if (property.Value?.GetType().IsPrimitive == true) { @event.SetTag(property.Key, Convert.ToString(property.Value, CultureInfo.InvariantCulture)!); } break; } } } } var tuple = id.ToTupleOrNull(); if (tuple.HasValue) { @event.SetTag(tuple.Value.name, tuple.Value.value); } return @event; } private bool ShouldCaptureEvent( LogLevel logLevel, EventId eventId, Exception? exception) => _options.MinimumEventLevel != LogLevel.None && logLevel >= _options.MinimumEventLevel && !IsFromSentry() && !IsEfExceptionMessage(eventId) && _options.Filters.All( f => !f.Filter( CategoryName, logLevel, eventId, exception)); private bool ShouldAddBreadcrumb( LogLevel logLevel, EventId eventId, Exception? exception) => _options.MinimumBreadcrumbLevel != LogLevel.None && logLevel >= _options.MinimumBreadcrumbLevel && !IsFromSentry() && !IsEfExceptionMessage(eventId) && _options.Filters.All( f => !f.Filter( CategoryName, logLevel, eventId, exception)); private bool IsFromSentry() { if (string.Equals(CategoryName, "Sentry", StringComparison.Ordinal)) { return true; } #if DEBUG if (CategoryName.StartsWith("Sentry.Samples.", StringComparison.Ordinal)) { return false; } #endif return CategoryName.StartsWith("Sentry.", StringComparison.Ordinal); } internal static bool IsEfExceptionMessage(EventId eventId) { return eventId.Name is "Microsoft.EntityFrameworkCore.Update.SaveChangesFailed" or "Microsoft.EntityFrameworkCore.Query.QueryIterationFailed" or "Microsoft.EntityFrameworkCore.Query.InvalidIncludePathError" or "Microsoft.EntityFrameworkCore.Update.OptimisticConcurrencyException"; } }
using System.Linq; using System.Threading.Tasks; using Sfa.Poc.ResultsAndCertification.Dfe.Domain.Models; using Sfa.Poc.ResultsAndCertification.Dfe.Models; namespace Sfa.Poc.ResultsAndCertification.Dfe.Application.Interfaces { public interface ITqPathwayService { IQueryable<TqPathway> GetTqPathways(); Task<TqPathwayDetails> GetTqPathwayDetailsByIdAsync(int pathwayId); Task<TqPathwayDetails> GetTqPathwayDetailsByCodeAsync(string code); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; namespace EmberKernel.Services.UI.Mvvm.ViewModel { public class KernelViewModelManager : IViewModelManager { private readonly Dictionary<string, INotifyPropertyChanged> instanceBinding = new Dictionary<string, INotifyPropertyChanged>(); private readonly Dictionary<Type, string> typeBinding = new Dictionary<Type, string>(); public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChangeEvent(object sender, PropertyChangedEventArgs args) { PropertyChanged?.Invoke(sender, args); } private string GetFullName(Type type) { if (type.GetCustomAttribute<ModelAttribute>() is ModelAttribute attr) { return $"{type.Namespace}{attr.Id}"; } return $"{type.Namespace}{type.Name}"; } private string GetFullName<T>() => GetFullName(typeof(T)); public void Register<T>(T instance) where T : INotifyPropertyChanged { var type = typeof(T); var fullName = GetFullName<T>(); instanceBinding.Add(fullName, instance); typeBinding.Add(type, fullName); instance.PropertyChanged += RaisePropertyChangeEvent; } public void Unregister<T>() where T : INotifyPropertyChanged { var type = typeof(T); var fullName = GetFullName<T>(); var instance = instanceBinding[fullName]; instance.PropertyChanged -= RaisePropertyChangeEvent; instanceBinding.Remove(fullName); typeBinding.Remove(type); } } }
using UnityEngine; public class TestMovement : MonoBehaviour { public float speed = 8.0f; void Start() { } void Update() { Vector2 movement_input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); Vector2 movement_delta = speed * movement_input.normalized * Time.deltaTime; transform.position += new Vector3(movement_delta.x, movement_delta.y, 0.0f); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public enum SceneName { LobbyScene, GameScene } [RequireComponent(typeof(Button))] public class SceneChangeButton : MonoBehaviour { [SerializeField] private SceneName sceneName; private void Awake() { Button button = transform.GetComponent<Button>(); if (button != null) button.onClick.AddListener(ChangeScene); } public void ChangeScene() { UnityEngine.SceneManagement.SceneManager.LoadScene((int)sceneName); System.GC.Collect(); } }
using System; class Point { public int XCor; public int YCor; public Point(int x,int y) { this.XCor = x; this.YCor = y; } public void SetCordinates(int p1, int p2) { this.XCor = p1; this.YCor = p2; } public static double GetLenght(Point p1, Point p2) { double dLeght = Math.Sqrt(Math.Pow((p1.XCor - p2.XCor), 2) + Math.Pow((p1.YCor - p2.YCor), 2)); return dLeght; } public static double GetAreaForm(Point p1, Point p2) { return (p1.XCor*p2.YCor - p1.YCor*p2.XCor); } }
public interface IUnitAttackState : IUnitState { void SetTarget(IUnit targetBehaviourParam); void SetWeapon(WeaponModel weaponParam); }
public class Solution { public IList<string> WordBreak(string s, IList<string> wordDict) { var hs = new HashSet<string>(wordDict); var dict = new Dictionary<int, IList<int>>(); for (int i = 1; i <= s.Length; i ++) { dict[i] = new List<int>(); for (int j = 0; j < i; j ++) { if ((j == 0 || dict[j].Count > 0) && hs.Contains(s.Substring(j, i-j))) { dict[i].Add(j); } } } // for (int i = 1; i < s.Length; i ++) { // Console.WriteLine($"key {i}:"); // Console.WriteLine(String.Join('-', dict[i])); // } var res = new List<string>(); DFSHelper(s, dict, res, "", s.Length); return res; } private void DFSHelper(string s, Dictionary<int, IList<int>> dict, IList<string> res, string currRes, int index) { if (index == 0) { res.Add(currRes); return; } foreach (int next in dict[index]) { string currStr = s.Substring(next, index - next) + (index == s.Length ? currRes : " " + currRes); DFSHelper(s, dict, res, currStr, next); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Xml; public partial class xmlgelen2aspx : System.Web.UI.Page { DataView resimurl; protected void Page_Load(object sender, EventArgs e) { resimurl = (DataView)Session["Resim"]; GridView1.DataSource = resimurl; //gridviewin veri kaynağı olarak data view belirlendi GridView1.DataBind();//dataviewde bulunan veriler grid içineyazdırıldı. //resimurl.ToTable().WriteXml(Server.MapPath("~/sonuc.xml"));//Dataviewde bulunan veriler xml bir dosya içerisine aktarıldı. } }
namespace Properties.Infrastructure.Zoopla.Objects { internal class Constants { public const string ProviderName = "ZOOPLA"; //TEST //public const string BaseUri = "https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/"; //LIVE public const string BaseUri = "https://realtime-listings-api.webservices.zpg.co.uk/live/v1/"; //UNIVERSAL public const string CertificateThumbprint = "f2ab49a07aa7f21e2b7e387d68b67beb4d1a2a81"; public const string SendPropertyEndpoint = "listing/update"; public const string RemovePropertyEndpoint = "listing/delete"; public const string GetAllPropertiesEndpoint = "listing/list"; public const string BranchReference = "76122"; } }
using Ecommerce_Framework.Api.Models; namespace Ecommerce_Framework.Api.Data.Repositories { public class UsuarioRepository { private readonly EcommerceFrameworkContext _context; // public UsuarioRepository(EcommerceFrameworkContext context) : base(context) => _context = context; //public void Add(UsuarioModel atendimentoGrupo, bool returnId = false) //{ // if (returnId && _context.Environment.Name != "Testing") // atendimentoGrupo.AtendimentoGrupoId = GetNewSequence("Atendimento", "AtendimentoGrupo", "AtendimentoGrupo"); // _context.AtendimentoGrupo.Add(atendimentoGrupo); //} //public AtendimentoGrupoModel Find(int id) //{ // return _context.AtendimentoGrupo.AsNoTracking() // .FirstOrDefault(t => t.AtendimentoGrupoId == id); //} //public void Delete(AtendimentoGrupoModel atendimentoGrupo) //{ // atendimentoGrupo.ClearPropertyModel(); // atendimentoGrupo.Excluido = true; // _context.Entry(atendimentoGrupo).State = EntityState.Modified; //} //public void Update(AtendimentoGrupoModel atendimentoGrupo) //{ // Validation(atendimentoGrupo, EntityState.Modified); // atendimentoGrupo.Validation(); // _context.AtendimentoGrupo.Update(atendimentoGrupo); //} } }
using Langium.DataLayer.DbModels; using Langium.PresentationLayer; using Langium.PresentationLayer.ViewModels; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Langium.DataLayer.DataAccessObjects { public class CategoryDao { public async Task<DataResult<CategoryModel>> GetCategoryByIdAsync(int id) { using (var context = new LangiumDbContext()) { try { var category = await context.Categories .Include(c => c.Words) .ThenInclude(w => w.Lexeme) .Include(c => c.Words) .ThenInclude(w => w.Transcription) .Include(c => c.Words) .ThenInclude(w => w.Translation) .FirstOrDefaultAsync(c => c.Id == id); if (category == null) { return new DataResult<CategoryModel>(null, "CATEGORY_NOT_EXISTS"); }; return new DataResult<CategoryModel>(category); } catch (Exception ex) { return new DataResult<CategoryModel>(ex, ex.InnerException.Message); } } } public async Task<DataResult<IEnumerable<CategoryModel>>> GetUserCategoriesAsync(int profileId) { using (var context = new LangiumDbContext()) { try { var categories = await context.Categories .Include(c => c.Words) .ThenInclude(w => w.Lexeme) .Include(c => c.Words) .ThenInclude(w => w.Transcription) .Include(c => c.Words) .ThenInclude(w => w.Translation) .Where(c => c.ProfileId == profileId) .ToListAsync(); return new DataResult<IEnumerable<CategoryModel>>(categories); } catch (Exception ex) { return new DataResult<IEnumerable<CategoryModel>>(ex, ex.InnerException.Message); } } } public async Task<DataResult<CategoryModel>> AddCategoryAsync(CategoryAddDto category) { using (var context = new LangiumDbContext()) { try { var newCategory = new CategoryModel() { Name = category.Name, Description = category.Description, Words = new List<WordModel>(), ProfileId = category.ProfileId }; var categoryWithSameName = await context.Categories.FirstOrDefaultAsync(c => c.Name == category.Name && c.ProfileId == category.ProfileId); if (categoryWithSameName == null) { var added = await context.Categories.AddAsync(newCategory); await context.SaveChangesAsync(); return new DataResult<CategoryModel>(added.Entity); } else { return new DataResult<CategoryModel>(null, "CATEGORY_WITH_SAME_NAME_AlREADY_EXISTS"); } } catch (Exception ex) { return new DataResult<CategoryModel>(ex, ex.InnerException.Message); } } } public async Task<DataResult<CategoryModel>> UpdateCategoryAsync(CategoryModel category) { using (var context = new LangiumDbContext()) { try { context.Entry(category).State = EntityState.Modified; await context.SaveChangesAsync(); var updatedCategory = context.Categories.FirstOrDefault(c => c.Id == category.Id); return new DataResult<CategoryModel>(updatedCategory); } catch (Exception ex) { return new DataResult<CategoryModel>(ex, ex.InnerException.Message); } } } public async Task<DataResult<bool>> RemoveCategoryAsync(int id) { using (var context = new LangiumDbContext()) { try { var entity = await context.Categories.FindAsync(id); if (entity == null) { return new DataResult<bool>(null, "CATEGORY_NOT_EXISTS"); } context.Remove(entity); await context.SaveChangesAsync(); return new DataResult<bool>(true); } catch (Exception ex) { return new DataResult<bool>(ex, ex.Message); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace LoanAPound.Db.Model { public class LoanApplicationCreditScoreCheck { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] public int Id { get; set; } public int ApplicationId { get; set; } [ForeignKey("ApplicationId")] public LoanApplication Application { get; set;} public int CreditScoreProviderId { get; set; } [ForeignKey("CreditScoreProviderId")] public CreditScoreProvider CreditScoreProvider { get; set; } public double CreditScore { get; set; } public DateTimeOffset DateCreated { get; set; } public DateTimeOffset DateLastUpdated { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace net.PingTools { public class ThreadPing { public string IPString; public static List<PingTools> lpt = new List<PingTools>(); PingTools pt; public void startPingThread(string ips){ string[] ipArray = System.Text.RegularExpressions.Regex.Split(ips, "\\s{1,}"); foreach (string s in ipArray) { //System.Windows.Forms.MessageBox.Show(s); /** if (System.Text.RegularExpressions.Regex.Split(s,"\\.{1,}").Length < 4) { // System.Windows.Forms.MessageBox.Show(s+"不是ip地址"); continue; } **/ pt = new PingTools(s); lpt.Add(pt); } } public static void clear(){ System.Threading.Thread.CurrentThread.Abort(); } } }
using UnityEngine; using System.Collections; public class UseBoost : MonoBehaviour { private BoostConfig boostConfig; private PlayerStats playerStats; // Use this for initialization void Start () { boostConfig = BoostConfig.instance; playerStats = PlayerStats.instance; } public void Use() { BoostButton button = gameObject.GetComponent<BoostButton>(); BoostConfig.BoostType boostType = button.GetBoostType (); if (playerStats.GetAvailableBoostCount (boostType) <= 0) { return; } playerStats.RemoveBoost (boostType); boostConfig.ExecuteBoost (boostType); } }
using Crystal.Plot2D.Common; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Shapes; namespace Crystal.Plot2D.Charts { /// <summary> /// Represents a label provider for major ticks of <see cref="System.DateTime"/> type. /// </summary> public class MajorDateTimeLabelProvider : DateTimeLabelProviderBase { /// <summary> /// Initializes a new instance of the <see cref="MajorDateTimeLabelProvider"/> class. /// </summary> public MajorDateTimeLabelProvider() { } public override UIElement[] CreateLabels(ITicksInfo<DateTime> ticksInfo) { object info = ticksInfo.Info; var ticks = ticksInfo.Ticks; UIElement[] res = new UIElement[ticks.Length - 1]; int labelsNum = 3; if (info is DifferenceIn) { DifferenceIn diff = (DifferenceIn)info; DateFormat = GetDateFormat(diff); } else if (info is MajorLabelsInfo) { MajorLabelsInfo mInfo = (MajorLabelsInfo)info; DifferenceIn diff = (DifferenceIn)mInfo.Info; DateFormat = GetDateFormat(diff); labelsNum = mInfo.MajorLabelsCount + 1; //DebugVerify.Is(labelsNum < 100); } DebugVerify.Is(ticks.Length < 10); LabelTickInfo<DateTime> tickInfo = new(); for (int i = 0; i < ticks.Length - 1; i++) { tickInfo.Info = info; tickInfo.Tick = ticks[i]; string tickText = GetString(tickInfo); Grid grid = new() { }; // doing binding as described at http://sdolha.spaces.live.com/blog/cns!4121802308C5AB4E!3724.entry?wa=wsignin1.0&sa=835372863 grid.SetBinding(Panel.BackgroundProperty, new Binding { Path = new PropertyPath("(0)", DateTimeAxis.MajorLabelBackgroundBrushProperty), RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor) { AncestorType = typeof(AxisControlBase) } }); Rectangle rect = new() { StrokeThickness = 2 }; rect.SetBinding(Shape.StrokeProperty, new Binding { Path = new PropertyPath("(0)", DateTimeAxis.MajorLabelRectangleBorderPropertyProperty), RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor) { AncestorType = typeof(AxisControlBase) } }); Grid.SetColumn(rect, 0); Grid.SetColumnSpan(rect, labelsNum); for (int j = 0; j < labelsNum; j++) { grid.ColumnDefinitions.Add(new ColumnDefinition()); } grid.Children.Add(rect); for (int j = 0; j < labelsNum; j++) { var tb = new TextBlock { Text = tickText, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 3, 0, 3) }; Grid.SetColumn(tb, j); grid.Children.Add(tb); } ApplyCustomView(tickInfo, grid); res[i] = grid; } return res; } protected override string GetDateFormat(DifferenceIn diff) { string format = null; switch (diff) { case DifferenceIn.Year: format = "yyyy"; break; case DifferenceIn.Month: format = "MMMM yyyy"; break; case DifferenceIn.Day: format = "%d MMMM yyyy"; break; case DifferenceIn.Hour: format = "HH:mm %d MMMM yyyy"; break; case DifferenceIn.Minute: format = "HH:mm %d MMMM yyyy"; break; case DifferenceIn.Second: format = "HH:mm:ss %d MMMM yyyy"; break; case DifferenceIn.Millisecond: format = "fff"; break; default: break; } return format; } } }
using AppLogic.Dto; using AppLogic.DtoCreate; using AppLogic.DtoUpdate; using AutoMapper; using DataAccess; using DataAccess.Repositories; using Domain.Entities; using Domain.InterfacesRepo; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppLogic.DtoConverter { public class PictureConvert : Converter<Picture, CreatePicture, ReadPicture, UpdatePicture> { public PictureConvert(Context context) : base(context) { ConverterINI.SetContext(context); } } }
using gView.Framework.Carto; using gView.Framework.Carto.Rendering; using gView.Framework.Data; using gView.Framework.Data.Filters; using gView.Framework.Geometry; using gView.Framework.Symbology; using gView.Framework.Xml; using gView.GraphicsEngine; using System; using System.Globalization; using System.IO; using System.Text; using System.Threading.Tasks; using System.Xml; namespace gView.Framework.XML { public class ObjectFromAXLFactory { private static IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat; public static IQueryFilter Query(XmlNode query, ITableClass tc) { return Query(query, tc, null); } public static IQueryFilter Query(XmlNode query, ITableClass tc, IFeatureClass rootFeateatureClass) { if (tc == null || query == null) { return null; } IQueryFilter filter = (query.Name == "QUERY") ? new QueryFilter() : new SpatialFilter(); if (query.Attributes["where"] != null) { filter.WhereClause = query.Attributes["where"].Value; } if (query.Attributes["subfields"] != null) { foreach (string field in query.Attributes["subfields"].Value.Split(' ')) { if (field == "#ALL#") { filter.AddField("*"); } else if (field == "#SHAPE#" && tc is IFeatureClass) { filter.AddField(((IFeatureClass)tc).ShapeFieldName); } else if (field == "#ID#") { filter.AddField(tc.IDFieldName); } else { filter.AddField(field); } } } else { filter.SubFields = "*"; } XmlNode featureCoordsys = query.SelectSingleNode("FEATURECOORDSYS"); if (featureCoordsys != null) { filter.FeatureSpatialReference = ArcXMLGeometry.AXL2SpatialReference(featureCoordsys); } XmlNode spatialFilter = query.SelectSingleNode("SPATIALFILTER"); if (query.Name == "SPATIALQUERY" && spatialFilter != null) { ((ISpatialFilter)filter).SpatialRelation = (spatialFilter.Attributes["relation"].Value == "envelope_intersection") ? spatialRelation.SpatialRelationEnvelopeIntersects : spatialRelation.SpatialRelationIntersects; ((ISpatialFilter)filter).Geometry = Geometry(spatialFilter.InnerXml); XmlNode filterCoordsys = query.SelectSingleNode("FILTERCOORDSYS"); if (featureCoordsys != null) { ((ISpatialFilter)filter).FilterSpatialReference = ArcXMLGeometry.AXL2SpatialReference(filterCoordsys); } } XmlNode bufferNode = query.SelectSingleNode("BUFFER[@distance]"); if (bufferNode != null) { BufferQueryFilter bFilter = new BufferQueryFilter(/*filter*/); bFilter.SubFields = "*"; bFilter.BufferDistance = Convert.ToDouble(bufferNode.Attributes["distance"].Value.Replace(",", "."), _nhi); bFilter.RootFilter = filter; bFilter.RootFeatureClass = rootFeateatureClass; bFilter.FeatureSpatialReference = filter.FeatureSpatialReference; filter = bFilter; } return filter; } static public IGeometry Geometry(string axl) { return ArcXMLGeometry.AXL2Geometry(axl); } public static SimpleRenderer SimpleRenderer(XmlNode axl) { SimpleRenderer renderer = new SimpleRenderer(); foreach (XmlNode child in axl.ChildNodes) { ISymbol symbol = SimpleSymbol(child); if (symbol != null) { renderer.Symbol = symbol; } } renderer.SymbolRotation = SymbolRotationFromAXLAttribtures(axl); return renderer; } public static IFeatureRenderer ValueMapRenderer(XmlNode axl) { if (axl == null || axl.Attributes["lookupfield"] == null) { return null; } if (axl.SelectSingleNode("RANGE") != null) { return QuantityRenderer(axl); } ValueMapRenderer renderer = new ValueMapRenderer(); renderer.ValueField = axl.Attributes["lookupfield"].Value; foreach (XmlNode child in axl.ChildNodes) { if (child.Name == "EXACT" && child.Attributes["value"] != null) { ISymbol symbol = (child.ChildNodes.Count > 0) ? SimpleSymbol(child.ChildNodes[0]) : null; if (symbol is ILegendItem && child.Attributes["label"] != null) { ((LegendItem)symbol).LegendLabel = child.Attributes["label"].Value; } renderer[child.Attributes["value"].Value] = symbol; } else if (child.Name == "OTHER") { ISymbol symbol = (child.ChildNodes.Count > 0) ? SimpleSymbol(child.ChildNodes[0]) : null; if (symbol is ILegendItem && child.Attributes["label"] != null) { ((LegendItem)symbol).LegendLabel = child.Attributes["label"].Value; } renderer.DefaultSymbol = symbol; } } renderer.SymbolRotation = SymbolRotationFromAXLAttribtures(axl); return renderer; } private static QuantityRenderer QuantityRenderer(XmlNode axl) { try { QuantityRenderer renderer = new QuantityRenderer(); renderer.ValueField = axl.Attributes["lookupfield"].Value; foreach (XmlNode child in axl.ChildNodes) { if (child.Name == "RANGE" && child.Attributes["lower"] != null && child.Attributes["upper"] != null) { ISymbol symbol = (child.ChildNodes.Count > 0) ? SimpleSymbol(child.ChildNodes[0]) : null; if (symbol is ILegendItem && child.Attributes["label"] != null) { ((LegendItem)symbol).LegendLabel = child.Attributes["label"].Value; } renderer.AddClass(new QuantityRenderer.QuantityClass( double.Parse(child.Attributes["lower"].Value.Replace(",", "."), _nhi), double.Parse(child.Attributes["upper"].Value.Replace(",", "."), _nhi), symbol)); } else if (child.Name == "OTHER") { ISymbol symbol = (child.ChildNodes.Count > 0) ? SimpleSymbol(child.ChildNodes[0]) : null; if (symbol is ILegendItem && child.Attributes["label"] != null) { ((LegendItem)symbol).LegendLabel = child.Attributes["label"].Value; } renderer.DefaultSymbol = symbol; } } return renderer; } catch { return null; } } public static SimpleLabelRenderer SimpleLabelRenderer(XmlNode axl, IFeatureClass fc) { if (axl == null || fc == null) { return null; } if (axl.Attributes["field"] == null) { return null; } string fieldname = axl.Attributes["field"].Value; bool found = false; foreach (IField field in fc.Fields.ToEnumerable()) { if (field.name == fieldname) { found = true; break; } } if (fc.FindField(fieldname) == null) { return null; } if (!found) { return null; } XmlNode symbol = axl.SelectSingleNode("TEXTSYMBOL"); if (symbol == null) { symbol = axl.SelectSingleNode("TEXTMARKERSYMBOL"); } if (symbol == null) { return null; } SimpleLabelRenderer renderer = new SimpleLabelRenderer(); bool hasAlignment = false; renderer.TextSymbol = SimpleTextSymbol(symbol, out hasAlignment); if (renderer.TextSymbol == null) { return null; } renderer.FieldName = fieldname; if (!hasAlignment) { renderer.TextSymbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignOver; if (fc.GeometryType == GeometryType.Polyline) { renderer.TextSymbol.TextSymbolAlignment = TextSymbolAlignment.Over; } else if (fc.GeometryType == GeometryType.Polygon) { renderer.TextSymbol.TextSymbolAlignment = TextSymbolAlignment.Center; } } if (axl.Attributes["howmanylabels"] != null) { switch (axl.Attributes["howmanylabels"].Value.ToLower()) { case "one_label_per_name": renderer.HowManyLabels = gView.Framework.Carto.Rendering.SimpleLabelRenderer.howManyLabels.one_per_name; break; case "one_label_per_shape": renderer.HowManyLabels = gView.Framework.Carto.Rendering.SimpleLabelRenderer.howManyLabels.one_per_feature; break; case "one_label_per_part": renderer.HowManyLabels = gView.Framework.Carto.Rendering.SimpleLabelRenderer.howManyLabels.one_per_part; break; } } if (axl.Attributes["labelweight"] != null) { switch (axl.Attributes["labelweight"].Value.ToLower()) { case "no_weight": renderer.LabelPriority = gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.low; break; case "med_weight": renderer.LabelPriority = gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.normal; break; case "high_weight": renderer.LabelPriority = gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.high; break; case "always": renderer.LabelPriority = gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.always; break; } } if (axl.Attributes["cartomethod"] != null) { switch (axl.Attributes["cartomethod"].Value.ToLower()) { case "horizontal": renderer.CartoLineLabelling = gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.Horizontal; break; case "perpendicular": renderer.CartoLineLabelling = gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.Perpendicular; break; case "curvedtext": renderer.CartoLineLabelling = gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.CurvedText; break; default: renderer.CartoLineLabelling = gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.Parallel; break; } } if (axl.Attributes["expression"] != null) { renderer.LabelExpression = axl.Attributes["expression"].Value; renderer.UseExpression = true; } renderer.SymbolRotation = SymbolRotationFromAXLAttribtures(axl); return renderer; } public static IFeatureRenderer GroupRenderer(XmlNode axl) { FeatureGroupRenderer renderer = new FeatureGroupRenderer(); foreach (XmlNode child in axl.ChildNodes) { if (child.Name == "SIMPLERENDERER") { IFeatureRenderer r = ObjectFromAXLFactory.SimpleRenderer(child); if (r != null) { renderer.Renderers.Add(r); } } else if (child.Name == "VALUEMAPRENDERER") { IFeatureRenderer r = ObjectFromAXLFactory.ValueMapRenderer(child); if (r != null) { renderer.Renderers.Add(r); } } else if (child.Name == "GROUPRENDERER") { IFeatureRenderer r = ObjectFromAXLFactory.GroupRenderer(child); if (r != null) { renderer.Renderers.Add(r); } } else if (child.Name == "SCALEDEPENDENTRENDERER") { IFeatureRenderer r = ObjectFromAXLFactory.ScaleDependentRenderer(child); if (r != null) { renderer.Renderers.Add(r); } } } if (renderer.Renderers.Count == 1) { return renderer.Renderers[0]; } return renderer; } public static ScaleDependentRenderer ScaleDependentRenderer(XmlNode axl) { try { ScaleDependentRenderer renderer = new ScaleDependentRenderer(); double minScale = axl.Attributes["lower"] != null ? Scale(axl.Attributes["lower"].Value) : 0D; double maxScale = axl.Attributes["upper"] != null ? Scale(axl.Attributes["upper"].Value) : 0D; object rendererObj = GroupRenderer(axl); if (rendererObj == null) { return null; } if (rendererObj is IGroupRenderer) { foreach (IFeatureRenderer childRenderer in ((IGroupRenderer)rendererObj).Renderers) { renderer.Renderers.Add(childRenderer); } } else if (rendererObj is IFeatureRenderer) { renderer.Renderers.Add((IFeatureRenderer)rendererObj); } foreach (IScaledependent sdRenderer in renderer.Renderers) { sdRenderer.MinimumScale = minScale; sdRenderer.MaximumScale = maxScale; } return renderer.Renderers.Count > 0 ? renderer : null; } catch { return null; } } public static ScaleDependentLabelRenderer ScaleDependentLabelRenderer(XmlNode axl, IFeatureClass fc) { try { ScaleDependentLabelRenderer renderer = new ScaleDependentLabelRenderer(); double minScale = axl.Attributes["lower"] != null ? Scale(axl.Attributes["lower"].Value) : 0D; double maxScale = axl.Attributes["upper"] != null ? Scale(axl.Attributes["upper"].Value) : 0D; foreach (XmlNode labelRendererNode in axl.SelectNodes("SIMPLELABELRENDERER")) { SimpleLabelRenderer labelRenderer = SimpleLabelRenderer(labelRendererNode, fc); if (labelRenderer == null) { continue; } renderer.Renderers.Add(labelRenderer); } foreach (IScaledependent sdRenderer in renderer.Renderers) { sdRenderer.MinimumScale = minScale; sdRenderer.MaximumScale = maxScale; } return renderer; } catch { return null; } } public static string ConvertToAXL(object gViewObject) { if (gViewObject is IToArcXml) { return ((IToArcXml)gViewObject).ArcXml; } if (gViewObject is SimpleRenderer) { return SimpleRenderer2AXL(gViewObject as SimpleRenderer); } if (gViewObject is SimpleLabelRenderer) { return SimpleLabelRenderer2AXL(gViewObject as SimpleLabelRenderer); } if (gViewObject is ValueMapRenderer) { return ValueMapRenderer2AXL(gViewObject as ValueMapRenderer); } if (gViewObject is QuantityRenderer) { return QuantityRenderer2AXL(gViewObject as QuantityRenderer); } if (gViewObject is FeatureGroupRenderer) { StringBuilder sb = new StringBuilder(); sb.Append("<GROUPRENDERER>"); foreach (IFeatureRenderer renderer in ((FeatureGroupRenderer)gViewObject).Renderers) { sb.Append(ConvertToAXL(renderer)); } sb.Append("</GROUPRENDERER>"); return sb.ToString(); } if (gViewObject is ISymbol) { return Symbol2AXL(gViewObject as ISymbol, null); } return ""; } public static string SimpleRenderer2AXL(SimpleRenderer renderer) { if (renderer == null) { return ""; } string symbol = Symbol2AXL(renderer.Symbol, renderer.SymbolRotation); if (symbol.Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append("<SIMPLERENDERER"); sb.Append(SymbolRotation2AXLParameters(renderer.SymbolRotation)); sb.Append(">\n"); sb.Append(symbol); sb.Append("\n</SIMPLERENDERER>\n"); return sb.ToString(); } return ""; } public static string SimpleLabelRenderer2AXL(SimpleLabelRenderer renderer) { if (renderer == null) { return ""; } string symbol = Symbol2AXL(renderer.TextSymbol, renderer.SymbolRotation); if (symbol.Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append("<SIMPLELABELRENDERER"); sb.Append(" field=\"" + renderer.FieldName + "\""); switch (renderer.HowManyLabels) { case gView.Framework.Carto.Rendering.SimpleLabelRenderer.howManyLabels.one_per_name: sb.Append(@" howmanylabels=""one_label_per_name"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.howManyLabels.one_per_feature: sb.Append(@" howmanylabels=""one_label_per_shape"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.howManyLabels.one_per_part: sb.Append(@" howmanylabels=""one_label_per_part"""); break; } switch (renderer.LabelPriority) { case gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.low: sb.Append(@" labelweight =""no_weight"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.normal: sb.Append(@" labelweight =""med_weight"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.high: sb.Append(@" labelweight =""high_weight"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.labelPriority.always: sb.Append(@" labelweight =""always"""); break; } switch (renderer.CartoLineLabelling) { case gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.Horizontal: sb.Append(@" cartomethod=""horizontal"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.Perpendicular: sb.Append(@" cartomethod=""perpendicular"""); break; case gView.Framework.Carto.Rendering.SimpleLabelRenderer.CartographicLineLabeling.CurvedText: sb.Append(@" cartomethod=""curvedtext"""); break; default: sb.Append(@" cartomethod=""parallel"""); break; } if (renderer.LabelExpression != null && renderer.LabelExpression != String.Empty) { sb.Append(@" expression=""" + renderer.LabelExpression.Replace("&", "&amp;").Replace("\"", "&quot;").Replace("<", "&lt;").Replace(">", "&gt;") + "\""); } sb.Append(SymbolRotation2AXLParameters(renderer.SymbolRotation)); sb.Append(">\n"); sb.Append(symbol); sb.Append("\n</SIMPLELABELRENDERER>\n"); return sb.ToString(); } return ""; } public static string ValueMapRenderer2AXL(ValueMapRenderer renderer) { if (renderer == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<VALUEMAPRENDERER"); sb.Append(" lookupfield=\"" + renderer.ValueField + "\""); sb.Append(SymbolRotation2AXLParameters(renderer.SymbolRotation)); sb.Append(">\n"); foreach (string key in renderer.Keys) { string symbol = Symbol2AXL(renderer[key], renderer.SymbolRotation); if (symbol != "") { sb.Append("<EXACT"); sb.Append(" value=\"" + CheckEsc(key) + "\""); if (renderer[key] is ILegendItem) { sb.Append(" label=\"" + CheckEsc((renderer[key].LegendLabel)) + "\""); } sb.Append(">\n"); sb.Append(symbol); sb.Append("\n</EXACT>\n"); } } string defaultSymbol = Symbol2AXL(renderer.DefaultSymbol, renderer.SymbolRotation); if (defaultSymbol != "") { sb.Append("<OTHER>"); sb.Append(defaultSymbol); sb.Append("</OTHER>"); } sb.Append("\n</VALUEMAPRENDERER>\n"); return sb.ToString(); } public static string QuantityRenderer2AXL(QuantityRenderer renderer) { if (renderer == null) { return String.Empty; } StringBuilder sb = new StringBuilder(); sb.Append("<VALUEMAPRENDERER"); sb.Append(" lookupfield=\"" + renderer.ValueField + "\""); sb.Append(SymbolRotation2AXLParameters(renderer.SymbolRotation)); sb.Append(">\n"); foreach (QuantityRenderer.QuantityClass qClass in renderer.QuantityClasses) { string symbol = Symbol2AXL(qClass.Symbol, renderer.SymbolRotation); if (String.IsNullOrEmpty(symbol)) { sb.Append("<RANGE"); sb.Append(" lower=\"" + qClass.Min.ToString(_nhi) + "\" upper=\"" + qClass.Max.ToString(_nhi) + "\""); if (qClass.Symbol is ILegendItem) { sb.Append(" label=\"" + CheckEsc((qClass.Symbol.LegendLabel)) + "\""); } sb.Append(">\n"); sb.Append(symbol); sb.Append("\n</RANGE>\n"); } } string defaultSymbol = Symbol2AXL(renderer.DefaultSymbol, renderer.SymbolRotation); if (String.IsNullOrEmpty(defaultSymbol)) { sb.Append("<OTHER>"); sb.Append(defaultSymbol); sb.Append("</OTHER>"); } sb.Append("\n</VALUEMAPRENDERER>\n"); return sb.ToString(); } public static string SimpleFillSymbol2AXL(SimpleFillSymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<SIMPLEPOLYGONSYMBOL"); sb.Append(" boundary=\"" + ((symbol.OutlineSymbol != null) ? "true" : "false") + "\""); ArgbColor col; if (symbol.OutlineSymbol != null) { col = symbol.OutlineColor; sb.Append(" boundarycolor=\"" + Color2AXL(col) + "\""); if (col.A != 255) { sb.Append(" boundarytransparency=\"" + ColorTransparency2AXL(col) + "\""); } if (symbol.OutlineDashStyle != LineDashStyle.Solid) { sb.Append(" boundarytype=\"" + DashStyle2AXL(symbol.OutlineDashStyle) + "\""); } if (symbol.OutlineWidth != 1) { sb.Append(" boundarywidth=\"" + symbol.OutlineWidth.ToString() + "\""); } } col = symbol.Color; sb.Append(" fillcolor=\"" + Color2AXL(col) + "\""); if (col.A != 255) { sb.Append(" filltransparency=\"" + ColorTransparency2AXL(col) + "\""); } sb.Append("/>"); return sb.ToString(); } public static string HatchSymbol2AXL(HatchSymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<SIMPLEPOLYGONSYMBOL"); sb.Append(" boundary=\"" + ((symbol.OutlineSymbol != null) ? "true" : "false") + "\""); ArgbColor col; if (symbol.OutlineSymbol != null) { col = symbol.OutlineColor; sb.Append(" boundarycolor=\"" + Color2AXL(col) + "\""); if (col.A != 255) { sb.Append(" boundarytransparency=\"" + ColorTransparency2AXL(col) + "\""); } if (symbol.OutlineDashStyle != LineDashStyle.Solid) { sb.Append(" boundarytype=\"" + DashStyle2AXL(symbol.OutlineDashStyle) + "\""); } if (symbol.OutlineWidth != 1) { sb.Append(" boundarywidth=\"" + symbol.OutlineWidth.ToString() + "\""); } } col = symbol.ForeColor; sb.Append(" fillcolor=\"" + Color2AXL(col) + "\""); if (col.A != 255) { sb.Append(" filltransparency=\"" + ColorTransparency2AXL(col) + "\""); } switch (symbol.HatchStyle) { case HatchStyle.BackwardDiagonal: sb.Append(" filltype=\"bdiagonal\""); break; case HatchStyle.ForwardDiagonal: sb.Append(" filltype=\"fdiagonal\""); break; case HatchStyle.LargeGrid: sb.Append(" filltype=\"cross\""); break; case HatchStyle.DiagonalCross: sb.Append(" filltype=\"diagcross\""); break; case HatchStyle.Horizontal: sb.Append(" filltype=\"horizontal\""); break; case HatchStyle.Vertical: sb.Append(" filltype=\"vertical\""); break; default: sb.Append(" filltype=\"bdiagonal\""); break; } sb.Append("/>"); return sb.ToString(); } public static string SimpleLineSymbol2AXL(SimpleLineSymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<SIMPLELINESYMBOL"); sb.Append(" color=\"" + Color2AXL(symbol.Color) + "\""); if (symbol.Color.A != 255) { sb.Append(" transparency=\"" + ColorTransparency2AXL(symbol.Color) + "\""); } if (symbol.Width != 1) { sb.Append(" width=\"" + symbol.Width.ToString() + "\""); } if (symbol.DashStyle != LineDashStyle.Solid) { sb.Append(" type=\"" + DashStyle2AXL(symbol.DashStyle) + "\""); } if (symbol.Smoothingmode == SymbolSmoothing.AntiAlias) { sb.Append(" antialiasing=\"true\""); } if (symbol.LineStartCap != LineCap.Flat || symbol.LineEndCap != LineCap.Flat) { if (symbol.LineStartCap == symbol.LineEndCap) { sb.Append(" captype=\""); switch (symbol.LineStartCap) { case LineCap.Flat: sb.Append("butt"); break; default: sb.Append(symbol.LineStartCap.ToString().ToLower()); break; } sb.Append("\""); } else { sb.Append(" startcaptype=\""); switch (symbol.LineStartCap) { case LineCap.Flat: sb.Append("butt"); break; default: sb.Append(symbol.LineStartCap.ToString().ToLower()); break; } sb.Append("\""); sb.Append(" endcaptype=\""); switch (symbol.LineEndCap) { case LineCap.Flat: sb.Append("butt"); break; default: sb.Append(symbol.LineEndCap.ToString().ToLower()); break; } sb.Append("\""); } } sb.Append("/>"); return sb.ToString(); } public static string SimplePointSymbol2AXL(SimplePointSymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<SIMPLEMARKERSYMBOL"); sb.Append(" color=\"" + Color2AXL(symbol.Color) + "\""); sb.Append(" transparency=\"" + ColorTransparency2AXL(symbol.Color) + "\""); sb.Append(" outline=\"" + Color2AXL(symbol.OutlineColor) + "\""); if (symbol.Marker != SimplePointSymbol.MarkerType.Circle) { sb.Append(" type=\"" + MarkerType2AXL(symbol.Marker) + "\""); } sb.Append(" width=\"" + symbol.Size.ToString() + "\""); sb.Append(" symbolwidth=\"" + symbol.SymbolWidth.ToString() + "\""); sb.Append(" gv_outlinetransparency=\"" + ColorTransparency2AXL(symbol.OutlineColor) + "\""); sb.Append(" gv_outlinewidth=\"" + symbol.PenWidth.ToString() + "\""); sb.Append("/>"); return sb.ToString(); } public static string SimpleTextSymbol2AXL(SimpleTextSymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<TEXTMARKERSYMBOL"); if (symbol.Angle != 0f) { sb.Append(" angle=\"" + symbol.Angle + "\""); } if (symbol.Font != null) { sb.Append(" font=\"" + symbol.Font.Name + "\""); sb.Append(" fontsize=\"" + symbol.Font.Size + "\""); sb.Append(" fontstyle=\"" + FontStyle2AXL(symbol.Font.Style) + "\""); } sb.Append(" fontcolor=\"" + Color2AXL(symbol.Color) + "\""); sb.Append(" halignment=\"" + HTextSymbolAlignment2AXL(symbol.TextSymbolAlignment) + "\""); sb.Append(" valignment=\"" + VTextSymbolAlignment2AXL(symbol.TextSymbolAlignment) + "\""); if (symbol.Color.A != 255) { sb.Append(" transparency=\"" + ColorTransparency2AXL(symbol.Color) + "\""); } if (symbol.Smoothingmode == SymbolSmoothing.AntiAlias) { sb.Append(" antialiasing=\"true\""); } if (symbol is GlowingTextSymbol) { sb.Append(" glowing=\"" + Color2AXL(((GlowingTextSymbol)symbol).GlowingColor) + "\""); sb.Append(" glowingwidth=\"" + ((GlowingTextSymbol)symbol).GlowingWidth + "\""); if (((GlowingTextSymbol)symbol).GlowingSmoothingmode == SymbolSmoothing.AntiAlias) { sb.Append(" glowing_antialiasing=\"true\""); } } sb.Append("/>"); return sb.ToString(); } public static string TrueTypeMarkerSymol2AXL(TrueTypeMarkerSymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append("<TRUETYPEMARKERSYMBOL"); sb.Append(" character=\"" + symbol.Charakter + "\""); if (symbol.Angle != 0f) { sb.Append(" angle=\"" + symbol.Angle + "\""); } if (symbol.Font != null) { sb.Append(" font=\"" + symbol.Font.Name + "\""); sb.Append(" fontsize=\"" + symbol.Font.Size + "\""); sb.Append(" fontstyle=\"" + FontStyle2AXL(symbol.Font.Style) + "\""); } sb.Append(" fontcolor=\"" + Color2AXL(symbol.Color) + "\""); if (symbol.Color.A != 255) { sb.Append(" transparency=\"" + ColorTransparency2AXL(symbol.Color) + "\""); } sb.Append(" hotspot=\"" + symbol.HorizontalOffset.ToString(_nhi) + "," + symbol.VerticalOffset.ToString(_nhi) + "\""); // Die Symbolrotation hängt bei gView am Renderer //sb.Append(SymbolRotation2AXLParameters(rotation)); sb.Append("/>"); return sb.ToString(); } private static string SymbolRotation2AXLParameters(SymbolRotation rotation) { if (rotation == null || rotation.RotationFieldName == null || rotation.RotationFieldName == String.Empty) { return ""; } StringBuilder sb = new StringBuilder(); sb.Append(" anglefield=\"" + rotation.RotationFieldName + "\""); switch (rotation.RotationType) { case RotationType.aritmetic: sb.Append(" rotatemethod=\"arithmetic\""); break; case RotationType.geographic: sb.Append(" rotatemethod=\"geographic\""); break; } switch (rotation.RotationUnit) { case RotationUnit.deg: sb.Append(" rotationunit=\"deg\""); break; case RotationUnit.gon: sb.Append(" rotationunit=\"grad\""); break; case RotationUnit.rad: sb.Append(" rotationunit=\"rad\""); break; } return sb.ToString(); } private static SymbolRotation SymbolRotationFromAXLAttribtures(XmlNode axl) { if (axl == null) { return null; } if (axl.Attributes["anglefield"] == null || axl.Attributes["anglefield"].Value == String.Empty) { return null; } SymbolRotation rotation = new SymbolRotation(); rotation.RotationFieldName = axl.Attributes["anglefield"].Value; if (axl.Attributes["rotatemethod"] != null) { switch (axl.Attributes["rotatemethod"].Value.ToLower()) { case "arithmetic": rotation.RotationType = RotationType.aritmetic; break; case "geographic": rotation.RotationType = RotationType.geographic; break; } } if (axl.Attributes["rotationunit"] != null) { switch (axl.Attributes["rotationunit"].Value.ToLower()) { case "deg": rotation.RotationUnit = RotationUnit.deg; break; case "grad": rotation.RotationUnit = RotationUnit.gon; break; case "rad": rotation.RotationUnit = RotationUnit.rad; break; } } return rotation; } private static string Color2AXL(ArgbColor col) { return col.R + "," + col.G + "," + col.B; } private static string ColorTransparency2AXL(ArgbColor col) { return (col.A / 255f).ToString(); } private static string DashStyle2AXL(LineDashStyle dashstyle) { switch (dashstyle) { case LineDashStyle.Dash: return "dash"; case LineDashStyle.DashDot: return "dash_dot"; case LineDashStyle.DashDotDot: return "dash_dot_dot"; case LineDashStyle.Dot: return "dot"; } return "solid"; } private static string MarkerType2AXL(SimplePointSymbol.MarkerType type) { switch (type) { case SimplePointSymbol.MarkerType.Cross: return "cross"; case SimplePointSymbol.MarkerType.Square: return "square"; case SimplePointSymbol.MarkerType.Star: return "star"; case SimplePointSymbol.MarkerType.Triangle: return "triangle"; } return "circle"; } private static string FontStyle2AXL(FontStyle fontstyle) { if (((fontstyle & FontStyle.Italic) != 0) && ((fontstyle & FontStyle.Bold) != 0)) { return "bolditalic"; } else if ((fontstyle & FontStyle.Bold) != 0) { return "bold"; } else if ((fontstyle & FontStyle.Italic) != 0) { return "italic"; } else if ((fontstyle & FontStyle.Underline) != 0) { return "underline"; } //else if (fontstyle & FontStyle.Strikeout) // return "outline"; return "regular"; } private static string VTextSymbolAlignment2AXL(TextSymbolAlignment alignment) { switch (alignment) { case TextSymbolAlignment.Center: case TextSymbolAlignment.leftAlignCenter: case TextSymbolAlignment.rightAlignCenter: return "center"; case TextSymbolAlignment.Over: case TextSymbolAlignment.leftAlignOver: case TextSymbolAlignment.rightAlignOver: return "top"; case TextSymbolAlignment.Under: case TextSymbolAlignment.leftAlignUnder: case TextSymbolAlignment.rightAlignUnder: return "bottom"; } return "top"; } private static string HTextSymbolAlignment2AXL(TextSymbolAlignment alignment) { switch (alignment) { case TextSymbolAlignment.Center: case TextSymbolAlignment.Over: case TextSymbolAlignment.Under: return "center"; case TextSymbolAlignment.leftAlignUnder: case TextSymbolAlignment.leftAlignOver: case TextSymbolAlignment.leftAlignCenter: return "left"; case TextSymbolAlignment.rightAlignOver: case TextSymbolAlignment.rightAlignCenter: case TextSymbolAlignment.rightAlignUnder: return "right"; } return "right"; } public static ISymbol SimpleSymbol(XmlNode axl) { if (axl == null) { return null; } if (axl.Name == "SIMPLEMARKERSYMBOL") { return SimpleMarkerSymbol(axl); } if (axl.Name == "SIMPLELINESYMBOL") { return SimpleLineSymbol(axl); } if (axl.Name == "SIMPLEPOLYGONSYMBOL") { return SimplePolygonSymbol(axl); } if (axl.Name == "TRUETYPEMARKERSYMBOL") { return TrueTypeMarkerSymbol(axl); } if (axl.Name == "TEXTSYMBOL" || axl.Name == "TEXTMARKERSYMBOL") { return SimpleTextSymbol(axl); } if (axl.Name == "RASTERMARKERSYMBOL") { return RasterMarkerSymbol(axl); } return null; } public static string Symbol2AXL(ISymbol symbol, SymbolRotation rotation) { if (symbol == null) { return ""; } if (symbol is SimpleFillSymbol) { return SimpleFillSymbol2AXL(symbol as SimpleFillSymbol, rotation); } if (symbol is HatchSymbol) { return HatchSymbol2AXL(symbol as HatchSymbol, rotation); } if (symbol is SimpleLineSymbol) { return SimpleLineSymbol2AXL(symbol as SimpleLineSymbol, rotation); } if (symbol is SimplePointSymbol) { return SimplePointSymbol2AXL(symbol as SimplePointSymbol, rotation); } if (symbol is SimpleTextSymbol) { return SimpleTextSymbol2AXL(symbol as SimpleTextSymbol, rotation); } if (symbol is TrueTypeMarkerSymbol) { return TrueTypeMarkerSymol2AXL(symbol as TrueTypeMarkerSymbol, rotation); } return ""; } public static IFillSymbol SimplePolygonSymbol(XmlNode axl) { if (axl == null) { return null; } IFillSymbol symbol = null; if (axl.Attributes["filltype"] == null || axl.Attributes["filltype"].Value == "solid" || axl.Attributes["filltype"].Value == "") { symbol = new SimpleFillSymbol(); } else { symbol = new HatchSymbol(); switch (axl.Attributes["filltype"].Value) { case "bdiagonal": ((HatchSymbol)symbol).HatchStyle = HatchStyle.BackwardDiagonal; break; case "fdiagonal": ((HatchSymbol)symbol).HatchStyle = HatchStyle.ForwardDiagonal; break; case "cross": ((HatchSymbol)symbol).HatchStyle = HatchStyle.LargeGrid; break; case "diagcross": ((HatchSymbol)symbol).HatchStyle = HatchStyle.DiagonalCross; break; case "horizontal": ((HatchSymbol)symbol).HatchStyle = HatchStyle.Horizontal; break; case "vertical": ((HatchSymbol)symbol).HatchStyle = HatchStyle.Vertical; break; default: ((HatchSymbol)symbol).HatchStyle = HatchStyle.BackwardDiagonal; break; } } new SimpleFillSymbol(); SimpleLineSymbol lSymbol = null; int A1 = 255, A2 = 255; if (axl.Attributes["filltransparency"] != null) { A1 = (int)(double.Parse(axl.Attributes["filltransparency"].Value.Replace(",", "."), _nhi) * 255.0); if (A1 < 0) { A1 = 0; } if (A1 > 255) { A1 = 255; } } if (axl.Attributes["boundarytransparency"] != null) { A2 = (int)(double.Parse(axl.Attributes["boundarytransparency"].Value.Replace(",", "."), _nhi) * 255.0); if (A1 < 0) { A2 = 0; } if (A1 > 255) { A2 = 255; } } if (axl.Attributes["transparency"] != null) { A1 = A2 = (int)(double.Parse(axl.Attributes["transparency"].Value.Replace(",", "."), _nhi) * 255.0); if (A1 < 0) { A1 = A2 = 0; } if (A1 > 255) { A1 = A2 = 255; } } if (axl.Attributes["fillcolor"] != null) { if (symbol is SimpleFillSymbol) { ((SimpleFillSymbol)symbol).Color = ColorFromRGB(A1, axl.Attributes["fillcolor"].Value); } else if (symbol is HatchSymbol) { ((HatchSymbol)symbol).ForeColor = ColorFromRGB(A1, axl.Attributes["fillcolor"].Value); } } else { if (symbol is SimpleFillSymbol) { ((SimpleFillSymbol)symbol).Color = ArgbColor.FromArgb(A1, ((SimpleFillSymbol)symbol).Color); } else if (symbol is HatchSymbol) { ((HatchSymbol)symbol).ForeColor = ArgbColor.FromArgb(A1, ((HatchSymbol)symbol).ForeColor); } } if (axl.Attributes["boundarycolor"] != null) { if (lSymbol == null) { lSymbol = new SimpleLineSymbol(); } lSymbol.Color = ColorFromRGB(A2, axl.Attributes["boundarycolor"].Value); } else { if (lSymbol == null) { lSymbol = new SimpleLineSymbol(); } lSymbol.Color = ArgbColor.FromArgb(A2, ArgbColor.Black); } if (axl.Attributes["boundarywidth"] != null) { if (lSymbol == null) { lSymbol = new SimpleLineSymbol(); } lSymbol.Width = float.Parse(axl.Attributes["boundarywidth"].Value.Replace(",", "."), _nhi); } if (lSymbol != null) { if (symbol is SimpleFillSymbol) { ((SimpleFillSymbol)symbol).OutlineSymbol = lSymbol; } else if (symbol is HatchSymbol) { ((HatchSymbol)symbol).OutlineSymbol = lSymbol; } } return symbol; } public static SimpleLineSymbol SimpleLineSymbol(XmlNode axl) { if (axl == null) { return null; } SimpleLineSymbol symbol = new SimpleLineSymbol(); int A = 255; if (axl.Attributes["transparency"] != null) { A = (int)(double.Parse(axl.Attributes["transparency"].Value.Replace(",", "."), _nhi) * 255.0); if (A < 0) { A = 0; } if (A > 255) { A = 255; } } if (axl.Attributes["color"] != null) { symbol.Color = ColorFromRGB(A, axl.Attributes["color"].Value); } else if (A != 255) { symbol.Color = ArgbColor.FromArgb(A, symbol.Color); } if (axl.Attributes["width"] != null) { symbol.Width = float.Parse(axl.Attributes["width"].Value.Replace(",", "."), _nhi); } if (axl.Attributes["type"] != null) { switch (axl.Attributes["type"].Value) { case "dash": symbol.DashStyle = LineDashStyle.Dash; break; case "dot": symbol.DashStyle = LineDashStyle.Dot; break; case "dash_dot": symbol.DashStyle = LineDashStyle.DashDot; break; case "dash_dot_dot": symbol.DashStyle = LineDashStyle.DashDotDot; break; } } if (axl.Attributes["antialiasing"] != null && axl.Attributes["antialiasing"].Value.ToLower() == "true") { symbol.Smoothingmode = SymbolSmoothing.AntiAlias; } if (axl.Attributes["captype"] != null) { switch (axl.Attributes["captype"].Value.ToLower()) { case "butt": symbol.LineStartCap = symbol.LineEndCap = LineCap.Flat; break; case "round": symbol.LineStartCap = symbol.LineEndCap = LineCap.Round; break; case "square": symbol.LineStartCap = symbol.LineEndCap = LineCap.Square; break; //case "anchormask": // symbol.LineStartCap = symbol.LineEndCap = LineCap.AnchorMask; // break; //case "arrowanchor": // symbol.LineStartCap = symbol.LineEndCap = LineCap.ArrowAnchor; // break; //case "custom": // symbol.LineStartCap = symbol.LineEndCap = LineCap.Custom; // break; //case "diamondanchor": // symbol.LineStartCap = symbol.LineEndCap = LineCap.DiamondAnchor; // break; //case "noanchor": // symbol.LineStartCap = symbol.LineEndCap = LineCap.NoAnchor; // break; //case "roundanchor": // symbol.LineStartCap = symbol.LineEndCap = LineCap.RoundAnchor; // break; //case "squareanchor": // symbol.LineStartCap = symbol.LineEndCap = LineCap.SquareAnchor; // break; //case "triangle": // symbol.LineStartCap = symbol.LineEndCap = LineCap.Triangle; // break; } } if (axl.Attributes["startcaptype"] != null) { switch (axl.Attributes["startcaptype"].Value.ToLower()) { case "butt": symbol.LineStartCap = LineCap.Flat; break; case "round": symbol.LineStartCap = LineCap.Round; break; case "square": symbol.LineStartCap = LineCap.Square; break; //case "anchormask": // symbol.LineStartCap = LineCap.AnchorMask; // break; //case "arrowanchor": // symbol.LineStartCap = LineCap.ArrowAnchor; // break; //case "custom": // symbol.LineStartCap = LineCap.Custom; // break; //case "diamondanchor": // symbol.LineStartCap = LineCap.DiamondAnchor; // break; //case "noanchor": // symbol.LineStartCap = LineCap.NoAnchor; // break; //case "roundanchor": // symbol.LineStartCap = LineCap.RoundAnchor; // break; //case "squareanchor": // symbol.LineStartCap = LineCap.SquareAnchor; // break; //case "triangle": // symbol.LineStartCap = LineCap.Triangle; // break; } } if (axl.Attributes["endcaptype"] != null) { switch (axl.Attributes["endcaptype"].Value.ToLower()) { case "butt": symbol.LineEndCap = LineCap.Flat; break; case "round": symbol.LineEndCap = LineCap.Round; break; case "square": symbol.LineEndCap = LineCap.Square; break; //case "anchormask": // symbol.LineEndCap = LineCap.AnchorMask; // break; //case "arrowanchor": // symbol.LineEndCap = LineCap.ArrowAnchor; // break; //case "custom": // symbol.LineEndCap = LineCap.Custom; // break; //case "diamondanchor": // symbol.LineEndCap = LineCap.DiamondAnchor; // break; //case "noanchor": // symbol.LineEndCap = LineCap.NoAnchor; // break; //case "roundanchor": // symbol.LineEndCap = LineCap.RoundAnchor; // break; //case "squareanchor": // symbol.LineEndCap = LineCap.SquareAnchor; // break; //case "triangle": // symbol.LineEndCap = LineCap.Triangle; // break; } } return symbol; } public static SimplePointSymbol SimpleMarkerSymbol(XmlNode axl) { if (axl == null) { return null; } SimplePointSymbol symbol = new SimplePointSymbol(); int A = 255, OA = 255; if (axl.Attributes["transparency"] != null) { A = (int)(double.Parse(axl.Attributes["transparency"].Value.Replace(",", "."), _nhi) * 255.0); if (A < 0) { A = 0; } if (A > 255) { A = 255; } OA = A; } if (axl.Attributes["gv_outlinetransparency"] != null) { OA = (int)(double.Parse(axl.Attributes["gv_outlinetransparency"].Value.Replace(",", "."), _nhi) * 255.0); if (OA < 0) { OA = 0; } if (OA > 255) { OA = 255; } } if (axl.Attributes["color"] != null) { symbol.Color = ColorFromRGB(A, axl.Attributes["color"].Value); } else if (A != 255) { symbol.Color = ArgbColor.FromArgb(A, symbol.Color); } if (axl.Attributes["outline"] != null) { symbol.OutlineColor = ColorFromRGB(OA, axl.Attributes["outline"].Value); } else if (A != 255) { symbol.OutlineColor = ArgbColor.FromArgb(A, symbol.OutlineColor); } if (axl.Attributes["width"] != null) { symbol.Size = float.Parse(axl.Attributes["width"].Value.Replace(",", "."), _nhi); } if (axl.Attributes["symbolwidth"] != null) { symbol.SymbolWidth = float.Parse(axl.Attributes["symbolwidth"].Value.Replace(",", "."), _nhi); } if (axl.Attributes["gv_outlinewidth"] != null) { symbol.PenWidth = float.Parse(axl.Attributes["gv_outlinewidth"].Value.Replace(",", "."), _nhi); } if (axl.Attributes["type"] != null) { switch (axl.Attributes["type"].Value.ToString()) { case "cross": symbol.Marker = SimplePointSymbol.MarkerType.Cross; break; case "square": symbol.Marker = SimplePointSymbol.MarkerType.Square; break; case "star": symbol.Marker = SimplePointSymbol.MarkerType.Star; break; case "triangle": symbol.Marker = SimplePointSymbol.MarkerType.Triangle; break; } } return symbol; } public static SimpleTextSymbol SimpleTextSymbol(XmlNode axl) { bool hasAlignment; return SimpleTextSymbol(axl, out hasAlignment); } public static SimpleTextSymbol SimpleTextSymbol(XmlNode axl, out bool hasAlignment) { hasAlignment = false; if (axl == null) { return null; } SimpleTextSymbol symbol = null; int A = 255; if (axl.Attributes["transparency"] != null) { A = (int)(double.Parse(axl.Attributes["transparency"].Value.Replace(",", "."), _nhi) * 255.0); if (A < 0) { A = 0; } if (A > 255) { A = 255; } } if (axl.Attributes["glowing"] != null) { symbol = new GlowingTextSymbol(); ((GlowingTextSymbol)symbol).GlowingColor = ColorFromRGB(A, axl.Attributes["glowing"].Value); if (axl.Attributes["glowingwidth"] != null) { try { ((GlowingTextSymbol)symbol).GlowingWidth = Convert.ToInt32(axl.Attributes["glowingwidth"].Value); } catch { } } if (axl.Attributes["glowing_antialiasing"] != null && axl.Attributes["glowing_antialiasing"].Value.ToLower().Equals("true")) { ((GlowingTextSymbol)symbol).GlowingSmoothingmode = SymbolSmoothing.AntiAlias; } } else { symbol = new SimpleTextSymbol(); } if (axl.Attributes["fontcolor"] != null) { symbol.Color = ColorFromRGB(A, axl.Attributes["fontcolor"].Value); } FontStyle fontstyle = FontStyle.Regular; if (axl.Attributes["fontstyle"] != null) { switch (axl.Attributes["fontstyle"].Value) { case "italicbold": fontstyle |= FontStyle.Italic | FontStyle.Bold; break; case "italic": fontstyle |= FontStyle.Italic; break; case "bold": fontstyle |= FontStyle.Bold; break; case "underline": fontstyle |= FontStyle.Underline; break; } } if (axl.Attributes["font"] != null) { float size = 10; if (axl.Attributes["fontsize"] != null) { size = float.Parse(axl.Attributes["fontsize"].Value.Replace(",", "."), _nhi); } symbol.Font = Current.Engine.CreateFont(axl.Attributes["font"].Value, size, fontstyle); } if (axl.Attributes["angle"] != null) { symbol.Angle = float.Parse(axl.Attributes["angle"].Value.Replace(",", "."), _nhi); } if (axl.Attributes["halignment"] != null && axl.Attributes["valignment"] != null) { hasAlignment = true; string h = axl.Attributes["halignment"].Value; string v = axl.Attributes["valignment"].Value; if (h == "left" && v == "top") { symbol.TextSymbolAlignment = TextSymbolAlignment.leftAlignOver; } if (h == "left" && v == "center") { symbol.TextSymbolAlignment = TextSymbolAlignment.leftAlignCenter; } if (h == "left" && v == "bottom") { symbol.TextSymbolAlignment = TextSymbolAlignment.leftAlignUnder; } if (h == "center" && v == "top") { symbol.TextSymbolAlignment = TextSymbolAlignment.Over; } if (h == "center" && v == "center") { symbol.TextSymbolAlignment = TextSymbolAlignment.Center; } if (h == "center" && v == "bottom") { symbol.TextSymbolAlignment = TextSymbolAlignment.Under; } if (h == "right" && v == "top") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignOver; } if (h == "right" && v == "center") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignCenter; } if (h == "right" && v == "bottom") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignUnder; } } else if (axl.Attributes["halignment"] != null) { hasAlignment = true; string h = axl.Attributes["halignment"].Value; if (h == "left") { symbol.TextSymbolAlignment = TextSymbolAlignment.leftAlignOver; } if (h == "center") { symbol.TextSymbolAlignment = TextSymbolAlignment.Over; } if (h == "right") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignOver; } } else if (axl.Attributes["valignment"] != null) { hasAlignment = true; string v = axl.Attributes["valignment"].Value; if (v == "top") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignOver; } if (v == "center") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignCenter; } if (v == "bottom") { symbol.TextSymbolAlignment = TextSymbolAlignment.rightAlignUnder; } } if (axl.Attributes["antialiasing"] != null && axl.Attributes["antialiasing"].Value.ToLower().Equals("true")) { symbol.Smoothingmode = SymbolSmoothing.AntiAlias; } return symbol; } public static TrueTypeMarkerSymbol TrueTypeMarkerSymbol(XmlNode axl) { if (axl == null) { return null; } TrueTypeMarkerSymbol symbol = new TrueTypeMarkerSymbol(); if (axl.Attributes["fontcolor"] != null) { symbol.Color = ColorFromRGB(255, axl.Attributes["fontcolor"].Value); } if (axl.Attributes["font"] != null) { float size = 10; if (axl.Attributes["fontsize"] != null) { size = float.Parse(axl.Attributes["fontsize"].Value.Replace(",", "."), _nhi); } symbol.Font = Current.Engine.CreateFont(axl.Attributes["font"].Value, size); } if (axl.Attributes["character"] != null) { try { symbol.Charakter = (byte)Convert.ToInt16(axl.Attributes["character"].Value); } catch { } } if (axl.Attributes["angle"] != null) { try { symbol.Angle = float.Parse(axl.Attributes["angle"].Value); } catch { } } if (axl.Attributes["hotspot"] != null) { try { string[] hs = axl.Attributes["hotspot"].Value.Split(','); if (hs.Length == 2) { float hs_x = float.Parse(hs[0], _nhi); float hs_y = float.Parse(hs[1], _nhi); //if (symbol.Angle != 0f) //{ // float x = (float)(hs_x * Math.Cos(symbol.Angle * Math.PI / 180.0) + hs_y * Math.Sin(symbol.Angle * Math.PI / 180.0)); // float y = (float)(-hs_x * Math.Sin(symbol.Angle * Math.PI / 180.0) + hs_y * Math.Cos(symbol.Angle * Math.PI / 180.0)); // hs_x = x; // hs_y = y; //} //symbol.HorizontalOffset = hs_x; //symbol.VerticalOffset = -hs_y; symbol.HorizontalOffset = hs_x; symbol.VerticalOffset = hs_y; } } catch { } } return symbol; } public static RasterMarkerSymbol RasterMarkerSymbol(XmlNode axl) { if (axl == null || axl.Attributes["image"] == null) { return null; } RasterMarkerSymbol symbol = new RasterMarkerSymbol(); symbol.Filename = axl.Attributes["image"].Value; if (axl.Attributes["size"] != null) { string[] xy = axl.Attributes["size"].Value.Split(','); if (xy.Length == 2) { float sizeX, sizeY; if (float.TryParse(xy[0], System.Globalization.NumberStyles.Any, _nhi, out sizeX)) { symbol.SizeX = sizeX; } if (float.TryParse(xy[1], System.Globalization.NumberStyles.Any, _nhi, out sizeY)) { symbol.SizeY = sizeY; } } } return symbol; } private static ArgbColor ColorFromRGB(int A, string col) { string[] rgb = col.Split(','); if (rgb.Length < 3) { return ArgbColor.Transparent; } return ArgbColor.FromArgb(A, Convert.ToInt32(rgb[0]), Convert.ToInt32(rgb[1]), Convert.ToInt32(rgb[2])); } private static double Scale(string scaleString) { if (String.IsNullOrEmpty(scaleString)) { return 0.0; } if (scaleString.Contains(":")) { return double.Parse(scaleString.Split(':')[1].Replace(",", "."), _nhi); } return double.Parse(scaleString.Replace(",", "."), _nhi); } public static IGraphicElement GraphicElement(XmlNode axl) { if (axl == null) { return null; } ISymbol symbol = null; IGeometry geometry = null; foreach (XmlNode node in axl.ChildNodes) { if (node.Name == "POINT" || node.Name == "MULTIPOINT" || node.Name == "POLYLINE" || node.Name == "POLYGON") { geometry = Geometry(node.OuterXml); // manchmal steht symbol auch innerhalb des Points... if (symbol == null) { foreach (XmlNode child in node.ChildNodes) { symbol = SimpleSymbol(child); if (symbol != null) { break; } } } } else if (node.Name == "TEXT" && node.Attributes["coords"] != null && node.Attributes["label"] != null) { double x, y; string[] xy = node.Attributes["coords"].Value.Split(' '); if (xy.Length == 2) { if (double.TryParse(xy[0].Replace(",", "."), NumberStyles.Any, _nhi, out x) && double.TryParse(xy[1].Replace(",", "."), NumberStyles.Any, _nhi, out y)) { geometry = new Point(x, y); } } // manchmal steht symbol auch innerhalb des Points... foreach (XmlNode child in node.ChildNodes) { symbol = SimpleSymbol(child); if (symbol != null) { break; } } if (symbol is ILabel) { ((ILabel)symbol).Text = node.Attributes["label"].Value; ((ILabel)symbol).TextSymbolAlignment = TextSymbolAlignment.leftAlignOver; } } else { symbol = SimpleSymbol(node); } if (geometry != null && symbol != null) { break; } } if (symbol != null && geometry != null) { return new AcetateGraphicElement(symbol, geometry); } return null; } async public static Task<IGraphicElement> GraphicElement(ISymbol symbol, IBufferQueryFilter filter) { if (symbol == null) { return null; } ISpatialFilter sFilter = await BufferQueryFilter.ConvertToSpatialFilter(filter); if (sFilter == null || sFilter.Geometry == null) { return null; } return new AcetateGraphicElement(symbol, sFilter.Geometry); } private class AcetateGraphicElement : IGraphicElement { private ISymbol _symbol; private IGeometry _geometry; public AcetateGraphicElement(ISymbol symbol, IGeometry geometry) { _symbol = symbol; _geometry = geometry; } #region IGraphicElement Member public void Draw(IDisplay display) { if (_symbol == null || _geometry == null) { return; } display.Draw(_symbol, _geometry); } #endregion } private static string CheckEsc(string str) { return str.Replace("&", "&amp;").Replace("\"", "&quot;").Replace("<", "&lt;").Replace(">", "&gt;"); } } public class AXLFromObjectFactory { public static string Renderers(IFeatureLayer layer) { if (layer == null) { return ""; } return ""; } public static string FeatureRenderer(IFeatureRenderer renderer) { if (renderer is SimpleRenderer) { } return ""; } static public string Geometry(IGeometry geom) { return ArcXMLGeometry.Geometry2AXL(geom); } static public string Query(IQueryFilter filter) { if (filter == null) { return ""; } if (filter is ISpatialFilter) { return SpatialQueryToAXL((ISpatialFilter)filter); } else { return QueryToAXL(filter); } } private static string QueryToAXL(IQueryFilter filter) { if (filter == null) { return ""; } try { AXLWriter axl = new AXLWriter(); axl.WriteStartElement("QUERY"); if (filter.SubFields == "" || filter.SubFields == "*") { axl.WriteAttribute("subfields", "#ALL#"); } else { axl.WriteAttribute("subfields", filter.SubFields); } string where = (filter is IRowIDFilter) ? ((IRowIDFilter)filter).RowIDWhereClause : filter.WhereClause; if (where != "") { axl.WriteAttribute("where", where); } if (filter.FeatureSpatialReference != null) { axl.WriteStartElement("FEATURECOORDSYS"); if (filter.FeatureSpatialReference.Name.ToLower().StartsWith("epsg:")) { axl.WriteAttribute("id", filter.FeatureSpatialReference.Name.Split(':')[1]); } else { axl.WriteAttribute("string", gView.Framework.Geometry.SpatialReference.ToESRIWKT(filter.FeatureSpatialReference)); } if (filter.FeatureSpatialReference.Datum != null) { axl.WriteAttribute("datumtransformstring", gView.Framework.Geometry.SpatialReference.ToESRIGeotransWKT(filter.FeatureSpatialReference)); } axl.WriteEndElement(); } axl.WriteEndElement(); // QUERY XmlDocument doc = new XmlDocument(); doc.LoadXml(axl.Request); return doc.SelectSingleNode("//QUERY").OuterXml; } catch { return ""; } } private static string SpatialQueryToAXL(ISpatialFilter filter) { if (filter == null) { return ""; } try { AXLWriter axl = new AXLWriter(); axl.WriteStartElement("SPATIALQUERY"); string where = (filter is IRowIDFilter) ? ((IRowIDFilter)filter).RowIDWhereClause : filter.WhereClause; if (where != "") { if (filter.SubFields == "" || filter.SubFields == "*") { axl.WriteAttribute("subfields", "#ALL#"); } else { axl.WriteAttribute("subfields", filter.SubFields); } axl.WriteAttribute("where", (filter is IRowIDFilter) ? ((IRowIDFilter)filter).RowIDWhereClause : filter.WhereClause); } else { axl.WriteAttribute("subfields", (filter.SubFields == "*") ? "#ALL#" : filter.SubFields); } if (filter.FilterSpatialReference != null || filter.FeatureSpatialReference != null) { if (filter.FilterSpatialReference != null) { axl.WriteStartElement("FILTERCOORDSYS"); if (filter.FilterSpatialReference.Name.ToLower().StartsWith("epsg:")) { axl.WriteAttribute("id", filter.FilterSpatialReference.Name.Split(':')[1]); } else { axl.WriteAttribute("string", gView.Framework.Geometry.SpatialReference.ToESRIWKT(filter.FilterSpatialReference)); } if (filter.FilterSpatialReference.Datum != null) { axl.WriteAttribute("datumtransformstring", gView.Framework.Geometry.SpatialReference.ToESRIGeotransWKT(filter.FilterSpatialReference)); } axl.WriteEndElement(); } if (filter.FeatureSpatialReference != null) { axl.WriteStartElement("FEATURECOORDSYS"); if (filter.FeatureSpatialReference.Name.ToLower().StartsWith("epsg:")) { axl.WriteAttribute("id", filter.FeatureSpatialReference.Name.Split(':')[1]); } else { axl.WriteAttribute("string", gView.Framework.Geometry.SpatialReference.ToESRIWKT(filter.FeatureSpatialReference)); } if (filter.FeatureSpatialReference.Datum != null) { axl.WriteAttribute("datumtransformstring", gView.Framework.Geometry.SpatialReference.ToESRIGeotransWKT(filter.FeatureSpatialReference)); } axl.WriteEndElement(); } } else if (filter.FilterSpatialReference != null) { // SPATIALREFERENCE axl.WriteStartElement("SPATIALREFERENCE"); axl.WriteAttribute("name", filter.FilterSpatialReference.Name); axl.WriteAttribute("param", gView.Framework.Geometry.SpatialReference.ToProj4(filter.FilterSpatialReference)); axl.WriteEndElement(); // FILTERCOORDSYS axl.WriteStartElement("FILTERCOORDSYS"); axl.WriteAttribute("string", gView.Framework.Geometry.SpatialReference.ToESRIWKT(filter.FilterSpatialReference)); axl.WriteEndElement(); } if (filter.Geometry != null) { axl.WriteStartElement("SPATIALFILTER"); axl.WriteAttribute("relation", "area_intersection"); axl.WriteRaw(ArcXMLGeometry.Geometry2AXL(filter.Geometry)); axl.WriteEndElement(); // SPATIALFILTER } axl.WriteEndElement(); // SPATIALQUERY XmlDocument doc = new XmlDocument(); doc.LoadXml(axl.Request); return doc.SelectSingleNode("//SPATIALQUERY").OuterXml; } catch { return ""; } } #region Helper Classes private class AXLWriter { protected StringBuilder m_axl; //protected StringWriter m_sw; protected MemoryStream m_ms; protected XmlTextWriter m_xWriter; protected Encoding m_encoding = Encoding.UTF8; public AXLWriter() : this(Encoding.UTF8) { } public AXLWriter(Encoding encoding) { m_axl = new StringBuilder(); //m_sw = new StringWriter(m_axl); m_ms = new MemoryStream(); m_xWriter = new XmlTextWriter(m_ms, m_encoding = encoding); m_xWriter.WriteStartDocument(); } public string Request { get { //m_xWriter.WriteEndDocument(); //m_xWriter.Close(); //m_sw.Close(); //return m_axl.ToString(); m_xWriter.WriteEndDocument(); m_xWriter.Flush(); m_ms.Flush(); m_ms.Position = 0; StreamReader sr = new StreamReader(m_ms); m_axl.Append(sr.ReadToEnd()); sr.Close(); m_ms.Close(); m_xWriter.Close(); return m_axl.ToString(); } } public XmlTextWriter xmlWriter { get { return m_xWriter; } } public void WriteStartElement(string element) { m_xWriter.WriteStartElement(element); } public void WriteEndElement() { m_xWriter.WriteEndElement(); } public void WriteRaw(string raw) { m_xWriter.WriteRaw(raw); } public void WriteAttribute(string tag, string val) { m_xWriter.WriteAttributeString(tag, val); } } #endregion } }
using System.Collections.Generic; using UserService.Model; namespace UserService.Service { public interface IDoctorService { IEnumerable<DoctorAccount> GetBySpecialty(int specialtyId); IEnumerable<DoctorAccount> GetAll(); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using WebQLKhoaHoc; using WebQLKhoaHoc.Models; namespace WebQLKhoaHoc.Controllers { [CustomizeAuthorize(Roles = "1")] public class AdminDonViChuTriController : Controller { private QLKhoaHocEntities db = new QLKhoaHocEntities(); // GET: AdminDonViChuTri public async Task<ActionResult> Index() { return View(await db.DonViChuTris.ToListAsync()); } // GET: AdminDonViChuTri/Create public ActionResult Create() { return View(); } // POST: AdminDonViChuTri/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "MaDVChuTri,TenDVChuTri,DiaChi")] DonViChuTri donViChuTri) { if (ModelState.IsValid) { db.DonViChuTris.Add(donViChuTri); await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(donViChuTri); } // GET: AdminDonViChuTri/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } DonViChuTri donViChuTri = await db.DonViChuTris.FindAsync(id); if (donViChuTri == null) { return HttpNotFound(); } return View(donViChuTri); } // POST: AdminDonViChuTri/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "MaDVChuTri,TenDVChuTri,DiaChi")] DonViChuTri donViChuTri) { if (ModelState.IsValid) { db.Entry(donViChuTri).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(donViChuTri); } // GET: AdminDonViChuTri/Delete/5 public async Task<ActionResult> Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } DonViChuTri donViChuTri = await db.DonViChuTris.FindAsync(id); if (donViChuTri == null) { return HttpNotFound(); } return View(donViChuTri); } // POST: AdminDonViChuTri/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(int id) { DonViChuTri donViChuTri = await db.DonViChuTris.FindAsync(id); List<DeTai> deTai = await db.DeTais.Where(p=>p.MaDVChuTri == donViChuTri.MaDVChuTri).ToListAsync(); foreach(var detai in deTai) { detai.DonViChuTri = null; } db.DonViChuTris.Remove(donViChuTri); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using ExitGames.Client.Photon; using Photon.Pun; using Photon.Realtime; using UnityEngine; public class Collision_Detect : MonoBehaviourPun { private Rigidbody thisBody; private AbilityChargeMeter chargeMeter; private PhotonView pView; private Car thisCar; private bool isHeavy = false; void Start() { pView = GetComponent<PhotonView>(); thisBody = GetComponent<Rigidbody>(); chargeMeter = GameObject.FindGameObjectWithTag("ChargeMeter").GetComponent<AbilityChargeMeter>(); int carChoice = (int)PhotonNetwork.LocalPlayer.CustomProperties["carChoice"]; if(carChoice < 2) { isHeavy = true; } thisCar = this.GetComponent<Car>(); } void OnCollisionEnter(Collision col) //when rigidbody collides with rigidbody { if (col.gameObject.tag.Equals("ThickCar") || col.gameObject.tag.Equals("ThinCar"))// if the hit rigidbody has component <Car> script { if (col.relativeVelocity.magnitude > 15 && pView.IsMine) { if ((thisBody.velocity.magnitude > col.rigidbody.velocity.magnitude) || (isHeavy)) { chargeMeter.AddCharge(col.relativeVelocity.magnitude); } } // if thisCar's <Car> script hasBomb = true, and it's held it for 2+ seconds, and it has collided with another rigidbody with <Car> script if (thisCar.hasBomb && (thisCar.timeHeld >= 2)) { Car hitCar = col.collider.GetComponent<Car>(); if (!hitCar.dead && World.currentWorld.playerList.Count > 1 && pView.IsMine) { byte evCode = 1; // Custom Event 1: Used as "CarCollision" event object[] content = new object[] { (short)this.gameObject.GetPhotonView().ViewID, (short)col.gameObject.GetPhotonView().ViewID }; // Names of both cars in collision RaiseEventOptions raiseEventOptions = new RaiseEventOptions { Receivers = ReceiverGroup.All }; SendOptions sendOptions = new SendOptions { Reliability = true }; PhotonNetwork.RaiseEvent(evCode, content, raiseEventOptions, sendOptions); } } } } }
using FluentValidation.TestHelper; using NUnit.Framework; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; using SFA.DAS.ProviderCommitments.Web.Validators.Cohort; using System; using System.Linq.Expressions; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Validators.Cohort { [TestFixture] public class DetailsViewModelValidatorTests { [TestCase(null, false)] [TestCase(CohortDetailsOptions.Send, true)] [TestCase(CohortDetailsOptions.Approve, true)] public void Validate_Selection_ShouldBeValidated(CohortDetailsOptions? selection, bool expectedValid) { var model = new DetailsViewModel { Selection = selection }; AssertValidationResult(request => request.Selection, model, expectedValid); } private void AssertValidationResult<T>(Expression<Func<DetailsViewModel, T>> property, DetailsViewModel instance, bool expectedValid) { var validator = new DetailsViewModelValidator(); if (expectedValid) { validator.ShouldNotHaveValidationErrorFor(property, instance); } else { validator.ShouldHaveValidationErrorFor(property, instance); } } } }
using System.ComponentModel.DataAnnotations; using Alabo.Web.Mvc.Attributes; namespace Alabo.Industry.Shop.Orders.Dtos { public class OrderToExcel { [Display(Name = "订单号")] [Field(ListShow = true, SortOrder = 1)] public string OrderId { get; set; } [Display(Name = "用户名")] [Field(ListShow = true, SortOrder = 1)] public string UserName { get; set; } [Display(Name = "电话")] [Field(ListShow = true, SortOrder = 1)] public string Mobile { get; set; } [Display(Name = "品名")] [Field(ListShow = true, SortOrder = 1)] public string ProductName { get; set; } [Display(Name = "规格")] [Field(ListShow = true, SortOrder = 1)] public string ProductSku { get; set; } [Display(Name = "单价")] [Field(ListShow = true, SortOrder = 1)] public string Price { get; set; } [Display(Name = "数量")] [Field(ListShow = true, SortOrder = 1)] public string Count { get; set; } [Display(Name = "总价")] [Field(ListShow = true, SortOrder = 1)] public string TotalPrice { get; set; } [Display(Name = "已付金额")] [Field(ListShow = true, SortOrder = 1)] public string PayPrice { get; set; } [Display(Name = "下单时间")] [Field(ListShow = true, SortOrder = 1)] public string CreateTime { get; set; } [Display(Name = "支付时间")] [Field(ListShow = true, SortOrder = 1)] public string PayTime { get; set; } [Display(Name = "支付方式")] [Field(ListShow = true, SortOrder = 1)] public string PayType { get; set; } [Display(Name = "支付状态")] [Field(ListShow = true, SortOrder = 1)] public string PayStatus { get; set; } [Display(Name = "订单状态")] [Field(ListShow = true, SortOrder = 1)] public string OrderStatus { get; set; } } }
using System; using AppKit; using Foundation; using ResilienceClasses; using System.Collections.Generic; namespace ManageNonLoanCashflows { public partial class ViewController : NSViewController { public clsCashflow.Type typeChosen; public NonLoanCashflowDataSource dataSource = new NonLoanCashflowDataSource(); public bool showExpired = false; public bool showActualOnly = true; public bool validIDEntered = false; private List<int> entityIndexToID = new List<int>(); private int entityID = -1; public ViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Do any additional setup after loading the view. this.InitializeValues(); this.TypePopUpButton.RemoveAllItems(); List<string> typeList = new List<string>(); foreach (clsCashflow.Type t in Enum.GetValues(typeof(clsCashflow.Type))) { if ((t == clsCashflow.Type.ManagementFee) || (t == clsCashflow.Type.AccountingFees) || (t == clsCashflow.Type.BankFees) || (t == clsCashflow.Type.CapitalCall) || (t == clsCashflow.Type.CatchUp) || (t == clsCashflow.Type.Distribution) || // (t == clsCashflow.Type.InterestAdditional) || (t == clsCashflow.Type.LegalFees) || (t == clsCashflow.Type.ManagementFee) || (t == clsCashflow.Type.Misc) || (t == clsCashflow.Type.PromoteFee)) typeList.Add(t.ToString()); } typeList.Sort(); foreach (string s in typeList) this.TypePopUpButton.AddItem(s); this.CashflowsTableView.Delegate = new NonLoanCashflowTableViewDelegate(this.dataSource); this.CashflowsTableView.TableColumns()[0].Title = "ID"; this.CashflowsTableView.TableColumns()[0].Width = 60; this.CashflowsTableView.TableColumns()[1].Title = "PayDate"; this.CashflowsTableView.TableColumns()[1].Width = 60; this.CashflowsTableView.TableColumns()[2].Title = "RecDate"; this.CashflowsTableView.TableColumns()[2].Width = 60; this.CashflowsTableView.TableColumns()[3].Title = "Amount"; this.CashflowsTableView.TableColumns()[3].Width = 80; this.CashflowsTableView.TableColumns()[4].Title = "Type"; this.CashflowsTableView.TableColumns()[4].Width = 80; this.CashflowsTableView.TableColumns()[5].Title = "Actual"; this.CashflowsTableView.TableColumns()[5].Width = 40; this.CashflowsTableView.TableColumns()[6].Title = "DelDate"; this.CashflowsTableView.TableColumns()[6].Width = 60; this.CashflowsTableView.TableColumns()[7].Title = "Comment"; this.CashflowsTableView.TableColumns()[7].Width = 200; // this.CashflowsTableView.RemoveColumn(this.CashflowsTableView.TableColumns()[0]); this.CashflowsTableView.DataSource = this.dataSource; clsCSVTable tblLenders = new clsCSVTable(clsEntity.strEntityPath); clsCSVTable tblLoans = new clsCSVTable(clsLoan.strLoanPath); for (int i = 0; i < tblLenders.Length(); i++) { if (tblLoans.Matches(clsLoan.LenderColumn, i.ToString()).Count > 0) { this.EntityPopUpButton.AddItem(tblLenders.Value(i, clsEntity.NameColumn)); this.entityIndexToID.Add(i); } } this.entityID = this.entityIndexToID[0]; this.EntityPopUpButton.SelectItem(1); } partial void TypeChosen(AppKit.NSPopUpButton sender) { this.InitializeValues(); this.RedrawTable(); } public override NSObject RepresentedObject { get { return base.RepresentedObject; } set { base.RepresentedObject = value; // Update the view, if already loaded. } } partial void ShowExpiredCheckBoxPressed(AppKit.NSButton sender) { this.showExpired = !this.showExpired; this.RedrawTable(); } partial void AddButtonPressed(AppKit.NSButton sender) { DateTime dtPay = ((DateTime)this.DatePicker.DateValue).Date; DateTime dtRecord = ((DateTime)this.RecordDateOverridePicker.DateValue).Date; double dAmount = this.AmountTextField.DoubleValue; // VALIDATE ENTRIES if (this.typeChosen == clsCashflow.Type.Unknown) { this.SystemMessageTextField.StringValue = "INVALID CASHFLOW TYPE, UNABLE TO ADD"; } else if (this.entityID < 0) { this.SystemMessageTextField.StringValue = "NO ENTITY SELECTED, UNABLE TO ADD"; } else { // CREATE NEW CASHFLOW clsCashflow cashflow = new clsCashflow(dtPay, dtRecord, System.DateTime.MaxValue, -this.entityID, dAmount, false, this.typeChosen, this.CommentTextField.StringValue); if (dtPay <= System.DateTime.Today.Date) cashflow.MarkActual(System.DateTime.Today.Date); // SAVE TO TABLE cashflow.Save(); this.CashflowIDTextField.IntValue = cashflow.ID(); // UPDATE COMMENT BOX this.SystemMessageTextField.StringValue = "CASHFLOW SAVED."; if ((cashflow.TypeID() == clsCashflow.Type.InterestAdditional) && (cashflow.Amount() < 0D)) this.SystemMessageTextField.StringValue += "\nCheck Amount. Additional Interest is usually >= 0."; else if ((cashflow.TypeID() == clsCashflow.Type.CapitalCall) && (cashflow.Amount() < 0D)) this.SystemMessageTextField.StringValue += "\nCheck Amount. Capital Calls are usually >= 0."; else if ((cashflow.TypeID() == clsCashflow.Type.CatchUp) && (cashflow.Amount() < 0D)) this.SystemMessageTextField.StringValue += "\nCheck Amount. Catchup Payments are usually >= 0."; else if (cashflow.Amount() > 0) this.SystemMessageTextField.StringValue += "\nCheck Amount. Expenses are normally <0."; } RedrawTable(); } partial void CashflowIDEntered(AppKit.NSTextField sender) { clsCashflow cf = new clsCashflow(this.CashflowIDTextField.IntValue); this.DatePicker.DateValue = (NSDate)cf.PayDate().ToUniversalTime(); this.RecordDateOverridePicker.DateValue = (NSDate)cf.RecordDate().ToUniversalTime(); this.AmountTextField.DoubleValue = cf.Amount(); this.TypePopUpButton.SelectItem(cf.TypeID().ToString()); if (this.TypePopUpButton.TitleOfSelectedItem == null) { this.typeChosen = clsCashflow.Type.Unknown; this.SystemMessageTextField.StringValue = "INVALID CASHFLOW TYPE (" + cf.TypeID().ToString() + ")"; this.validIDEntered = false; } else { this.validIDEntered = true; if (cf.Comment() != null) this.CommentTextField.StringValue = cf.Comment(); else this.CommentTextField.StringValue = ""; this.RedrawTable(); } this.ActualTextField.StringValue = "Actual : " + cf.Actual().ToString(); this.RedrawTable(); } partial void ExpireButtonPressed(AppKit.NSButton sender) { if (this.validIDEntered) { clsCashflow cashflow = new clsCashflow(this.CashflowIDTextField.IntValue); if (cashflow.Delete(System.DateTime.Now, true)) { this.SystemMessageTextField.StringValue = "CASHFLOW EXPIRED"; cashflow.Save(); } else { this.SystemMessageTextField.StringValue = "CASHFLOW IS ALREADY ACTUAL, EXPIRE FAILED"; } } RedrawTable(); } partial void RecordDateOverriden(AppKit.NSDatePicker sender) { } partial void ActualCashflowPressed(NSButton sender) { if (this.validIDEntered) { clsCashflow cashflow = new clsCashflow(this.CashflowIDTextField.IntValue); if (cashflow.Comment() != null) this.CommentTextField.StringValue = cashflow.Comment(); else this.CommentTextField.StringValue = ""; if (cashflow.Actual()) { this.SystemMessageTextField.StringValue = "CASHFLOW IS ALREADY ACTUAL"; } else if (cashflow.MarkActual(System.DateTime.Today)) { this.SystemMessageTextField.StringValue = "CASHFLOW MADE ACTUAL"; this.ActualTextField.StringValue = "Actual : " + true.ToString(); cashflow.Save(); } else { this.SystemMessageTextField.StringValue = "CASHFLOW EXPIRED, CAN'T MAKE ACTUAL"; } } RedrawTable(); } partial void EntityChosen(NSPopUpButton sender) { this.entityID = this.entityIndexToID[(int)this.EntityPopUpButton.IndexOfSelectedItem - 1]; RedrawTable(); } partial void TableViewEvent(NSTableView sender) { int selectedRowIndex = (int)this.CashflowsTableView.SelectedRow; if (selectedRowIndex >= 0) { int cashflowID = this.dataSource.Cashflows[selectedRowIndex].ID(); this.CashflowIDTextField.IntValue = cashflowID; this.CashflowIDEntered(this.CashflowIDTextField); } } private void RedrawTable() { clsCSVTable tbl = new clsCSVTable(clsCashflow.strCashflowPath); string selected = this.TypePopUpButton.TitleOfSelectedItem; this.typeChosen = clsCashflow.Type.Unknown; foreach (clsCashflow.Type t in Enum.GetValues(typeof(clsCashflow.Type))) { if (t.ToString() == selected) this.typeChosen = t; } List<int> IDs = tbl.Matches(clsCashflow.TransactionTypeColumn, ((int)this.typeChosen).ToString()); this.dataSource.Cashflows.Clear(); foreach (int id in IDs) { clsCashflow newCf = new clsCashflow(id); if (((this.showExpired) || (newCf.DeleteDate() > System.DateTime.Today.AddYears(50))) && (newCf.LoanID() == -this.entityID)) this.dataSource.Cashflows.Add(newCf); } this.CashflowsTableView.ReloadData(); } private void InitializeValues() { this.DatePicker.DateValue = (NSDate)System.DateTime.Today; this.RecordDateOverridePicker.DateValue = (NSDate)System.DateTime.Today; this.AmountTextField.StringValue = "Amount"; this.CashflowIDTextField.StringValue = "Cashflow ID"; this.CommentTextField.StringValue = "Comment"; this.ActualTextField.StringValue = ""; this.SystemMessageTextField.StringValue = ""; this.validIDEntered = false; } } }
using System.Collections.Generic; using FluentAssertions; using MinistryPlatform.Translation.Extensions; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace MinistryPlatform.Translation.Test.Extensions { public class JsonUnmappedDataExtensionsTest { private IDictionary<string, JToken> _fixture; private const string FieldName = "field1"; private const string FieldValue = "field1 value"; [SetUp] public void SetUp() { _fixture = new Dictionary<string, JToken> { {FieldName, JToken.FromObject(FieldValue)} }; } [Test] public void TestGetUnmappedDataFieldExists() { var field = _fixture.GetUnmappedDataField<string>(FieldName); Assert.IsNotNull(field); Assert.AreEqual(FieldValue, field); } [Test] public void TestGetUnmappedDataFieldDoesNotExist() { var field = _fixture.GetUnmappedDataField<int>(FieldName + "1"); Assert.IsNotNull(field); Assert.AreEqual(default(int), field); } [Test] public void TestGetUnmappedDataFieldNonNullableIsNull() { _fixture = new Dictionary<string, JToken> { {FieldName, JToken.Parse("null")} }; var field = _fixture.GetUnmappedDataField<int>(FieldName); Assert.IsNotNull(field); Assert.AreEqual(default(int), field); } [Test] public void TestGetUnmappedDataFieldNullableIsNull() { _fixture = new Dictionary<string, JToken> { {FieldName, JToken.Parse("null")} }; var field = _fixture.GetUnmappedDataField<int?>(FieldName); Assert.IsNull(field); } [Test] public void TestGetAttribute() { const string prefix = "prefix"; _fixture.Add($"{prefix}_Attribute_Name", JToken.FromObject("attr name")); _fixture.Add($"{prefix}_Attribute_ID", JToken.FromObject(1)); _fixture.Add($"{prefix}_Attribute_Sort_Order", JToken.FromObject(2)); _fixture.Add($"{prefix}_Attribute_Type_Name", JToken.FromObject("attr type name")); _fixture.Add($"{prefix}_Attribute_Type_ID", JToken.FromObject(3)); var attr = _fixture.GetAttribute(prefix); attr.Should().NotBeNull(); attr.Name.Should().Be("attr name"); attr.Id.Should().Be(1); attr.SortOrder.Should().Be(2); attr.Type.Should().NotBeNull(); attr.Type.Name.Should().Be("attr type name"); attr.Type.Id.Should().Be(3); } } }
namespace DealOrNoDeal.ErrorMessages { /// <summary> /// Holds the error messages for the round manager /// Author: Alex DeCesare /// Version: 03-September-2021 /// </summary> public static class RoundManagerErrorMessages { /// <summary> /// The error message that tells the user that they should not set current round to less than one /// </summary> public const string ShouldNotSetCurrentRoundToLessThanOne = "Cannot set the current round to a value less than one"; /// <summary> /// The error message that tells the user that they should not set cases left for current round to less than zero /// </summary> public const string ShouldNotSetCasesLeftForCurrentRoundToLessThanZero = "Cannot set the cases left for the current round to a value less than zero"; /// <summary> /// The error message that tells the user that they should not have a null cases available for each round /// </summary> public const string ShouldNotAllowNullCasesAvailableForEachRound = "Cannot allow a round manager with null cases available for each round"; /// <summary> /// The error messages that tells the user that they should not have an empty cases available for each round /// </summary> public const string ShouldNotAllowEmptyCasesAvailableForEachRound = "Cannot allow a round manager with an empty cases available for each round"; } }
using UnityEngine; using System.Collections; public class PlayerBehaviour : MonoBehaviour { // Use this for initialization void Start () { } static Plane XZPlane = new Plane(Vector3.up, Vector3.zero); public static Vector3 GetMousePositionOnXZPlane() { float distance; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (XZPlane.Raycast(ray, out distance)) { Vector3 hitPoint = ray.GetPoint(distance); //Just double check to ensure the y position is exactly zero hitPoint.y = 0; return hitPoint; } return Vector3.zero; } // Update is called once per frame void FixedUpdate () { //Vector3 pos = GetMousePositionOnXZPlane(); //GetComponent<Rigidbody>().MovePosition(new Vector3(pos.x, 10.0f, pos.z)); Vector3 movedir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); GetComponent<Rigidbody>().AddForce(movedir * 10f); } }
namespace WinAppDriver.UI { using System.Windows.Input; internal interface IKeyboard { bool IsModifierKey(Key key); bool IsModifierKeysPressed(ModifierKeys keys); void ReleaseAllModifierKeys(); void KeyUpOrDown(Key key); void KeyPress(Key key); void Type(char key); } }
using Controller.DrugAndTherapy; using Model.Manager; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace WpfApp1 { /// <summary> /// Interaction logic for CheckingDrug.xaml /// </summary> public partial class CheckingDrug : Window { private Drug drug; private DrugController dc = new DrugController(); public CheckingDrug() { InitializeComponent(); List<Drug> drugs = dc.ViewUnconfirmedDrugs(); drug = drugs[0]; newDrug.Text = drugs[0].Name; List<Ingredient> ingredients = drugs[0].ingredient; List<string> names = new List<string>(); foreach (Ingredient i in ingredients) { names.Add(i.Name); } listBox1.DataContext = names; } private void Button_Click(object sender, RoutedEventArgs e) { var s = new MessageConfirmedDrug(drug); s.Show(); this.Close(); } private void Button_Click_1(object sender, RoutedEventArgs e) { var s = new MessageUnconfirmedDrug(); s.Show(); this.Close(); } private void Button_Click_3(object sender, RoutedEventArgs e) { if (listBox1.SelectedIndex < 0) { MessageBox.Show("Morate selektovati jedan sastojak.", "Upozorenje!", MessageBoxButton.OK, MessageBoxImage.Warning); txtBoxNewDrug.Focus(); return; } List<Ingredient> ingridients = drug.ingredient; foreach (Ingredient i in ingridients) { if (i.Name == listBox1.SelectedItem.ToString()) { i.Name = txtBoxNewDrug.Text; } } drug.ingredient = ingridients; dc.EditUnconfirmedDrug(drug); txtBoxNewDrug.Clear(); List<Drug> drugs = dc.ViewUnconfirmedDrugs(); drug = drugs[0]; newDrug.Text = drugs[0].Name; List<Ingredient> ingredients = drugs[0].ingredient; List<string> names = new List<string>(); foreach (Ingredient i in ingredients) { names.Add(i.Name); } listBox1.DataContext = names; } private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { Window activeWindow = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive); IInputElement focusedControl = FocusManager.GetFocusedElement(activeWindow); if (focusedControl is DependencyObject) { string str = HelpProvider.GetHelpKey((DependencyObject)focusedControl); if (str.Equals("index")) { str = "noviLijek"; } HelpProvider.ShowHelp(str); } else { string str = HelpProvider.GetHelpKey((DependencyObject)activeWindow); HelpProvider.ShowHelp(str); } } private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (listBox1.SelectedIndex >= 0) { txtBoxNewDrug.Text = listBox1.SelectedItem.ToString(); } } } }
using Moudou.CodeGenerator.AbstractionClasses; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace TemplateFramework { public class Global { static void readTemplates() { } private const string ConfigDirectory = "Configs"; private const string ExportDirectory = "Results"; #region "config" //public static void setConfig(string ConfigText) //{ //} //static IEnumerable<string> loadConfigFile() //{ // yield return ""; //} //static IEnumerable<FileSettingText> readConfig(IEnumerable<string> ConfigContent) //{ // var setting = new FileSettingText() // { // Name = "Sample", // SaveTo = "D:\\GoGoGo\\Template\\", // SaveType = SaveType.SourceText, // InjectSettings = new List<InjectSettingText>() // { // new InjectSettingText() // { // Assembly = @"F:\Projects\CodeGenerator\ConsoleApplication1\bin\Debug\SampleTemplateProject.dll", // Templates = // "[ SampleTemplateProject.Template.SampleTemplate1, " + // "SampleTemplateProject.Template.SampleTemplate2 ]", // InputValue = "{ Author: \"Moudou\" }", // InitValue = "{ connectionstring: \"thisisaconnectionstring;gogogogogo;\" }", // Injector = "SampleTemplateProject.Framework.DBInjector" // } // } // }; // var retList = new List<FileSettingText>() { setting }; // return retList; //} #endregion #region "Log" private static void LogError(string msg) { } #endregion #region "reflection" static void reflect(IEnumerable<FileSettingText> configs) { Assembly[] AssembliesLoaded = AppDomain.CurrentDomain.GetAssemblies(); foreach (FileSettingText config in configs) { foreach (InjectSettingText injSetting in config.InjectSettings) { string path = injSetting.Assembly; var assemblies = new Assembly[] { Assembly.LoadFile(path) }; IInjector injectObj = Global.getTypedObject<IInjector>(assemblies, injSetting.Injector); if (injectObj == null) { Global.LogError(""); continue; } IEnumerable<string> aaa = injSetting.Templates.Trim('[', ']').Split(',').Select(obj => obj.Trim()); List<ITemplate> templateList = new List<ITemplate>(); foreach (string templates in aaa) { ITemplate template = Global.getTypedObject<ITemplate>(assemblies, templates); if (template == null) { Global.LogError(""); continue; } templateList.Add(template); } IInitValue initValue = injectObj.GetInitValue(); IInputValue inputValue = injectObj.GetInputValue(); initValue.SetValue(injSetting.InitValue); inputValue.SetValue(injSetting.InputValue); Global.dicTemplates.Add(config.Name, templateList); Global.dicInput.Add(config.Name, inputValue); Global.dicInit.Add(config.Name, initValue); Global.dicInject.Add(config.Name, injectObj); } Global.dicSetting.Add(config.Name, config); } } private static T getTypedObject<T>(Assembly[] AssembliesLoaded, string TypeName) { Type MyType = AssembliesLoaded .Select(assembly => assembly.GetType(TypeName)) .Where(type => type != null) .FirstOrDefault(); if (!typeof(T).IsAssignableFrom(MyType)) return default(T); object obj = Activator.CreateInstance(MyType); if (obj == null) return default(T); return (T)obj; } #endregion #region "Framework" static Dictionary<string, List<ITemplate>> dicTemplates = new Dictionary<string, List<ITemplate>>(); static Dictionary<string, IInputValue> dicInput = new Dictionary<string, IInputValue>(); static Dictionary<string, IInitValue> dicInit = new Dictionary<string, IInitValue>(); static Dictionary<string, IInjector> dicInject = new Dictionary<string, IInjector>(); static Dictionary<string, FileSettingText> dicSetting = new Dictionary<string, FileSettingText>(); //public static void init() //{ // var configContents = Global.loadConfigFile(); // var list = Global.readConfig(configContents); // Global.init(list); //} //public static void init(IEnumerable<string> JsonConfigContent) //{ // var configs = Global.readConfig(JsonConfigContent); // Global.init(configs); //} public static void Init(IEnumerable<FileSettingText> configs) { Global.reflect(configs); } public static void Execute() { foreach (string tmpName in dicInject.Keys) { IInjector owner = dicInject[tmpName]; List<ITemplate> tmpList = dicTemplates[tmpName]; IInputValue inputVO = dicInput[tmpName]; IInitValue initVO = dicInit[tmpName]; FileSettingText setting = dicSetting[tmpName]; owner.Init(initVO); owner.Inject(inputVO, tmpList); foreach (ITemplate iTemp in tmpList) { string FileName = iTemp.GetType().ToString(); string writeContent = iTemp.TransformText(); string directoryPath = setting.SaveTo; string filePath = directoryPath + FileName; if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); File.WriteAllText(filePath, writeContent); } } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IsoCamera : MonoBehaviour { public GameObject CameraTarget; enum CameraStates { Default, RotateMapCCW, //This is to divide the stage into different sections. RotateMapCW, CinematicA, Shoulder, }; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
namespace EventSourcingService.DTO.PatientSchedulingEventDTO { public class SchedulingStepsStatisticDTO { public int NumberOfClosedScheduling { get; set; } public int NumberOfNextSteps { get; set; } public int NumberOfPreviousSteps { get; set; } public int NumberOfSteps { get; set; } } }
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Base; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pe.Stracon.Politicas.Aplicacion.TransferObject.Request.General { /// <summary> /// Representa el objeto de filtro a aplicar a la busqueda de trabajador /// </summary> /// <remarks> /// Creación: GMD 20150327 <br /> /// Modificación: <br /> /// </remarks> public class FiltroTrabajador : Filtro { /// <summary> /// Código de trabajador /// </summary> public string CodigoTrabajador { get; set; } /// <summary> /// Nombre /// </summary> public string Nombre { get; set; } /// <summary> /// Código de identifiación /// </summary> public string CodigoIdentifiacion { get; set; } /// <summary> /// Código tipo documento de identidad /// </summary> public string CodigoTipoDocumentoIdentidad { get; set; } /// <summary> /// Número documento de identidad /// </summary> public string NumeroDocumentoIdentidad { get; set; } } }
using Alabo.Regexs; using Alabo.Validations; using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; namespace Alabo.Data.People.Users.ViewModels { /// <summary> /// Class ViewForgotPassword. /// </summary> public class ViewForgotPassword { /// <summary> /// Gets or sets the password. /// </summary> [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [DataType(DataType.Password)] [StringLength(16, MinimumLength = 6, ErrorMessage = "6~16个字符,为了安全请使用字母加数字组合")] //[RegularExpression("^[@A-Za-z0-9!#$%^&*.~]{6,16}$",ErrorMessage = "6~16个字符,区分大小写,为了安全请使用大小写字母加数字组合")] [Display(Name = "密码")] public string Password { get; set; } /// <summary> /// Gets or sets the email. /// </summary> [Display(Name = "邮箱")] [Remote("verify_email", HttpMethod = "POST", ErrorMessage = ErrorMessage.IsUserd)] //[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [RegularExpression(RegularExpressionHelper.Email, ErrorMessage = ErrorMessage.NotMatchFormat)] public string Email { get; set; } /// <summary> /// Gets or sets the mobile. /// </summary> [Display(Name = "手机")] [Remote("verify_mobile", HttpMethod = "POST", ErrorMessage = ErrorMessage.IsUserd)] //[Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [RegularExpression(RegularExpressionHelper.ChinaMobile, ErrorMessage = ErrorMessage.NotMatchFormat)] public string Mobile { get; set; } /// <summary> /// Gets or sets the mobile verifiy code. /// </summary> [Display(Name = "手机验证码")] public string MobileVerifiyCode { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace App.Data.Models { [Table("session")] public class Session { [Key] [Column("token")] public string SessionToken { get; set; } [Column("user_id")] [ForeignKey(nameof(User))] public int UserId { get; set; } [Column("expires_at")] public DateTime ExpiresAt { get; set; } public virtual User User { get; set; } } }
namespace EqualExperts.Core { public class Validation : IValidation { public bool ValidateInput(int firstNumber, int secondNumber) { return firstNumber <= secondNumber; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using SocialWorld.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialWorld.DataAccess.Concrete.EntityFrameworkCore.Mapping { public class ApplicantMap : IEntityTypeConfiguration<Applicant> { public void Configure(EntityTypeBuilder<Applicant> builder) { builder.HasKey(x => x.Id); builder.Property(X => X.Id).UseIdentityColumn(); builder.HasIndex(I => new { I.JobId, I.UserId }).IsUnique(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyPhoneBook.Core; using Console = System.Console; using MyPhoneBook; namespace ConsoleReference { class Spravochnik { static void Main(string[] args) { var service = new MyPhoneBookService(); service.DeleteDb(); service.AddPerson(new Person { Name = "Dan", PhoneNumber = "889900", }); } } } // int nomer; // string adress; // string name; // public override string ToString() // { // return String.Format("Абонент по имени:{0}\nзарегистрирован за номером:{1}\nпроживает по адресу:{2}", name, nomer, adress); // } // public Spravochnik(int n, string a, string na) // { // this.nomer = n; // this.adress = a; // this.name = na; // } // public bool Findname(Spravochnik sp) // { // return sp.name == name; ; // } // public bool Findnumber(Spravochnik sp) // { // return sp.nomer == nomer; ; // } // public bool Findadrees(Spravochnik sp) // { // return sp.adress == adress; // } // } // class EntryMainPoint // { // public static void Main() // { // string selection; // string command; // int number; // string name; // string adress; // List<Spravochnik> mylist = new List<Spravochnik>(); // Console.WriteLine("Консольный справочник с функциями\nудаление\nдобавления\nпоиска по адресу,имени,номеру"); // while (true) // { // Console.ForegroundColor = ConsoleColor.Red; // Console.WriteLine("\nПродолжить и добавить абонента нажмите p\nВыйти e\n"); // selection = Console.ReadLine(); // switch (selection) // { // case "p": // do // { // Console.WriteLine("\nВведите количество абонентов которое вы собираетесь ввести\n"); // int a = int.Parse(Console.ReadLine()); // for (int i=0; i < a; i++) // { // Console.ForegroundColor = ConsoleColor.White; // Console.WriteLine("\nВведите имя абонента:\n"); // name = Console.ReadLine(); // name = name.ToUpper(); // Console.WriteLine("\nВведите номер абонента:\n"); // number = Convert.ToInt32(Console.ReadLine()); // Console.WriteLine("\nВведите адрес абонента:\n"); // adress = Console.ReadLine(); // adress = adress.ToUpper(); // mylist.Add(new Spravochnik(number, adress, name)); // foreach (object g in mylist) // { // Console.WriteLine("\n"+g); // } // } // Console.ForegroundColor = ConsoleColor.Red; // Console.WriteLine(@"Выберете дальнейшее действие //Найти c возможностью удаления //1: по номеру //2: по адресу //3: по имени //4: добавить еще абонентов //5: Вернуться в главное меню"); // command = Console.ReadLine(); // switch (command) // { // case "1": // Console.WriteLine("Введите номер абонента для поиска:"); // int nomer = int.Parse(Console.ReadLine()); // Spravochnik spp = new Spravochnik(nomer, "", ""); // Spravochnik sp = mylist.Find(new Predicate<Spravochnik>(spp.Findnumber)); // if (sp != null) // { // Console.WriteLine(sp); // Console.WriteLine("Хотите его удалить?y/n"); // string remove = Console.ReadLine(); // switch (remove) // { // case "y": // mylist.RemoveAll(new Predicate<Spravochnik>(spp.Findnumber)); // break; // } // } // else // { // Console.WriteLine("Абонент с таким номером не найден:"); // } // break; // case "2": // Console.WriteLine("Введите адрес абонента для поиска:"); // string adress1 = Console.ReadLine(); // adress1 = adress1.ToUpper(); // Spravochnik spp1 = new Spravochnik(0, adress1, ""); // Spravochnik sp1 = mylist.Find(new Predicate<Spravochnik>(spp1.Findadrees)); // if (sp1 != null) // { // Console.WriteLine(sp1); // Console.WriteLine("Хотите его удалить?y/n"); // string remove = Console.ReadLine(); // switch (remove) // { // case "y": // mylist.RemoveAll(new Predicate<Spravochnik>(spp1.Findnumber)); // break; // } // } // else { // Console.WriteLine("Абонент с таким адресом не найден:"); // } // break; // case "3": // Console.WriteLine("Введите имя для поиска:"); // string names = Console.ReadLine(); // names = names.ToUpper(); // Console.WriteLine(names); // Spravochnik sppp = new Spravochnik(0, "", names); // mylist.FindAll(new Predicate<Spravochnik>(sppp.Findname)).ForEach(delegate (Spravochnik s) { Console.WriteLine(s); }); // if (sppp != null) // { // Console.WriteLine(sppp); // Console.WriteLine("Хотите его удалить?y/n"); // string remove = Console.ReadLine(); // switch (remove) // { // case "y": // mylist.RemoveAll(new Predicate<Spravochnik>(sppp.Findnumber)); // break; // } // } // else // { // Console.WriteLine("Абонент с таким адресом не найден:"); // } // break; // default: // ; // break; // } // } // while (command != "5"); // break; // case "e": // Environment.Exit(0); // break; // } // } //}
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace Quizlet_Server.Apis { [RoutePrefix("api/kiemtras")] public class KiemTrasController : ApiController { [Route("")] [HttpPost] public async Task<IHttpActionResult> CreateLopHocHocSinh(int mangAnhDapAn) { return Ok(); } } }
using Alabo.Data.Things.Goodss.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; namespace Alabo.Data.Things.Goodss.Domain.Repositories { public class GoodsRepository : RepositoryMongo<Goods, long>, IGoodsRepository { public GoodsRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
using ASPNet_MVC_AngularJS_SPA.Models; using ASPNet_MVC_AngularJS_SPA.Services; using ASPNet_MVC_AngularJS_SPA.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ASPNet_MVC_AngularJS_SPA.Controllers { public class UserController : Controller { // // GET: /User/ [HttpPost] public JsonResult UserAuthentication(String email, String password) { UserServices service = new UserServices(); User existinguser= service.UserLogin(email, password); if (existinguser!=null && existinguser.ID>0) { SessionManagement.SetValue("UserId", existinguser.ID.ToString()); SessionManagement.SetValue("UserName", existinguser.Name.ToString()); return Json(existinguser, JsonRequestBehavior.AllowGet); } else { Error err = new Error(); err.ErrorMessage = "Username and password does not match"; return Json(err, JsonRequestBehavior.AllowGet); } } [HttpPost] public JsonResult GetLoggedInUser() { AppUser user = new AppUser(); user.UserId = Convert.ToInt16( SessionManagement.GetValue("UserId")); if (user.UserId > 0) { user.UserName = SessionManagement.GetValue("UserName"); } else { user.UserName = ""; } return Json(user, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult LogoutUser() { SessionManagement.Logout(); return Json("true", JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult NewUser() { return Json("", JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult UserSignUp(User objUser) { if (ModelState.IsValid) { UserServices service = new UserServices(); service.SaveUser(objUser); return Json(objUser, JsonRequestBehavior.AllowGet); } return Json("", JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult AddNewActivity(Activity objActivity) { ActivityServices service = new ActivityServices(); if (ModelState.IsValid) { int loggedInUser = Convert.ToInt16( SessionManagement.GetValue("UserId")); objActivity.UserId = loggedInUser; service.SaveActivity(objActivity); return Json(objActivity, JsonRequestBehavior.AllowGet); } return Json("", JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult GetActivities() { ActivityServices service = new ActivityServices(); int loggedInUser =Convert.ToInt16(SessionManagement.GetValue("UserId")); if (loggedInUser > 0) { return Json(service.GetAllActivities(loggedInUser), JsonRequestBehavior.AllowGet); } else { return Json("", JsonRequestBehavior.AllowGet); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SMG.Common.Conditions { public class AnyCondition : Condition { public override string ToString() { return "ANY"; } public override IGate Decompose(ConditionMode mode) { return Gate.Constant(true); } } }
using PropertyToken = Serilog.Parsing.PropertyToken; namespace Serilog.Tests.Parsing; public class MessageTemplateParserTests { static MessageTemplateToken[] Parse(string messageTemplate) { return new MessageTemplateParser().Parse(messageTemplate).Tokens.ToArray(); } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local static void AssertParsedAs(string message, params MessageTemplateToken[] messageTemplateTokens) { var parsed = Parse(message); Assert.Equal( parsed, messageTemplateTokens); } [Fact] public void MessageTemplateIsRequired() { Assert.Throws<ArgumentNullException>(() => Parse(null!)); } [Fact] public void AnEmptyMessageIsASingleTextToken() { var ts = Parse(""); var mt = Assert.Single(ts); var tt = Assert.IsType<TextToken>(mt); Assert.Equal("", tt.Text); Assert.Equal("", tt.ToString()); Assert.Equal(0, tt.Length); } [Fact] public void AnEmptyPropertyIsIsParsedAsText() { var ts = Parse("{}"); var mt = Assert.Single(ts); var tt = Assert.IsType<TextToken>(mt); Assert.Equal("{}", tt.Text); Assert.Equal("{}", tt.ToString()); Assert.Equal(2, tt.Length); } [Fact] public void AMessageWithoutPropertiesIsASingleTextToken() { AssertParsedAs("Hello, world!", new TextToken("Hello, world!")); } [Fact] public void AMessageWithPropertyOnlyIsASinglePropertyToken() { AssertParsedAs("{Hello}", new PropertyToken("Hello", "{Hello}")); } [Fact] public void DoubledLeftBracketsAreParsedAsASingleBracket() { AssertParsedAs("{{ Hi! }", new TextToken("{ Hi! }")); } [Fact] public void DoubledLeftBracketsAreParsedAsASingleBracketInsideText() { AssertParsedAs("Well, {{ Hi!", new TextToken("Well, { Hi!")); AssertParsedAs("Hello, {{worl@d}!", new TextToken("Hello, {worl@d}!")); } [Fact] public void DoubledRightBracketsAreParsedAsASingleBracket() { AssertParsedAs("Nice }}-: mo", new TextToken("Nice }-: mo")); } [Fact] public void DoubledRightBracketsAfterOneLeftIsParsedAPropertyTokenAndATextToken() { AssertParsedAs("{World}}!", new PropertyToken("World", "{World}"), new TextToken("}!")); AssertParsedAs("Hello, {World}}!", new TextToken("Hello, "), new PropertyToken("World", "{World}"), new TextToken("}!")); } [Fact] public void DoubledBracketsAreParsedAsASingleBracket() { AssertParsedAs("{{Hi}}", new TextToken("{Hi}")); AssertParsedAs("Hello, {{worl@d}}!", new TextToken("Hello, {worl@d}!")); } [Fact] public void AMalformedPropertyTagIsParsedAsText() { AssertParsedAs("{0 space}", new TextToken("{0 space}")); AssertParsedAs("{0 space", new TextToken("{0 space")); AssertParsedAs("{0_space", new TextToken("{0_space")); } [Fact] public void AMalformedPropertyTagIsParsedAsText2() { AssertParsedAs("{0_{{space}", new TextToken("{0_{{space}")); AssertParsedAs("{0_{{space", new TextToken("{0_{{space")); } [Fact] public void AMalformedPropertyTagIsParsedAsText3() { AssertParsedAs("{0_}}space}", new PropertyToken("0_", "{0_}"), new TextToken("}space}")); } [Fact] public void AMessageWithAMalformedPropertyTagIsParsedAsManyTextTokens() { AssertParsedAs("Hello, {w@rld}", new TextToken("Hello, "), new TextToken("{w@rld}")); AssertParsedAs("Hello, {w@rld", new TextToken("Hello, "), new TextToken("{w@rld")); AssertParsedAs("Hello, {w{{rld", new TextToken("Hello, "), new TextToken("{w{{rld")); AssertParsedAs("Hello{{, {w{{rld", new TextToken("Hello{, "), new TextToken("{w{{rld")); AssertParsedAs("Hello, {w@rld}, HI!", new TextToken("Hello, "), new TextToken("{w@rld}"), new TextToken(", HI!")); AssertParsedAs("{w@rld} Hi!", new TextToken("{w@rld}"), new TextToken(" Hi!")); AssertParsedAs("{H&llo}, {w@rld}", new TextToken("{H&llo}"), new TextToken(", "), new TextToken("{w@rld}")); } [Fact] public void ASingleIntegerPropertyNameIsParsedAsPositionalProperty() { var parsed = (PropertyToken)Parse("{0}").Single(); Assert.Equal("0", parsed.PropertyName); Assert.Equal("{0}", parsed.RawText); Assert.Equal(parsed.RawText, parsed.ToString()); Assert.True(parsed.IsPositional); } [Fact] public void ManyIntegerPropertyNameIsParsedAsPositionalProperty() { var parsed = Parse("{0}, {1}, {2}"); var prop1 = (PropertyToken)parsed[0]; Assert.Equal("0", prop1.PropertyName); Assert.Equal("{0}", prop1.RawText); Assert.True(prop1.IsPositional); Assert.Equal(3, prop1.Length); var prop2 = (TextToken)parsed[1]; Assert.Equal(", ", prop2.Text); Assert.Equal(2, prop2.Length); var prop3 = (PropertyToken)parsed[2]; Assert.Equal("1", prop3.PropertyName); Assert.Equal("{1}", prop3.RawText); Assert.True(prop3.IsPositional); Assert.Equal(3, prop3.Length); var prop4 = (TextToken)parsed[3]; Assert.Equal(", ", prop4.Text); Assert.Equal(2, prop4.Length); var prop5 = (PropertyToken)parsed[4]; Assert.Equal("2", prop5.PropertyName); Assert.Equal("{2}", prop5.RawText); Assert.True(prop5.IsPositional); Assert.Equal(3, prop5.Length); } [Fact] public void InvalidIntegerPropertyNameIsParsedAsText() { var parsed = Parse("{-1}{-0}{0}{1}{3.1415}"); var prop1 = (TextToken)parsed[0]; Assert.Equal("{-1}", prop1.Text); var prop2 = (TextToken)parsed[1]; Assert.Equal("{-0}", prop2.Text); var prop3 = (PropertyToken)parsed[2]; Assert.Equal("0", prop3.PropertyName); Assert.Equal("{0}", prop3.RawText); Assert.True(prop3.IsPositional); var prop4 = (PropertyToken)parsed[3]; Assert.Equal("1", prop4.PropertyName); Assert.Equal("{1}", prop4.RawText); Assert.True(prop4.IsPositional); var prop5 = (TextToken)parsed[4]; Assert.Equal("{3.1415}", prop5.Text); } [Fact] public void FormatsCanContainColons() { var parsed = (PropertyToken)Parse("{Time:hh:mm}").Single(); Assert.Equal("hh:mm", parsed.Format); } [Fact] public void APropertyWithValidNameAndInvalidFormatIsParsedAsText() { AssertParsedAs("{Hello:HH$MM}", new TextToken("{Hello:HH$MM}")); } [Fact] public void PropertiesCanHaveLeftAlignment() { var prop1 = (PropertyToken)Parse("{Hello,-5}").Single(); Assert.Equal("Hello", prop1.PropertyName); Assert.Equal("{Hello,-5}", prop1.RawText); Assert.Equal(new Alignment(AlignmentDirection.Left, 5), prop1.Alignment); var prop2 = (PropertyToken)Parse("{Hello,-50}").Single(); Assert.Equal("Hello", prop2.PropertyName); Assert.Equal("{Hello,-50}", prop2.RawText); Assert.Equal(new Alignment(AlignmentDirection.Left, 50), prop2.Alignment); } [Fact] public void PropertiesCanHaveRightAlignment() { var prop1 = (PropertyToken)Parse("{Hello,5}").Single(); Assert.Equal("Hello", prop1.PropertyName); Assert.Equal("{Hello,5}", prop1.RawText); Assert.Equal(new Alignment(AlignmentDirection.Right, 5), prop1.Alignment); var prop2 = (PropertyToken)Parse("{Hello,50}").Single(); Assert.Equal("Hello", prop2.PropertyName); Assert.Equal("{Hello,50}", prop2.RawText); Assert.Equal(new Alignment(AlignmentDirection.Right, 50), prop2.Alignment); } [Fact] public void PropertiesCanHaveAlignmentAndFormat() { var prop1 = (PropertyToken)Parse("{Hello,-5:000}").Single(); Assert.Equal("Hello", prop1.PropertyName); Assert.Equal("{Hello,-5:000}", prop1.RawText); Assert.Equal("000", prop1.Format); Assert.Equal(new Alignment(AlignmentDirection.Left, 5), prop1.Alignment); var prop2 = (PropertyToken)Parse("{Hello,-50:000}").Single(); Assert.Equal("Hello", prop2.PropertyName); Assert.Equal("{Hello,-50:000}", prop2.RawText); Assert.Equal("000", prop2.Format); Assert.Equal(new Alignment(AlignmentDirection.Left, 50), prop2.Alignment); var prop3 = (PropertyToken)Parse("{Hello,5:000}").Single(); Assert.Equal("Hello", prop3.PropertyName); Assert.Equal("{Hello,5:000}", prop3.RawText); Assert.Equal("000", prop3.Format); Assert.Equal(new Alignment(AlignmentDirection.Right, 5), prop3.Alignment); var prop4 = (PropertyToken)Parse("{Hello,50:000}").Single(); Assert.Equal("Hello", prop4.PropertyName); Assert.Equal("{Hello,50:000}", prop4.RawText); Assert.Equal("000", prop4.Format); Assert.Equal(new Alignment(AlignmentDirection.Right, 50), prop4.Alignment); } [Fact] public void FormatInFrontOfAlignmentWillHaveTheAlignmentBeConsideredPartOfTheFormat() { var prop1 = (PropertyToken)Parse("{Hello:000,-5}").Single(); Assert.Equal("Hello", prop1.PropertyName); Assert.Equal("{Hello:000,-5}", prop1.RawText); Assert.Equal("000,-5", prop1.Format); Assert.Null(prop1.Alignment); var prop2 = (PropertyToken)Parse("{Hello:000,-50}").Single(); Assert.Equal("Hello", prop2.PropertyName); Assert.Equal("{Hello:000,-50}", prop2.RawText); Assert.Equal("000,-50", prop2.Format); Assert.Null(prop2.Alignment); var prop3 = (PropertyToken)Parse("{Hello:000,5}").Single(); Assert.Equal("Hello", prop3.PropertyName); Assert.Equal("{Hello:000,5}", prop3.RawText); Assert.Equal("000,5", prop3.Format); Assert.Null(prop3.Alignment); var prop4 = (PropertyToken)Parse("{Hello:000,50}").Single(); Assert.Equal("Hello", prop4.PropertyName); Assert.Equal("{Hello:000,50}", prop4.RawText); Assert.Equal("000,50", prop4.Format); Assert.Null(prop4.Alignment); } [Fact] public void ZeroValuesAlignmentIsParsedAsText() { AssertParsedAs("{Hello,-0}", new TextToken("{Hello,-0}")); AssertParsedAs("{Hello,0}", new TextToken("{Hello,0}")); } [Fact] public void NonNumberAlignmentIsParsedAsText() { AssertParsedAs("{Hello,-aa}", new TextToken("{Hello,-aa}")); AssertParsedAs("{Hello,aa}", new TextToken("{Hello,aa}")); AssertParsedAs("{Hello,-10-1}", new TextToken("{Hello,-10-1}")); AssertParsedAs("{Hello,10-1}", new TextToken("{Hello,10-1}")); } [Fact] public void EmptyAlignmentIsParsedAsText() { AssertParsedAs("{Hello,}", new TextToken("{Hello,}")); AssertParsedAs("{Hello,:format}", new TextToken("{Hello,:format}")); } [Fact] public void MultipleTokensHasCorrectIndexes() { AssertParsedAs("{Greeting}, {Name}!", new PropertyToken("Greeting", "{Greeting}"), new TextToken(", "), new PropertyToken("Name", "{Name}"), new TextToken("!")); } [Fact] public void MissingRightBracketIsParsedAsText() { AssertParsedAs("{Hello", new TextToken("{Hello")); } [Fact] public void DestructureHintIsParsedCorrectly() { var parsed = (PropertyToken)Parse("{@Hello}").Single(); Assert.Equal(Destructuring.Destructure, parsed.Destructuring); } [Fact] public void StringifyHintIsParsedCorrectly() { var parsed = (PropertyToken)Parse("{$Hello}").Single(); Assert.Equal(Destructuring.Stringify, parsed.Destructuring); } [Fact] public void DestructureWithInvalidHintsIsParsedAsText() { AssertParsedAs("{@$}", new TextToken("{@$}")); AssertParsedAs("{$@}", new TextToken("{$@}")); } [Fact] public void DestructuringWithEmptyPropertyNameIsParsedAsText() { AssertParsedAs("{@}", new TextToken("{@}")); AssertParsedAs("{$}", new TextToken("{$}")); } [Fact] public void UnderscoresAreValidInPropertyNames() { AssertParsedAs("{_123_Hello}", new PropertyToken("_123_Hello", "{_123_Hello}")); } [Fact] public void IndexOutOfRangeExceptionBugHasNotRegressed() { var parser = new MessageTemplateParser(); parser.Parse("{,,}"); } [Fact] public void FormatCanContainMultipleSections() { var parsed = (PropertyToken)Parse("{Number:##.0;-##.0;zero}").Single(); Assert.Equal("##.0;-##.0;zero", parsed.Format); } [Fact] public void FormatCanContainPlusSign() { var parsed = (PropertyToken)Parse("{Number:+##.0}").Single(); Assert.Equal("+##.0", parsed.Format); } }
using System; using System.Linq; using ApplicationServices.Command; using ApplicationServices.DTO; using ApplicationServices.Services.Interfaces; using DomainModel.Entity.AmountClasses; using DomainModel.Entity.DomainServices; using DomainModel.Entity.PaymentMethods; using DomainModel.Entity.PaymentProducts; using DomainModel.StatePattern.InstallmentState; using DomainModel.StatePattern.OrderState; using Infrostructure.Enums; using Repository.Repository.Read.Interfaces; namespace ApplicationServices.Services.Implementations { public class PaymentServices : IPaymentServices { #region Constructor readonly IOrderRepositoryRead _orderRepositoryRead; readonly IUserRepositoryRead _userRepositoryRead; private readonly PaymentServiceDom _paymentServiceDom; public PaymentServices(IOrderRepositoryRead orderRepositoryRead, IUserRepositoryRead userRepositoryRead, PaymentServiceDom paymentServiceDom) { _orderRepositoryRead = orderRepositoryRead; _userRepositoryRead = userRepositoryRead; _paymentServiceDom = paymentServiceDom; } #endregion #region Get Payment Method public PaymentMethodDto GetPaymentMethod(Guid userId, PaymentMethodCommand paymentMethodCommand) { if (paymentMethodCommand.PaymentMethodEnum == PaymentMethodEnum.Cash) return new PaymentMethodDto() { PaymentMethod = new CashPaymentMethod() }; var user = _userRepositoryRead.GetUserById(userId); var order = _orderRepositoryRead.GetOrderById(user.OrdersId.LastOrDefault()); var totalPrice = order.Products.Sum(c => c.Price.Value); var installmentPaymentMethod = new InstallmentPaymentMethod(paymentMethodCommand.InstallmentCount, paymentMethodCommand.InstallmentPaymentType); return new PaymentMethodDto() { PaymentMethod = installmentPaymentMethod }; } #endregion #region Get Installments Details public string ValidateForPayment(Guid userId) { var user = _userRepositoryRead.GetUserById(userId); var order = _orderRepositoryRead.GetOrderById(user.OrdersId.LastOrDefault()); var paymentMethod = order.PaymentMethod; var totalPrice = order.Products.Sum(c => c.Price.Value); if (paymentMethod == null) return "\nPayment method not selected"; return paymentMethod is CashPaymentMethod ? "\nCash payment method selected\nTotal Price is : " + totalPrice : null; } public PaymentDto GetInstallmentPaymentDetails(Guid userId) { var user = _userRepositoryRead.GetUserById(userId); var order = _orderRepositoryRead.GetOrderById(user.OrdersId.LastOrDefault()); var payment = order.Payment; if (payment != null) { var installmentPayment = (InstallmentPayment)payment; var installments = installmentPayment.Installments.ToList(); var totalPriceForShow = new Amount(installments.Sum(c => ((c.InstallmentAmount + c.Comision) + c.Penalty).Value)); totalPriceForShow += installmentPayment.Cash ?? new Amount(0); return new PaymentDto() { Installments = installments, Cash = installmentPayment.Cash, TotalPrice = totalPriceForShow }; } else { var totalPrice = new Amount(order.Products.Sum(c => c.Price.Value)); var installmentPaymentMethod = (InstallmentPaymentMethod)order.PaymentMethod; var installmentPayment = new InstallmentPayment(_paymentServiceDom); installmentPayment.CreateInstallments(totalPrice, installmentPaymentMethod.InstallmentCount, installmentPaymentMethod.InstallmentPaymentType); var installments = installmentPayment.Installments.ToList(); var totalPriceForShow = new Amount(installments.Sum(c => ((c.InstallmentAmount + c.Comision) + c.Penalty).Value)); totalPriceForShow += installmentPayment.Cash ?? new Amount(0); return new PaymentDto() { Installments = installments, Cash = installmentPayment.Cash, TotalPrice = totalPriceForShow }; } } #endregion #region Payment Of Installments public string ValidateForInstallment(Guid userId) { var user = _userRepositoryRead.GetUserById(userId); var order = _orderRepositoryRead.GetOrderById(user.OrdersId.LastOrDefault()); var paymentMethod = order.PaymentMethod; var payment = order.Payment; if (paymentMethod == null) return "payment method not selected!"; if (paymentMethod is CashPaymentMethod) return "Cash Payment method selected!"; if (payment == null) return "Please finalize your order"; return null; } public InstallmentDto PaymentOfInstallments(Guid userId) { var user = _userRepositoryRead.GetUserById(userId); var order = _orderRepositoryRead.GetOrderById(user.OrdersId.LastOrDefault()); var payment = order.Payment; var installmentPayment = (InstallmentPayment)payment; var installmentForPayment = installmentPayment.Installments.Where(c => c.CurrentState is not Paid).ToList().First(); installmentForPayment.SetPenalty(); return new InstallmentDto() { Installment = installmentForPayment, InstallmentPayment = installmentPayment }; } #endregion } }
using UnityEngine; using System.Collections; public static class ConfigParseUtil { public const char DEFAULT_SPLITER = ','; public const char DEFAULT_APLITER2 = ';'; public static int[] ParseIntArray(string str, char spliter = DEFAULT_SPLITER) { if (string.IsNullOrEmpty(str)) return null; string[] strArray = str.Split(spliter); int[] intArray = new int[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { intArray[i] = int.Parse(strArray[i]); } return intArray; } public static float[] ParseFloatArray(string str, char spliter = DEFAULT_SPLITER) { if (string.IsNullOrEmpty(str)) return null; string[] strArray = str.Split(spliter); float[] floatArray = new float[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { floatArray[i] = float.Parse(strArray[i]); } return floatArray; } public static Vector3 ParseVec3(string str, char spliter = DEFAULT_SPLITER) { if (string.IsNullOrEmpty(str)) return Vector3.zero; string[] strArray = str.Split(spliter); Vector3 vec3 = Vector3.zero; for (int i = 0; i < strArray.Length; i++) { switch (i) { case 0: vec3.x = float.Parse(strArray[i]); break; case 1: vec3.y = float.Parse(strArray[i]); break; case 2: vec3.z = float.Parse(strArray[i]); break; default: break; } } return vec3; } public static Vector3[] ParseVec3Array(string str, char spliter = DEFAULT_SPLITER, char spliter2 = DEFAULT_APLITER2) { if (string.IsNullOrEmpty(str)) return null; string[] strArray = str.Split(spliter2); Vector3[] vec3 = new Vector3[strArray.Length]; for (int i = 0; i < strArray.Length; i++) { vec3[i] = ParseVec3(strArray[i]); } return vec3; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CarTransparency : MonoBehaviour { [SerializeField] private MeshRenderer[] carPartRenderers = null; [SerializeField] private Renderer[] fireRenderers = new Renderer[4]; private MaterialPropertyBlock _propBlock; private Color[] fireColors; private float ditherAmount = 2; private Car thisCar; private bool faded = false; void Start() { thisCar = this.GetComponent<Car>(); fireColors = new Color[fireRenderers.Length]; _propBlock = new MaterialPropertyBlock(); for (int i = 0; i < fireRenderers.Length; i++) { fireColors[i] = fireRenderers[i].material.color; } } void Update() { // distance between car and camera float distance = Vector3.Distance(transform.position, Camera.main.transform.position); // when below certain distance start to dither if (distance <= 20) { ditherAmount = Mathf.Clamp((distance / 10) + 0.15f, 1.125f, 3f); foreach (MeshRenderer m in carPartRenderers) { m.material.SetFloat("_DitherAmount", ditherAmount); } if (thisCar.hasBomb) { float fadeAmount = Mathf.Clamp((distance / 10) - 0.4f, 0f, 1f); faded = true; for (int i = 0; i < fireRenderers.Length; i++) { // Get the current value of the material properties in the renderer. fireRenderers[i].GetPropertyBlock(_propBlock); // Assign our new value. _propBlock.SetColor("_BaseColor", new Color(fireColors[i].r, fireColors[i].g, fireColors[i].b, fadeAmount)); // Apply the edited values to the renderer. fireRenderers[i].SetPropertyBlock(_propBlock); } } } else if(ditherAmount < 2 || faded) { foreach (MeshRenderer m in carPartRenderers) { m.material.SetFloat("_DitherAmount", 2f); } ditherAmount = 2; if (thisCar.hasBomb) { for (int i = 0; i < fireRenderers.Length; i++) { // Get the current value of the material properties in the renderer. fireRenderers[i].GetPropertyBlock(_propBlock); // Assign our new value. _propBlock.SetColor("_BaseColor", new Color(fireColors[i].r, fireColors[i].g, fireColors[i].b, 1)); // Apply the edited values to the renderer. fireRenderers[i].SetPropertyBlock(_propBlock); } faded = false; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PIBP { public partial class Menu : Form { public Menu() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Clanovi c1 = new Clanovi(); c1.Show(); } private void button7_Click(object sender, EventArgs e) { Environment.Exit(0); } private void button6_Click(object sender, EventArgs e) { Treneri t1 = new Treneri(); t1.Show(); } private void button2_Click(object sender, EventArgs e) { Treninzi t2 = new Treninzi(); t2.Show(); } private void button3_Click(object sender, EventArgs e) { Evidencija e1 = new Evidencija(); e1.Show(); } private void button5_Click(object sender, EventArgs e) { Usluge u1 = new Usluge(); u1.Show(); } private void button4_Click(object sender, EventArgs e) { Clanarine c11 = new Clanarine(); c11.Show(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Data; using System.Globalization; using System.Collections.ObjectModel; using GeoSearch.CSWQueryServiceReference; namespace GeoSearch { public partial class SBAQuickSearchPanel : UserControl { public SBAQuickSearchPanel() { InitializeComponent(); ObservableCollection<SBAVocabularyTree> list = SBAVocabularyTree.getSBAVocabularyList(); TreeView_SBAVocabulary.ItemsSource = list; } private void HyperlinkButton_Click(object sender, RoutedEventArgs e) { TreeViewItem tvi = TreeView_SBAVocabulary.GetSelectedContainer(); SBAVocabularyTree current = tvi.Header as SBAVocabularyTree; SBAVocabulary vocabulary = SBAVocabularyTree.createSBAVocabularyFromTreeNode(current); HyperlinkButton button = sender as HyperlinkButton; string id = button.Tag as string; RecordsSearchFunctions.cannotStartSearchYet = true; RecordsSearchFunctions sf = new RecordsSearchFunctions(); sf.BrowseBySBA_Using_WCFService(vocabulary, ConstantCollection.startPosition, ConstantCollection.maxRecords); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace LivrariaWEB.Models.ViewModels { public class FiltroLivroViewModel { public int? ISBN { get; set; } public string Autor { get; set; } public string Nome { get; set; } public decimal Preco { get; set; } public string Data_Publicacao { get; set; } } }
using System.Linq; using ServiceDesk.Infrastructure; using ServiceDesk.Ticketing.Domain.CategoryAggregate; namespace ServiceDesk.Ticketing.DataAccess.Repositories { public class CategoryRepository : RepositoryBase<Category>, ICategoryRepository { private readonly TicketingDbContext _context; public CategoryRepository(TicketingDbContext context, IBus bus) : base(context, bus) { _context = context; } public Category GetByName(string name) { return _context.Categories.First(c=>c.Name == name).ToCategory(); } protected override void AddNew(Category aggregate) { _context.Categories.Add(aggregate.State); } } }
namespace VnStyle.Services.Data.Domain { public class ArticleLanguage { public long Id { get; set; } public string HeadLine { get; set; } public string Content { get; set; } public string Extract { get; set; } public string LanguageId { get; set; } public int MetaTagId { get; set; } public virtual MetaTag MetaTag { get; set; } public int ArticleId { get; set; } public virtual Article Article { get; set; } } }
using System; using System.IO; using System.Linq; namespace Nono.Engine.IO { public class NonFileReader : IDisposable { private readonly string _name; private Stream? _stream; private bool disposedValue = false; public NonFileReader(FileStream stream) : this(stream.Name, stream) { } public NonFileReader(string name, Stream stream) { _name = name; _stream = stream; } public Nonogram Read() { if (_stream == null) throw new ObjectDisposedException(nameof(_stream)); _stream.Position = 0; int height = 0; int width = 0; int[][]? rows = null; int[][]? columns = null; using (var reader = new StreamReader(_stream)) { string line; do { line = reader.ReadLine(); if (line == null) break; var splits = line.Split(" "); switch (splits.FirstOrDefault()) { case "width": width = int.Parse(splits[1]); break; case "height": height = int.Parse(splits[1]); break; case "columns": columns = ReadNumberHints(reader, width); break; case "rows": rows = ReadNumberHints(reader, height); break; default: continue; } } while (true); return new Nonogram(rows!, columns!, _name); } } private int[][] ReadNumberHints(StreamReader reader, int height) { var list = new int[height][]; for (var i = 0; i < height; i++) { var line = reader.ReadLine(); list[i] = line.Split(",").Select(x => int.Parse(x)).ToArray(); } return list; } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _stream?.Dispose(); } _stream = null; disposedValue = true; } } public void Dispose() { Dispose(true); } } }
using System.Collections.Generic; namespace Alabo.UI.Design.AutoReports.Dtos { /// <summary> /// 表格 /// </summary> public class SumReportTableItems { /// <summary> /// 当前页记录数 /// </summary> public long CurrentSize { get; set; } /// <summary> /// 总记录数 private /// </summary> public long TotalCount { get; set; } /// <summary> /// 当前页 private /// </summary> public long PageIndex { get; set; } /// <summary> /// 每页记录数 private /// </summary> public long PageSize { get; set; } /// <summary> /// 总页数 /// </summary> public long PageCount { get; set; } /// <summary> /// 表格列 /// </summary> public List<SumColumns> Columns { get; set; } /// <summary> /// 表格行 /// </summary> public List<object> Rows { get; set; } } /// <summary> /// 列 /// </summary> public class SumColumns { public string name { get; set; } public string type { get; set; } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using Erlang.NET; namespace Spring.Erlang { /// <summary> /// Exception thrown when an 'error' is received from an Erlang RPC call. /// </summary> /// <author>Mark Pollack</author> public class ErlangErrorRpcException : OtpErlangException { private OtpErlangTuple reasonTuple; public ErlangErrorRpcException(string reason): base(reason) { } public ErlangErrorRpcException(OtpErlangTuple tuple) : base(tuple.ToString()) { this.reasonTuple = tuple; } public OtpErlangTuple ReasonTuple { get { return reasonTuple; } } } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.State.Example1 { public abstract class BaseState { protected Player player; protected List<string> playlist; protected int currentPlayingIndex = -1; public BaseState(BaseState state) : this(state.player, state.playlist) { currentPlayingIndex = state.currentPlayingIndex; } public BaseState(Player player, List<string> playlist) { this.player = player; this.playlist = playlist; } public abstract void Play(); public abstract void Next(); public abstract void Previous(); public abstract void Lock(); int Index { get { return currentPlayingIndex % playlist.Count; } } protected void NextMusic() { currentPlayingIndex++; player.CurrentMusicName = playlist[Index]; } protected void PreviousMusic() { currentPlayingIndex--; player.CurrentMusicName = playlist[Index]; } } }
using buildingEnergyLoss.Model; namespace buildingEnergyLoss { public class Floor : Construction { public Floor(double lengthA, double lengthB, MinimalOutdoorTemperature minimalOutdoorTemperature, TemperatureIndoor temperatureIndoor) : base(lengthA, lengthB, minimalOutdoorTemperature, temperatureIndoor) { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Rwd.Framework.Obsolete.SuretyGroup { public static class Cryptography { private static string _key = "&%#@?,:*"; // Encrypt the text public static string EncryptText(string strText) { if (string.IsNullOrEmpty(strText)) return string.Empty; else return Encrypt(strText, _key); } //Decrypt the text public static string DecryptText(string strText) { if (string.IsNullOrEmpty(strText)) return string.Empty; else return Decrypt(strText, _key); } //The function used to encrypt the text private static string Encrypt(string strText, string strEncrKey) { byte[] byKey = { }; byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef }; try { byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey); var des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(strText); var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { return ex.Message; } } //The function used to decrypt the text private static string Decrypt(string strText, string sDecrKey) { if (strText == null) return string.Empty; byte[] byKey = { }; byte[] iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef }; var inputByteArray = new byte[strText.Length + 1]; try { byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey); var des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); var encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray()); } catch (Exception ex) { return ex.Message; } } } }
using System; using System.Threading; using System.Threading.Tasks; namespace Marten.Services { public class FetchResult<T> { public FetchResult(T document, string json) { Document = document; Json = json; } public T Document { get; } public string Json { get; } } public interface IIdentityMap { T Get<T>(object id, Func<FetchResult<T>> result) where T : class; Task<T> GetAsync<T>(object id, Func<CancellationToken, Task<FetchResult<T>>> result, CancellationToken token = default(CancellationToken)) where T : class; T Get<T>(object id, string json) where T : class; T Get<T>(object id, Type concreteType, string json) where T : class; void Remove<T>(object id); void Store<T>(object id, T entity); bool Has<T>(object id); T Retrieve<T>(object id) where T : class; } }
using EduHome.Models.Base; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EduHome.Models.Entity { public class EventSpeaker:BaseEntity { public Event Event { get; set; } public int? EventId { get; set; } public Speaker Speaker { get; set; } public int? SpeakerId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MGO.Models { public partial class CommissionsReport { public string Employee_Name { get; set; } public float? Employee_Commission { get; set; } public int Employee_Qty_Sold { get; set; } public decimal Employee_Sales { get; set; } public float? Employee_Commission_Total { get; set; } static MGO_Entities MGO_Entity = new MGO_Entities(); public static IEnumerable<CommissionsReport> GetCommissionsReport() { var result = from sale in MGO_Entity.Sales join employee in MGO_Entity.Employees on sale.Emp_ID equals employee.Emp_ID join salesItem in MGO_Entity.SaleItems on sale.Sale_Num equals salesItem.Sale_Num join item in MGO_Entity.Items on salesItem.SKU equals item.SKU group sale by sale.Emp_ID into employee_sales select new CommissionsReport() { Employee_Name = employee_sales.FirstOrDefault().Employee.Emp_FName + " " + employee_sales.FirstOrDefault().Employee.Emp_LName, Employee_Commission = employee_sales.FirstOrDefault().Employee.Emp_Commission, Employee_Qty_Sold = employee_sales.Count(), Employee_Sales = employee_sales.Sum(s => s.SaleItems.FirstOrDefault().SI_Qty_Sold * s.SaleItems.FirstOrDefault().Item.Item_Price), Employee_Commission_Total = (float?)employee_sales.Sum(s => s.SaleItems.FirstOrDefault().SI_Qty_Sold * s.SaleItems.FirstOrDefault().Item.Item_Price) * employee_sales.FirstOrDefault().Employee.Emp_Commission }; return result; } } }
// VBConversions Note: VB project level imports using System.Collections.Generic; using System; using System.Linq; using System.Drawing; using System.Diagnostics; using System.Data; using System.Xml.Linq; using Microsoft.VisualBasic; using System.Collections; using System.Windows.Forms; // End of VB project level imports using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过下列特性集 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 // 查看程序集特性的值 [assembly: AssemblyTitle("S7_UDP_CLIENT_C#2010")] [assembly:AssemblyDescription("")] [assembly:AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("UdpClient")] [assembly:AssemblyCopyright("Copyright © Microsoft 2012")] [assembly:AssemblyTrademark("")] [assembly: ComVisible(true)] //如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly:Guid("5904411e-1e46-4e05-ab31-7cbbe552d6a7")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // <Assembly: AssemblyVersion("1.0.*")> [assembly:AssemblyVersion("1.0.0.0")] [assembly:AssemblyFileVersion("1.0.0.0")]
namespace BettingSystem.Infrastructure.Betting.Repositories { using System.Threading; using System.Threading.Tasks; using Application.Betting.Matches; using Common.Repositories; using Domain.Betting.Models.Matches; using Domain.Betting.Repositories; using Microsoft.EntityFrameworkCore; using Persistence; internal class MatchRepository : DataRepository<BettingDbContext, Match>, IMatchDomainRepository, IMatchQueryRepository { public MatchRepository(BettingDbContext db) : base(db) { } public async Task<bool> Delete( int id, CancellationToken cancellationToken = default) { var match = await this.Data.Matches.FindAsync(id); if (match == null) { return false; } this.Data.Matches.Remove(match); await this.Data.SaveChangesAsync(cancellationToken); return true; } public async Task<Match?> Find( int id, CancellationToken cancellationToken = default) => await this .All() .FirstOrDefaultAsync(m => m.Id == id, cancellationToken); } }
using System; using System.Collections.Generic; using System.Linq; namespace StringArray { class Program { static void Main(string[] args) { string numbers = Console.ReadLine(); string[] numbersSplit = Console.ReadLine() .Split(' ', StringSplitOptions.RemoveEmptyEntries) .ToArray(); while (true) { string command = Console.ReadLine(); if (command == "end") { break; } int[] numbersArray = new int[numbersSplit.Length]; for (int i = 0; i < numbersSplit.Length; i++) { numbersArray[i] = int.Parse(numbersSplit[i]); } string[] commandSplit = command.Split(' '); int start = 0; int end = 0; string output; switch (commandSplit[0]) { case "reverse": start = int.Parse(commandSplit[2]); end = int.Parse(commandSplit[4]); for (int i = 0 - 1; i < numbersArray.Length - 1; i++) { output = numbersArray.ToString() + ", "; } break; case "sort": break; case "remove": start = int.Parse(commandSplit[1]); for (int i = start - 1; i < numbersArray.Length - 1; i++) { output = numbersArray.ToString() + ", "; output += numbersArray[numbersArray.Length - 1]; Console.WriteLine(output); } break; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamOthellop.Model.Agents { /// <summary> /// Evaluates board based on user-defined features /// </summary> class HeuristicAgent : IEvaluationAgent { /// <summary> /// Formula takes the following form : value = (diffSlope * diff) + (offsetSlope * time) + diffOffset /// </summary> //*****difference-dependent slope for Board Evaluation double coinDiffSlope; double cornerDiffSlope; double nearCornerDiffSlope; double avalibleMoveDiffSlope; double nonTurnableCoinDiffSlope; double controlledCornerDiffSlope; //*****offset for Board Evaluation double coinDiffOffset; double cornerDiffOffset; double nearCornerDiffOffset; double avalibleMoveDiffOffset; double nonTurnableCoinDiffOffset; double controlledCornerDiffOffset; ////*****Time-dependent Slope double coinTimeSlope; double cornerTimeSlope; double nearCornerTimeSlope; double avalibleMoveTimeSlope; double nonTurnableTimeSlope; double controlledCornerTimeSlope; public HeuristicAgent() { try { string[] strWeights = System.IO.File.ReadAllLines("bestchromosome.dat"); double[] weights = strWeights.Select((gene) => double.Parse(gene)).ToArray(); coinDiffSlope = weights[0]; cornerDiffSlope = weights[1]; nearCornerDiffSlope = weights[2]; avalibleMoveDiffSlope = weights[3]; nonTurnableCoinDiffSlope = weights[4]; controlledCornerDiffSlope = weights[5]; coinDiffOffset = weights[6]; cornerDiffOffset = weights[7]; nearCornerDiffOffset = weights[8]; avalibleMoveDiffOffset = weights[9]; nonTurnableCoinDiffOffset = weights[10]; controlledCornerDiffOffset = weights[11]; coinTimeSlope = weights[11]; cornerTimeSlope = weights[13]; nearCornerTimeSlope = weights[14]; avalibleMoveTimeSlope = weights[15]; nonTurnableTimeSlope = weights[16]; controlledCornerTimeSlope = weights[17]; } catch (Exception) { //ok performing values coinDiffSlope = 3; cornerDiffSlope = 75; nearCornerDiffSlope = -5; avalibleMoveDiffSlope = 0; nonTurnableCoinDiffSlope = 10; controlledCornerDiffSlope = 100; coinDiffOffset = 30; cornerDiffOffset = 30; nearCornerDiffOffset = 30; avalibleMoveDiffOffset = 30; nonTurnableCoinDiffOffset = 30; controlledCornerDiffOffset = 30; coinTimeSlope = 0; cornerTimeSlope = 0; nearCornerTimeSlope = 0; avalibleMoveTimeSlope = 0; nonTurnableTimeSlope = 0; controlledCornerTimeSlope = 0; } } public HeuristicAgent(double[] weights) { coinDiffSlope = weights[0]; cornerDiffSlope = weights[1]; nearCornerDiffSlope = weights[2]; avalibleMoveDiffSlope = weights[3]; nonTurnableCoinDiffSlope = weights[4]; controlledCornerDiffSlope = weights[5]; coinDiffOffset = weights[6]; cornerDiffOffset = weights[7]; nearCornerDiffOffset = weights[8]; avalibleMoveDiffOffset = weights[9]; nonTurnableCoinDiffOffset = weights[10]; controlledCornerDiffOffset = weights[11]; coinTimeSlope = weights[11]; cornerTimeSlope = weights[13]; nearCornerTimeSlope = weights[14]; avalibleMoveTimeSlope = weights[15]; nonTurnableTimeSlope = weights[16]; controlledCornerTimeSlope = weights[17]; } public override byte[] MakeMove(OthelloGame game, BoardStates player) { byte[] bestMove = new byte[] { byte.MaxValue, byte.MaxValue }; List<byte[]> moves = game.GetPossiblePlayList(); double bestScore = int.MinValue + 1; if (game.GetPieceCount(BoardStates.empty) > 58)//first two moves, don't compute { return OpeningMove(player, game); } else if (moves.Count == 1) //don't compute if there is only 1 move { return moves[0]; } foreach (byte[] move in moves) { OthelloGame testGame = game.DeepCopy(); testGame.MakeMove(move); double thisScore = EvaluateBoard(testGame, player); if (thisScore > bestScore) { bestScore = thisScore; bestMove = move; } } if ((bestMove[0] == byte.MaxValue || bestMove[1] == byte.MaxValue) && moves.Count > 0) {//All moves are valued at -inf, return one of em return moves[0]; } return bestMove; } /// <summary> /// returns weights for Heuristic evaluation function /// </summary> /// <returns></returns> public double[] GetWeights() { return new double[] { coinDiffSlope, cornerDiffSlope, nearCornerDiffSlope, avalibleMoveDiffSlope, nonTurnableCoinDiffSlope, controlledCornerDiffSlope, coinDiffOffset, cornerDiffOffset, nearCornerDiffOffset, avalibleMoveDiffOffset, nonTurnableCoinDiffOffset, controlledCornerDiffOffset, coinTimeSlope, cornerTimeSlope, nearCornerTimeSlope, avalibleMoveTimeSlope, nonTurnableTimeSlope, controlledCornerTimeSlope }; } public override double EvaluateBoard(OthelloGame game, BoardStates player) { ///Based of features of the board that humans have identified. ///Hints of evaluation from any source I could find ///idealy these could me optimized using a genetic algorithm, ///but that is a different project double value = 0; int empty = game.GetPieceCount(BoardStates.empty); if (game.GameComplete) { return CompleteEval(player, game); } //plane funct //value += coinDiffSlope * (game.GetPieceCount(player) - game.GetPieceCount(~player)) + (empty * coinTimeSlope) + coinDiffOffset; //value += cornerDiffSlope * (game.GetCornerCount(player) - game.GetCornerCount(~player)) + (empty * cornerTimeSlope) + cornerDiffOffset; //value += nearCornerDiffSlope * (game.GetAdjCornerCount(player) - game.GetAdjCornerCount(~player)) + (empty * nearCornerTimeSlope) + nearCornerDiffOffset; //value += avalibleMoveDiffSlope * (game.GetPossiblePlayList(player).Count() - game.GetPossiblePlayList(~player).Count()) + (empty * avalibleMoveTimeSlope) + avalibleMoveDiffOffset; //value += nonTurnableCoinDiffSlope * (game.GetSafePeiceCountEstimation(player) - game.GetSafePeiceCountEstimation(~player)) + (empty * nonTurnableTimeSlope) + nonTurnableCoinDiffOffset; //value += controlledCornerDiffSlope * (game.GetControlledCorners(player) - game.GetControlledCorners(~player)) + (empty * controlledCornerTimeSlope) + controlledCornerDiffOffset; //power funct value += coinDiffSlope * Math.Pow(game.GetPieceCount(player) - game.GetPieceCount(~player) + empty - coinDiffOffset, coinTimeSlope); value += cornerDiffSlope * Math.Pow(game.GetCornerCount(player) - game.GetCornerCount(~player) + empty - cornerDiffOffset, cornerTimeSlope); value += nearCornerDiffSlope * Math.Pow(game.GetAdjCornerCount(player) - game.GetAdjCornerCount(~player) + empty - nearCornerDiffOffset, nearCornerTimeSlope); value += avalibleMoveDiffSlope * Math.Pow(game.GetPossiblePlayList(player).Count() - game.GetPossiblePlayList(~player).Count() + empty - avalibleMoveDiffOffset, avalibleMoveTimeSlope); value += nonTurnableCoinDiffSlope * Math.Pow(game.GetSafePeiceCountEstimation(player) - game.GetSafePeiceCountEstimation(~player) + empty - nonTurnableCoinDiffOffset, nonTurnableTimeSlope); value += controlledCornerDiffSlope * Math.Pow(game.GetControlledCorners(player) - game.GetControlledCorners(~player) + empty - controlledCornerDiffOffset, controlledCornerTimeSlope); return value; } private static int CompleteEval(BoardStates player, OthelloGame game) { ///Returns complete worth of board, -inf for loss, +inf for win if (game.FinalWinner == player) { return int.MaxValue; } else return int.MinValue; } private static byte[] OpeningMove(BoardStates player, OthelloGame game) {//avoid computation for first move - only one symmetric option //randomly select perpendicular or diagonal for second move - parallel //has been shown to be much worse //SPECIFIC TO 8x8 BOARDS byte[][] firstMoves = new byte[4][] { new byte[]{ 2, 3 }, new byte[]{ 3, 2 }, new byte[]{ 4, 5 }, new byte[]{ 5, 4 }}; if (game.GetPieceCount(BoardStates.empty) == 60) { Random rndGen = new Random(); int rand = (int)Math.Ceiling(rndGen.NextDouble() * 4); switch (rand) { case 1: return firstMoves[0]; case 2: return firstMoves[1]; case 3: return firstMoves[2]; case 4: return firstMoves[3]; default: throw new Exception("OpeningMove has faulted with random number generation"); } } if (game.GetPieceCount(BoardStates.empty) == 59) { List<byte[]> moves = game.GetPossiblePlayList(); Random rndGen = new Random(); byte rand = (byte)Math.Ceiling(rndGen.NextDouble() * 2); switch (rand) { case 1: //diagonal return moves[0]; case 2: //perpendicular return moves[0]; default: throw new Exception("Opening move has faulted with random number generation"); } } return new byte[] { byte.MaxValue, byte.MaxValue }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DistCWebSite.Core.Entities; using DistCWebSite.Core.Interfaces; namespace DistCWebSite.Infrastructure { public class OperationRepository : IOperationLogRepository { public void Add(OperationLog op) { var ctx = new DistCSiteContext(); ctx.OpLogs.Add(op); ctx.SaveChanges(); } public IEnumerable<OperationLog> GetList() { var ctx = new DistCSiteContext(); return ctx.OpLogs.OrderByDescending(o => o.OpTime); } } public enum OperationEnum { Submit3rdPartyEmpInfo, DMSubmit3rdParty, CCSubmit3rdParty } }
using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using OpenTelemetry.Resources; using OpenTelemetry.Trace; namespace DistributedTracing.WebApp1 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddOpenTelemetryTracing(builder => { builder.SetSampler(new AlwaysOnSampler()); builder.AddJaegerExporter(o => Configuration.Bind("Jaeger", o)); var resourceBuilder = ResourceBuilder.CreateDefault(); resourceBuilder.AddService(Assembly.GetExecutingAssembly().FullName?.Split(',').FirstOrDefault()); builder.SetResourceBuilder(resourceBuilder); builder.AddAspNetCoreInstrumentation(); builder.AddHttpClientInstrumentation(); builder.SetErrorStatusOnException(); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using HowLeaky.CustomAttributes; using HowLeaky.Models; using HowLeaky.Tools; using HowLeaky.Tools.DataObjects; using HowLeaky.XmlObjects; using HowLeakyWebsite.Tools.DHMCoreLib.Helpers; using System; using System.Xml.Serialization; namespace HowLeaky.DataModels { public enum PlantingRules { prPlantInWindow, prFixedAnualPlaning, prPlantFromSequenceFile }; //<VegetationType href = "C:\REEF\Grains_HL_2015\P2R2\P2R2_Jo\Vegetation\A and B management Chickpeas CQ 1 JO.vege" text="A and B management Chickpeas - CQ 1" Description="A and B management Chickpeas - CQ 1"> //<PotMaxLai default="3.5" LastModified="08/04/2011">3</PotMaxLai> //<PropGrowSeaForMaxLai>0.7</PropGrowSeaForMaxLai> //<PercentOfMaxLai1>5</PercentOfMaxLai1> //<PercentOfGrowSeason1>15</PercentOfGrowSeason1> //<PercentOfMaxLai2>75</PercentOfMaxLai2> //<PercentOfGrowSeason2 LastModified = "21/01/2011" > 50 </ PercentOfGrowSeason2 > //< SWPropForNoStress > 0.3 </ SWPropForNoStress > //< DegreeDaysPlantToHarvest default="1900" LastModified="21/01/2011">2000</DegreeDaysPlantToHarvest> //<SenesenceCoef default="0.75" LastModified="21/01/2011">1</SenesenceCoef> //<RadUseEffic default="2.4" LastModified="08/04/2011">1.6</RadUseEffic> //<HarvestIndex default="0.42" LastModified="21/01/2011">0.5</HarvestIndex> //<BaseTemp>0</BaseTemp> //<OptTemp>20</OptTemp> //<MaxRootDepth default="1200" LastModified="21/01/2011">600</MaxRootDepth> //<DailyRootGrowth default="15">12</DailyRootGrowth> //<WatStressForDeath>0.1</WatStressForDeath> //<DaysOfStressToDeath default="21">30</DaysOfStressToDeath> //<MaxResidueLoss default="4" LastModified="25/02/2011">5</MaxResidueLoss> //<BiomassAtFullCover default="5000" LastModified="21/04/2011">4000</BiomassAtFullCover> ////<PropGGDEnd>1</PropGGDEnd> public class PlantingFormat : IndexData { public DayMonthData StartPlantWindow { get; set; } public DayMonthData EndPlantWindow { get; set; } public DayMonthData PlantDate { get; set; } public StateData ForcePlanting { get; set; } public StateData MultiPlantInWindow { get; set; } public RotationOptions RotationOptions { get; set; } public Sequence PlantingDates { get; set; } public FallowSwitch FallowSwitch { get; set; } public RainfallSwitch RainfallSwitch { get; set; } public SoilWaterSwitch SoilWaterSwitch { get; set; } public RatoonCrop RatoonCrop { get; set; } public PlantingFormat() { } } public class RotationOptions : IndexData { public int MinContinuousRotations { get; set; } public int MaxContinuousRotations { get; set; } public int MinYearsBetweenSowing { get; set; } public RotationOptions() { } } public class FallowSwitch : StateData { public int MinFallowLength { get; set; } public FallowSwitch() { } } public class RainfallSwitch : StateData { public double PlantingRain { get; set; } public int DaysToTotalRain { get; set; } public int SowingDelay { get; set; } public RainfallSwitch() { } } public class SoilWaterSwitch : StateData { public double MinSoilWaterRatio { get; set; } public double MaxSoilWaterRatio { get; set; } public double AvailSWAtPlanting { get; set; } public double SoilDepthToSumPlantingSW { get; set; } public SoilWaterSwitch() { } } public class RatoonCrop : StateData { public int RatoonCount { get; set; } public double RatoonScaleFactor { get; set; } public RatoonCrop() { } } public class Waterlogging : StateData { public double WaterLoggingFactor1 { get; set; } public double WaterLoggingFactor2 { get; set; } public Waterlogging() { } } [XmlRoot("VegetationType")] public class LAIVegObjectDataModel : DataModel { //Input Parameters public double PotMaxLAI { get; set; } // The upper limit of the leaf area index (LAI) - development curve. public double PropGrowSeaForMaxLai { get; set; } // The development stage for potential maximum LAI. public double BiomassAtFullCover { get; set; } // The amount of dry plant residues (ie stubble, pasture litter etc) that results in complete coverage of the ground. This parameter controls the relationship between the amount of crop residue and cover, which is used in calculating runoff and erosion. [Unit("mm_per_day")] public double DailyRootGrowth { get; set; } // The daily increment in root depth. public double PropGDDEnd { get; set; } // Set the proportion of the growth cycle for which irrigation is possible. public double DaysOfStressToDeath { get; set; } // The number of consecutive days that water supply is less than threshold before the crop is killed. public double PercentOfMaxLai1 { get; set; } // Percent of Maximum LAI for the 1st development stage. public double PercentOfGrowSeason1 { get; set; } // The development stage for the 1st LAI "point". public double PercentOfMaxLai2 { get; set; } // Percent of Maximum LAI for the 2nd development stage. public double PercentOfGrowSeason2 { get; set; } // The development stage for the 2nd LAI "point". [Unit("days")] public double DegreeDaysPlantToHarvest { get; set; } // The sum of degree-days (temperature less the base temperature) between planting and harvest. Controls the rate of crop development and the potential duration of the crop. Some plants develop to maturity and harvest more slowly than others - these accumulate more degree-days between plant and harvest. public double SenesenceCoef { get; set; } // Rate of LAI decline after max LAI. public double RadUseEffic { get; set; } // Biomass production per unit of radiation. public double HarvestIndex { get; set; } // The grain biomass (kg/ha) divided by the above-ground biomass at flowering (kg/ha) [Unit("oC")] public double BaseTemp { get; set; } // The lower limit of plant development and growth, with respect to temperature (the average day temperature, degrees Celsius). The base temperature of vegetation is dependent on the type of environment in which the plant has evolved, and any breeding for hot or cold conditions. [Unit("oC")] public double OptTemp { get; set; } // The temperature for maximum biomass production. Biomass production is a linear function of temperature between the Base temperature and the Optimum temperature. [Unit("mm")] public double MaxRootDepth { get; set; } // located in CustomVegObject - >The maximum depth of the roots from the soil surface. For the LAI model, the model calculates daily root growth from the root depth increase parameter public double SWPropForNoStress { get; set; } // Ratio of water supply to potential water supply that indicates a stress day public double MaxResidueLoss { get; set; } //Decomposition Rate public DayMonthData PlantDate { get; set; } public PlantingFormat PlantingFormat { get; set; } public Waterlogging Waterlogging { get; set; } //Getters public int PlantingRulesOptions { get {return PlantingFormat.index; } } public DayMonthData PlantingWindowStartDate { get { return PlantingFormat.StartPlantWindow; } } public DayMonthData PlantingWindowEndDate { get { return PlantingFormat.EndPlantWindow; } } public bool ForcePlantingAtEndOfWindow { get { return PlantingFormat.ForcePlanting.state; } } public bool MultiPlantInWindow { get { return PlantingFormat.MultiPlantInWindow.state; } } public int RotationFormat { get { return PlantingFormat.RotationOptions.index; } } public int MinRotationCount { get { return PlantingFormat.RotationOptions.MinContinuousRotations; } } public int MaxRotationCount { get { return PlantingFormat.RotationOptions.MaxContinuousRotations; } } public int RestPeriodAfterChangingCrops { get { return PlantingFormat.RotationOptions.MinYearsBetweenSowing; } } public bool FallowSwitch { get { return PlantingFormat.FallowSwitch.state; } } [Unit("days")] public int MinimumFallowPeriod { get { return PlantingFormat.FallowSwitch.MinFallowLength; } } public bool PlantingRainSwitch { get { return PlantingFormat.RainfallSwitch.state; } } [Unit("mm")] public double RainfallPlantingThreshold { get { return PlantingFormat.RainfallSwitch.PlantingRain; } } [Unit("days")] public int RainfallSummationDays { get { return PlantingFormat.RainfallSwitch.DaysToTotalRain; } } public bool SoilWaterSwitch { get { return PlantingFormat.SoilWaterSwitch.state; } } [Unit("mm")] public double MinSoilWaterTopLayer { get { return PlantingFormat.SoilWaterSwitch.MinSoilWaterRatio; } } [Unit("mm")] public double MaxSoilWaterTopLayer { get { return PlantingFormat.SoilWaterSwitch.MaxSoilWaterRatio; } } public double SoilWaterReqToPlant { get { return PlantingFormat.SoilWaterSwitch.AvailSWAtPlanting; } } [Unit("mm")] public double DepthToSumPlantingWater { get { return PlantingFormat.SoilWaterSwitch.SoilDepthToSumPlantingSW; } set { } } public int SowingDelay { get { return PlantingFormat.RainfallSwitch.SowingDelay; } } public Sequence PlantingSequence { get { return PlantingFormat.PlantingDates; } } // The rate of removal of plant residues from the soil surface by decay. Fraction of current plant/crop residues that decay each day. Plant residues on the soil surface are used in calculation of soil evaporation, runoff and erosion. public bool WaterLoggingSwitch { get { return Waterlogging.state; } } public double WaterLoggingFactor1 { get { return Waterlogging.WaterLoggingFactor1; } } public double WaterLoggingFactor2 { get { return Waterlogging.WaterLoggingFactor2; } } public bool RatoonSwitch { get { return PlantingFormat.RatoonCrop.state; } } public int NumberOfRatoons { get { return PlantingFormat.RatoonCrop.RatoonCount; } } public double ScalingFactorForRatoons { get { return PlantingFormat.RatoonCrop.RatoonScaleFactor; } } //TODO: unmatched //MaxResidueLoss, WatStressForDeath public double MaximumResidueCover { get; set; } public LAIVegObjectDataModel() { } } public class LAIVegObjectController : VegObjectController { public LAIVegObjectDataModel dataModel { get; set; } public static int UNCONTROLLED = 0; public static int OPPORTUNITY = 1; public static int INCROPORDER = 2; public double heat_units { get; set; } public double heat_unit_index { get; set; } public int LastPlantYear { get; set; } //public bool TodayIsPlantDay { get; set; } public double dhrlt { get; set; } public double hrltp { get; set; } public double hufp { get; set; } public bool AllowMultiPlanting { get; set; } public double decompdays { get; set; } public double LAICurveY1active { get; set; } public double LAICurveY2active { get; set; } public int days_since_fallow { get; set; } public double max_calc_lai { get; set; } public double lai { get; set; } /// <summary> /// /// </summary> public LAIVegObjectController() { } /// <summary> /// /// </summary> /// <param name="sim"></param> public LAIVegObjectController(Simulation sim) : base(sim) { predefined_residue = false; //TodayIsPlantDay = false; } /// <summary> /// /// </summary> public override void Initialise() { base.Initialise(); Scurve(); heat_unit_index = 0; hrltp = 0; } /// <summary> /// /// </summary> public void SimulateCrop() { if (ExistsInTheGround) { ++days_since_planting; CalculateTranspiration(); if (CheckCropSurvives()) { sim.UpdateManagementEventHistory(ManagementEvent.meCropGrowing, sim.VegetationController.GetCropIndex(this)); if (TodayIsPlantDay) //remove this once debugging is done { lai = 0.02; // this is here just to replicate the old code... see Brett about it. //TodayIsPlantDay = false; } if (!ReadyToHarvest()) { RecordCropStage(); CalculateGrowthStressFactors(); CalculateLeafAreaIndex(); CalculateBioMass(); CalculateRootGrowth(); // lai=0; } else HarvestTheCrop(); } else SimulateCropDeath(); } } /// <summary> /// /// </summary> /// <returns></returns> public override double GetPotentialSoilEvaporation() { if (sim.ModelOptionsController.in_UsePERFECTSoilEvapFn) { if (lai < 0.3) return sim.out_PanEvap_mm * (1.0 - green_cover); } return sim.out_PanEvap_mm * (1.0 - crop_cover); } /// <summary> /// /// </summary> /// <returns></returns> public override bool IsSequenceCorrect() { //if the cropindex is less than 2, the this is either the current crop or the next crop. //int index=sim.SortedCropList.IndexOf(this); int index = 0; for (int i = 0; i < 10; i++) { if (sim.VegetationController.SortedCropList[i] == this) { index = i; break; } } if (index == 2) return (dataModel.RotationFormat != INCROPORDER); return true; } /// <summary> /// /// </summary> /// <returns></returns> public override bool DoesCropMeetSowingCriteria() { if (dataModel.PlantingRulesOptions == (int)PlantingRules.prFixedAnualPlaning) { if (dataModel.PlantDate.MatchesDate(sim.today)) return true; } else if (dataModel.PlantingRulesOptions == (int)PlantingRules.prPlantInWindow) { // run ALL planting tests up front before testing results so that results // can be added to the annotations on the time-series charts. bool satisifies_window_conditions = SatisifiesWindowConditions(); bool satisifies_fallow_conditions = SatisifiesFallowConditions(); bool satisifies_planting_rain_conditions = SatisifiesPlantingRainConditions(); bool satisifies_soil_water_conditions = SatisifiesSoilWaterConditions(); bool satisifies_MultiPlantInWindow = SatisifiesMultiPlantInWindow(); if (satisifies_window_conditions && satisifies_MultiPlantInWindow) { if (satisifies_fallow_conditions) { if (satisifies_planting_rain_conditions && satisifies_soil_water_conditions) return true; } else if (dataModel.ForcePlantingAtEndOfWindow) { if (!HasAlreadyPlantedInThisWindow()) { DateTime endplantingdate = new DateTime(sim.today.Year, dataModel.PlantingWindowEndDate.Month, dataModel.PlantingWindowEndDate.Day); return (sim.today == endplantingdate); } return false; } else ++missed_rotation_count; } } else if (dataModel.PlantingRulesOptions == (int)PlantingRules.prPlantFromSequenceFile) { return dataModel.PlantingSequence.ContainsDate(sim.today); } return false; } /// <summary> /// /// </summary> /// <returns></returns> public override bool SatisifiesMultiPlantInWindow() { if (!dataModel.MultiPlantInWindow && LastSowingDate != DateUtilities.NULLDATE) { return !HasAlreadyPlantedInThisWindow(); } return true; } /// <summary> /// /// </summary> /// <returns></returns> public bool HasAlreadyPlantedInThisWindow() { //Note there was a possible error here in previous version where the wrong year could have been used. return DateUtilities.isDateInWindow(LastSowingDate, dataModel.PlantingWindowStartDate, dataModel.PlantingWindowEndDate); } /// <summary> /// /// </summary> /// <returns></returns> bool SatisifiesWindowConditions() { bool result = DateUtilities.isDateInWindow(sim.today, dataModel.PlantingWindowStartDate, dataModel.PlantingWindowEndDate); if (result) sim.UpdateManagementEventHistory(ManagementEvent.meInPlantingWindow, sim.VegetationController.GetCropIndex(this)); return result; } /// <summary> /// /// </summary> /// <returns></returns> bool SatisifiesPlantingRainConditions() { bool result = true; if (dataModel.PlantingRainSwitch) { int actual_sowing_delay = dataModel.SowingDelay; double sumrain = 0; int index; int count_rainfreedays = 0; int max = 3 * dataModel.SowingDelay; for (int i = 0; i < max; ++i) { index = sim.climateindex - i; if (index >= 0) { if ((sim.Rainfall)[index] < 5) ++count_rainfreedays; } if (count_rainfreedays == dataModel.SowingDelay) { actual_sowing_delay = i; i = max; } } if (count_rainfreedays == dataModel.SowingDelay) { int fallow_planting_rain = (int)sim.SumRain(dataModel.RainfallSummationDays, actual_sowing_delay); result = (fallow_planting_rain > dataModel.RainfallPlantingThreshold); } else result = false; if (result) sim.UpdateManagementEventHistory(ManagementEvent.meMeetsRainfallPlantCritera, sim.VegetationController.GetCropIndex(this)); } return result; } /// <summary> /// /// </summary> /// <returns></returns> bool SatisifiesFallowConditions() { bool result = true; if (dataModel.FallowSwitch) { result = (sim.VegetationController.days_since_harvest >= dataModel.MinimumFallowPeriod); if (result) sim.UpdateManagementEventHistory(ManagementEvent.meMeetsDaysSinceHarvestPlantCritera, sim.VegetationController.GetCropIndex(this)); } return result; } /// <summary> /// /// </summary> /// <returns></returns> bool SatisifiesSoilWaterConditions() { bool result = true; if (dataModel.SoilWaterSwitch) { double SumSW = 0.0; for (int i = 0; i < sim.in_LayerCount; ++i) { if (sim.depth[i + 1] - sim.depth[i] > 0) { if (dataModel.DepthToSumPlantingWater > sim.depth[sim.in_LayerCount]) { dataModel.DepthToSumPlantingWater = sim.depth[sim.in_LayerCount]; } if (sim.depth[i + 1] < dataModel.DepthToSumPlantingWater) { SumSW += sim.SoilWater_rel_wp[i]; } if (sim.depth[i] < dataModel.DepthToSumPlantingWater && sim.depth[i + 1] > dataModel.DepthToSumPlantingWater) { SumSW += sim.SoilWater_rel_wp[i] * (dataModel.DepthToSumPlantingWater - sim.depth[i]) / (sim.depth[i + 1] - sim.depth[i]); } if (!MathTools.DoublesAreEqual(sim.DrainUpperLimit_rel_wp[i], 0)) { sim.mcfc[i] = Math.Max(sim.SoilWater_rel_wp[i] / sim.DrainUpperLimit_rel_wp[i], 0.0); } else { sim.mcfc[i] = 0; } } else { SumSW = 0; sim.mcfc[i] = 0; MathTools.LogDivideByZeroError("SatisifiesSoilWaterConditions", "sim.depth[i+1]-sim.depth[i]", "SumSW"); } } result = (SumSW > dataModel.SoilWaterReqToPlant && sim.mcfc[0] >= dataModel.MinSoilWaterTopLayer && sim.mcfc[0] <= dataModel.MaxSoilWaterTopLayer); if (result) { sim.UpdateManagementEventHistory(ManagementEvent.meMeetsSoilWaterPlantCritera, sim.VegetationController.GetCropIndex(this)); } } return result; } /// <summary> /// /// </summary> /// <returns></returns> public override bool IsCropUnderMaxContinuousRotations() { if (dataModel.PlantingRulesOptions != (int)PlantingRules.prPlantFromSequenceFile && dataModel.RotationFormat != UNCONTROLLED) { if (FirstRotationDate != DateUtilities.NULLDATE) { return (rotation_count + missed_rotation_count < dataModel.MaxRotationCount); } } return true; } /// <summary> /// /// </summary> /// <returns></returns> public override bool HasCropHadSufficientContinuousRotations() { if (dataModel.PlantingRulesOptions != (int)PlantingRules.prPlantFromSequenceFile && dataModel.RotationFormat != UNCONTROLLED) { if (FirstRotationDate != DateUtilities.NULLDATE) return (rotation_count + missed_rotation_count >= dataModel.MinRotationCount); } return true; } /// <summary> /// /// </summary> /// <param name="today"></param> /// <returns></returns> public override bool HasCropBeenAbsentForSufficientYears(DateTime today) { if (dataModel.PlantingRulesOptions != (int)PlantingRules.prPlantFromSequenceFile && dataModel.RotationFormat != UNCONTROLLED) { if (LastHarvestDate != DateUtilities.NULLDATE) { int months_since_last_sow = DateUtilities.MonthsBetween(today, LastHarvestDate); return (months_since_last_sow >= dataModel.RestPeriodAfterChangingCrops); } } return true; } /// <summary> /// /// </summary> public new void Plant() { base.Plant(); sim.VegetationController.CurrentCrop.ResetCover(); heat_unit_index = 0; heat_units = 0; max_calc_lai = 0; hufp = 0; killdays = 0; ++rotation_count; //TodayIsPlantDay = true; if (sim.ModelOptionsController.in_ResetSoilWaterAtPlanting) { for (int i = 0; i < sim.in_LayerCount; ++i) sim.SoilWater_rel_wp[i] = (sim.ModelOptionsController.in_ResetValueForSWAtPlanting_pc / 100.0) * sim.DrainUpperLimit_rel_wp[i]; } sim.FManagementEvent = ManagementEvent.mePlanting; sim.UpdateManagementEventHistory(ManagementEvent.mePlanting, sim.VegetationController.GetCropIndex(this)); } /// <summary> /// /// </summary> /// <returns></returns> public override double GetTotalCover() { total_cover = Math.Min(1.0, crop_cover + residue_cover * (1 - crop_cover)); out_TotalCover_pc = total_cover * 100.0; return total_cover; } /// <summary> /// /// </summary> /// <returns></returns> public bool CheckCropSurvives() { if (sim.ModelOptionsController.in_IgnoreCropKill == false) { if (crop_stage <= 2.0) { if (out_WaterStressIndex <= dataModel.SWPropForNoStress) ++killdays; else killdays = 0; if (killdays >= dataModel.DaysOfStressToDeath) return false; } else killdays = 0; } return true; } // *********************************************************************** // * This subroutine calculates growth stress factors for todays_temp * // * and water * // *********************************************************************** /// <summary> /// /// </summary> public void CalculateGrowthStressFactors() { // ****************************** // * Temperature stress index * // ****************************** // [Equation 2.235] from EPIC double ratio; if (!MathTools.DoublesAreEqual(dataModel.OptTemp, dataModel.BaseTemp)) ratio = (sim.temperature - dataModel.BaseTemp) / (dataModel.OptTemp - dataModel.BaseTemp); else { ratio = 1; //dont log error for this one } out_TempStressIndex = Math.Sin(0.5 * Math.PI * ratio); out_TempStressIndex = Math.Max(out_TempStressIndex, 0.0); out_TempStressIndex = Math.Min(out_TempStressIndex, 1.0); // ************************ // * Water stress index * // ************************ out_WaterStressIndex = 1.0; if (out_PotTranspiration_mm > 0.0) out_WaterStressIndex = total_transpiration / out_PotTranspiration_mm; out_WaterStressIndex = Math.Max(out_WaterStressIndex, 0.0); out_WaterStressIndex = Math.Min(out_WaterStressIndex, 1.0); // ************************************* // * calculate minimum stress factor * // ************************************* out_GrowthRegulator = 1; out_GrowthRegulator = Math.Min(out_GrowthRegulator, out_TempStressIndex); out_GrowthRegulator = Math.Min(out_GrowthRegulator, out_WaterStressIndex); out_GrowthRegulator = MathTools.CheckConstraints(out_GrowthRegulator, 1.0, 0); } // ********************************************************************* // * This subroutine fits an s curve to two points. It was derived * // * from EPIC3270. * // ********************************************************************* /// <summary> /// /// </summary> public void Scurve() { if (MathTools.DoublesAreEqual(dataModel.PercentOfMaxLai1, 1)) dataModel.PercentOfMaxLai1 = 0.99999; if (MathTools.DoublesAreEqual(dataModel.PercentOfMaxLai2, 1)) dataModel.PercentOfMaxLai2 = 0.99999; if (dataModel.PercentOfMaxLai1 > 0 && dataModel.PercentOfMaxLai2 > 0) { double value1 = dataModel.PercentOfGrowSeason1 / dataModel.PercentOfMaxLai1 - dataModel.PercentOfGrowSeason1; double value2 = dataModel.PercentOfGrowSeason2 / dataModel.PercentOfMaxLai2 - dataModel.PercentOfGrowSeason2; if (!MathTools.DoublesAreEqual(value1, 0) && !MathTools.DoublesAreEqual(value2, 0)) { double x = Math.Log(value1); LAICurveY2active = (x - Math.Log(value2)) / (dataModel.PercentOfGrowSeason2 - dataModel.PercentOfGrowSeason1); LAICurveY1active = x + dataModel.PercentOfGrowSeason1 * LAICurveY2active; } else MathTools.LogDivideByZeroError("Scurve", "in_LAICurveX1/in_LAICurveY1-in_LAICurveX1 or in_LAICurveX2/in_LAICurveY2-in_LAICurveX2", "LAI Curves - Taking Logs"); } else { MathTools.LogDivideByZeroError("Scurve", "in_LAICurveY1 or in_LAICurveY2", "LAICurveY2active or LAICurveY1active"); } } // **************************************************************************** // * This subroutine calculates leaf area index using the major * // * functions from the EPIC model * // **************************************************************************** /// <summary> /// /// </summary> public void CalculateLeafAreaIndex() { double HUF; //Heat Unit Factor double dHUF; //daily change in Heat Unit Factor double dlai; // *************************** // * accumulate heat units * // *************************** // accumulate heat units heat_units = heat_units + Math.Max(sim.temperature - dataModel.BaseTemp, 0.0); // caluclate heat unit index [Equation 2.191] from EPIC if (!MathTools.DoublesAreEqual(dataModel.DegreeDaysPlantToHarvest, 0)) heat_unit_index = heat_units / dataModel.DegreeDaysPlantToHarvest; else { heat_unit_index = 1; MathTools.LogDivideByZeroError("CalculateLeafAreaIndex", "in_DegreeDaysToMaturity_days", "heat_unit_index"); } // *************************** // * calculate leaf growth * // *************************** if (heat_unit_index < dataModel.PropGrowSeaForMaxLai) { // heat unit factor, [Equation 2.198] from EPIC double denom = (heat_unit_index + Math.Exp(LAICurveY1active - LAICurveY2active * heat_unit_index)); if (!MathTools.DoublesAreEqual(denom, 0)) HUF = heat_unit_index / denom; else { HUF = 0; //not sure I should log this one } dHUF = HUF - hufp; hufp = HUF; // leaf area index [Equation 2.197] from EPIC // Eqn 2.197 originally stated that // // dlai = dHUF * MaxLAI * (1.0-Math.Exp(5.0*(laip-MaxLAI)))* sqrt(reg) // // This function NEVER allows lai to achieve MaxLAI under no stress // conditions due to the exponential term. This term was removed. Therefore, // lai development is governed by the S-Curve, Max lai, and stress factors // only. if (sim.ModelOptionsController.in_UsePERFECTLeafAreaFn) dlai = dHUF * dataModel.PotMaxLAI * Math.Sqrt(out_GrowthRegulator); else dlai = dHUF * dataModel.PotMaxLAI * out_GrowthRegulator; lai = lai + dlai; // store maximum lai if (lai > max_calc_lai) max_calc_lai = lai; } // ****************************** // * calculate leaf senesence * // ****************************** if (heat_unit_index >= dataModel.PropGrowSeaForMaxLai && heat_unit_index <= 1) { if (dataModel.SenesenceCoef > 0) { // leaf senesence [Equation 2.199] from EPIC if (!MathTools.DoublesAreEqual(1.0 - dataModel.PropGrowSeaForMaxLai, 0)) lai = max_calc_lai * Math.Pow((1.0 - heat_unit_index) / (1.0 - dataModel.PropGrowSeaForMaxLai), dataModel.SenesenceCoef); else lai = 0; lai = Math.Max(lai, 0); } else lai = 0; } } // ******************************************************************** // * Subroutine calculates biomass using EPIC type functions * // ******************************************************************** /// <summary> /// /// </summary> public void CalculateBioMass() { double rad, par, hrlt, dhrlt; // ********************************* // * intercepted radiation (PAR) * // ********************************* // Assumes PAR is 50% of solar radiation // Extinction Coefficient = 0.65 rad = sim.out_SolarRad_MJ_per_m2_per_day; par = 0.5 * rad * (1.0 - Math.Exp(-0.65 * lai)); // ********************** // * daylength factor * // ********************** // daylength factor from PERFECT hrlt = GetDayLength(); dhrlt = hrlt - hrltp; if (hrltp < 0.01) dhrlt = 0.0; hrltp = hrlt; double rue = dataModel.RadUseEffic; double effectiverue = rue; if (dataModel.WaterLoggingSwitch && IsWaterLogged()) effectiverue = rue * dataModel.WaterLoggingFactor2; // ************************** // * biomass accumulation * // ************************** // [Equation 2.193] from EPIC if (sim.ModelOptionsController.in_UsePERFECTDryMatterFn) { dry_matter += out_GrowthRegulator * par * effectiverue * Math.Pow(1.0 + dhrlt, 3.0); out_DryMatter_kg_per_ha = dry_matter * 10.0; } else { par = 0.5 * rad; dry_matter += effectiverue * par * out_WaterStressIndex * out_TempStressIndex * green_cover; out_DryMatter_kg_per_ha = dry_matter * 10.0; } } /// <summary> /// /// </summary> /// <returns></returns> bool IsWaterLogged() { int i = 1; return (sim.SoilWater_rel_wp[i] > sim.DrainUpperLimit_rel_wp[i]); } // ******************************************************************* // * This subroutine calculates day length from latitude and day * // * number in the year. * // ******************************************************************* /// <summary> /// /// </summary> /// <returns></returns> public double GetDayLength() { double alat = (!MathTools.DoublesAreEqual(sim.ClimateController.Latitude, 0) ? sim.Latitude : -27); double sund = -2.2; int dayno = (sim.today - new DateTime(sim.today.Year, 1, 1 + 1)).Days; double theta = 0.0172142 * (dayno - 172.0); double sdcln = 0.00678 + 0.39762 * Math.Cos(theta) + 0.00613 * Math.Sin(theta) - 0.00661 * Math.Cos(2.0 * theta) - 0.00159 * Math.Sin(2.0 * theta); double dcln = Math.Asin(sdcln); double rlat = alat * 0.0174533; double dnlat = 0; if (!MathTools.DoublesAreEqual(Math.Cos(rlat), 0) && !MathTools.DoublesAreEqual(Math.Cos(dcln), 0)) dnlat = -(Math.Sin(rlat) / Math.Cos(rlat)) * (Math.Sin(dcln) / Math.Cos(dcln)); else { MathTools.LogDivideByZeroError("GetDayLength", "Math.Cos(rlat) or Math.Cos(dcln)", "dnlat"); } double rsund = sund * 0.0174533; double twif = Math.Cos(rlat) * Math.Cos(dcln); double atwil = 0; if (!MathTools.DoublesAreEqual(twif, 0)) atwil = Math.Sin(rsund) / twif; else { MathTools.LogDivideByZeroError("GetDayLength", "twif", "atwil"); } double htwil = Math.Acos(atwil + dnlat); return 7.639437 * htwil; } /// <summary> /// /// </summary> public void CalculateRootGrowth() { out_RootDepth_mm = out_RootDepth_mm + dataModel.DailyRootGrowth; out_RootDepth_mm = MathTools.CheckConstraints(out_RootDepth_mm, MaximumRootDepth, 0); } /// <summary> /// /// </summary> /// <returns></returns> public bool ReadyToHarvest() { return (heat_unit_index >= 1); } /// <summary> /// /// </summary> public override void ResetCropParametersAfterHarvest() { if (today_is_harvest_day) //if harvest day { today_is_harvest_day = false; yield = 0; out_Yield_t_per_ha = 0; } } /// <summary> /// /// </summary> public void HarvestTheCrop() { LastHarvestDate = sim.today; today_is_harvest_day = true; sim.FManagementEvent = ManagementEvent.meHarvest; sim.UpdateManagementEventHistory(ManagementEvent.meHarvest, sim.VegetationController.GetCropIndex(this)); ++number_of_harvests; // sim.days_since_harvest=0; //should this also get reset at crop death // soil_water_at_harvest=sim.total_soil_water; // ++number_of_fallows; // CropStatus=csInFallow; yield = dataModel.HarvestIndex * dry_matter * 10.0; out_Yield_t_per_ha = yield / 1000.0; out_ResidueAmount_kg_per_ha = out_ResidueAmount_kg_per_ha + (dry_matter - yield / 10.0) * 0.95 * 10.0; //***************** green_cover = 0; //***************** sim.VegetationController.CalculateTotalResidue(); cumulative_yield += yield; ResetParametersForEndOfCrop(); } /// <summary> /// /// </summary> public void SimulateCropDeath() { CalculateGrowthStressFactors(); CalculateLeafAreaIndex(); CalculateBioMass(); CalculateRootGrowth(); // CalculateBioMass();//only needs to be here to replicate previous results // CalculateResidue();//only needs to be here to replicate previous results out_ResidueAmount_kg_per_ha = out_ResidueAmount_kg_per_ha + (dry_matter - yield) * 0.95 * 10.0; sim.VegetationController.CalculateTotalResidue(); out_WaterStressIndex = 1.0; ++number_of_crops_killed; yield = 0; out_Yield_t_per_ha = 0; ResetParametersForEndOfCrop(); //crop_stage=0; //dry_matter=0; // soil_water_at_harvest=sim.total_soil_water; //CropStatus=csInFallow; // crop_cover=0; // total_transpiration=0; // for(int i=0;i<sim.LayerCount;++i) // sim.layer_transpiration[i]=0; // lai=0; } /// <summary> /// /// </summary> public void ResetParametersForEndOfCrop() { CropStatus = ModelControllers.CropStatus.csInFallow; ++number_of_fallows; soil_water_at_harvest = sim.total_soil_water; sim.VegetationController.days_since_harvest = 0; //should this also get reset at crop death days_since_planting = 0; total_transpiration = 0; crop_cover = 0; crop_cover_percent = 0; crop_stage = 0; lai = 0; for (int i = 0; i < sim.in_LayerCount; ++i) sim.layer_transpiration[i] = 0; heat_unit_index = 0; out_RootDepth_mm = 0; green_cover = 0; out_GrowthRegulator = 0; dry_matter = 0; out_DryMatter_kg_per_ha = 0; out_PotTranspiration_mm = 0; } /// <summary> /// /// </summary> public void RecordCropStage() { // CropAnthesis=false; if (heat_unit_index <= dataModel.PropGrowSeaForMaxLai && !MathTools.DoublesAreEqual(dataModel.PropGrowSeaForMaxLai, 0)) { crop_stage = heat_unit_index * 2.0 / dataModel.PropGrowSeaForMaxLai; //anth=0; } else { if (MathTools.DoublesAreEqual(dataModel.PropGrowSeaForMaxLai, 0)) MathTools.LogDivideByZeroError("RecordCropStage", "in_PropSeasonForMaxLAI", "crop_stage"); //if(anth==0) // { // CropAnthesis=true; // anth=1; // } if (!MathTools.DoublesAreEqual(dataModel.PropGrowSeaForMaxLai, 1)) crop_stage = 2 + (heat_unit_index - dataModel.PropGrowSeaForMaxLai) / (1.0 - dataModel.PropGrowSeaForMaxLai); } } /// <summary> /// /// </summary> /// <returns></returns> public override double CalculatePotentialTranspiration() { // Calculate potential transpiration if (sim.ModelOptionsController.in_UsePERFECTGroundCovFn) green_cover = Math.Min(lai / 3.0, 1.0); else { if (lai > 0) green_cover = 1 - Math.Exp(-0.55 * (lai + 0.1)); // changed br on 9/12/2005 else green_cover = 0; } green_cover = Math.Max(0.0, green_cover); crop_cover = Math.Max(crop_cover, green_cover); double value = Math.Min(sim.out_PanEvap_mm * green_cover, sim.out_PanEvap_mm - sim.out_WatBal_SoilEvap_mm); if (value > sim.out_PanEvap_mm) value = sim.out_PanEvap_mm; out_GreenCover_pc = green_cover * 100.0; crop_cover_percent = crop_cover * 100.0; if (dataModel.WaterLoggingSwitch && IsWaterLogged()) value = value * dataModel.WaterLoggingFactor1; return value; } /// <summary> /// /// </summary> /// <returns></returns> public override bool StillRequiresIrrigating() { return (heat_units < dataModel.PropGDDEnd / 100.0 * (double)(dataModel.DegreeDaysPlantToHarvest)); } /// <summary> /// /// </summary> public new void CalculateResidue() { if (sim.ModelOptionsController.in_UsePERFECTResidueFn) CalculateResidue_PERFECT(); else CalculateResidue_BR(); total_cover = GetTotalCover(); out_TotalCover_pc = total_cover * 100.0; accumulated_residue += residue_cover * 100.0; } /// <summary> /// /// </summary> public void CalculateResidue_BR() { int seriesindex = sim.climateindex; double rain_yesterday = (seriesindex > 0 ? (sim.Rainfall)[seriesindex - 1] : 0); double rain_daybeforeyesterday = (seriesindex > 1 ? (sim.Rainfall)[seriesindex - 2] : 0); double mi = 4.0 / 7.0 * (Math.Min(sim.effective_rain, 4) / 4.0 + Math.Min(rain_yesterday, 4) / 8.0 + Math.Min(rain_daybeforeyesterday, 4) / 16.0); //moisture index //there is a minor problem here...doesn't take into consideration irrigation in the previous days. double ti = Math.Max(sim.temperature / 32.0, 0); // temperature index decompdays = Math.Min(Math.Min(mi, ti), 1); // min=0 days, max =1day // Will change this to a non-linear function in the near future. BR 14/09/2010 out_ResidueAmount_kg_per_ha = Math.Max(0, out_ResidueAmount_kg_per_ha - out_ResidueAmount_kg_per_ha * dataModel.MaxResidueLoss / 100.0 * decompdays); if (!MathTools.DoublesAreEqual(dataModel.BiomassAtFullCover, 0)) residue_cover = Math.Min(1.0, out_ResidueAmount_kg_per_ha / dataModel.BiomassAtFullCover); else { residue_cover = 0; MathTools.LogDivideByZeroError("CalculateResidue_BR", "in_BiomassAtFullCover", "residue_cover"); } if (residue_cover < 0) residue_cover = 0; out_ResidueCover_pc = residue_cover * 100.0; } /// <summary> /// /// </summary> public void CalculateResidue_PERFECT() { // ************************************************************ // * Subroutine decays residue and calculates surface cover * // ************************************************************ // Decay residue using Sallaway's functions if (CropStatus == ModelControllers.CropStatus.csInFallow) { if (days_since_fallow < 60) out_ResidueAmount_kg_per_ha = Math.Max(0, out_ResidueAmount_kg_per_ha - 15); else if (days_since_fallow >= 60) out_ResidueAmount_kg_per_ha = Math.Max(0, out_ResidueAmount_kg_per_ha - 3); days_since_fallow += 1; } else out_ResidueAmount_kg_per_ha = Math.Max(0, out_ResidueAmount_kg_per_ha - 15); // Calculate proportion cover from residue weight // using Sallaway type functions residue_cover = dataModel.MaximumResidueCover * (1.0 - Math.Exp(-1.0 * out_ResidueAmount_kg_per_ha / 1000.0)); if (residue_cover < 0) residue_cover = 0; if (residue_cover > 1) residue_cover = 1; out_ResidueCover_pc = residue_cover * 100.0; } } }