text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamOthellop.Model { public abstract class IOthelloAgent { /// <summary> /// Returns Agent's move of choice /// </summary> /// <param name="game"></param> /// <param name="player"></param> /// <returns>Location of choice move</returns> public abstract byte[] MakeMove(OthelloGame game, BoardStates player); } }
using Microsoft.SqlServer.Management.Smo; using SqlServerWebAdmin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SqlServerWebAdmin { public partial class EditDatabaseUser : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { //Response.Redirect("Error.aspx?errorPassCode=" + 2002); Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; User user = null; if (Request["User"] != null) { user = database.Users.Cast<User>().FirstOrDefault(i => i.Name == Request["User"].Replace("[", "").Replace("]", "")); } if (user == null) Response.Redirect("DatabaseUsers.aspx"); LoginLabel.Text = user.Login; DatabaseRoleCollection dbRoles = database.Roles; Roles.DataSource = dbRoles; Roles.DataBind(); foreach (string roleName in user.EnumRoles()) { ListItem roleItem = Roles.Items.FindByValue(roleName); if (roleItem != null) { roleItem.Selected = true; } } server.Disconnect(); } } protected void Save_Click(object sender, EventArgs e) { Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { //Response.Redirect("Error.aspx?errorPassCode=" + 2002); Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } try { Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; DatabaseRoleCollection dbRoles = database.Roles; User user = database.Users[Request["user"].Replace("[", "").Replace("]", "")]; foreach (ListItem item in Roles.Items) { if (!user.IsMember(item.Value) && item.Selected) { dbRoles[item.Value].AddMember(Request["user"]); } else if (user.IsMember(item.Value) && !item.Selected) { dbRoles[item.Value].DropMember(Request["user"]); } } } catch (Exception ex) { ErrorMessage.Text = ex.Message; return; } finally { server.Disconnect(); } Response.Redirect("~/Modules/DatabaseUser/DatabaseUsers.aspx?database=" + Server.UrlEncode(Request["database"])); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Windows.Forms; namespace MouseSpeedSwitcher { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { bool runone; Mutex run = new Mutex(true, "MouseSpeedSwitcher", out runone); if (runone) { run.ReleaseMutex(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (new Tray()) { Application.Run(); } } } } }
using System; using System.Collections.Generic; namespace POSServices.Models { public partial class DiscountRetailLines { public int Id { get; set; } public int DiscountRetailId { get; set; } public int? ArticleId { get; set; } public int? BrandCode { get; set; } public int? Gender { get; set; } public int? Department { get; set; } public int? Size { get; set; } public int? Color { get; set; } public decimal? DiscountPrecentage { get; set; } public decimal? CashDiscount { get; set; } public decimal? DiscountPrice { get; set; } public int? Qty { get; set; } public decimal? AmountTransaction { get; set; } public int? DepartmentType { get; set; } public int ArticleIdDiscount { get; set; } public DateTime? CreatedDate { get; set; } public int? QtyMin { get; set; } public int? QtyMax { get; set; } public decimal? AmountMin { get; set; } public decimal? AmountMax { get; set; } public virtual Item Article { get; set; } public virtual Item ArticleIdDiscountNavigation { get; set; } public virtual ItemDimensionBrand BrandCodeNavigation { get; set; } public virtual ItemDimensionColor ColorNavigation { get; set; } public virtual ItemDimensionDepartment DepartmentNavigation { get; set; } public virtual ItemDimensionDepartmentType DepartmentTypeNavigation { get; set; } public virtual ItemDimensionGender GenderNavigation { get; set; } public virtual ItemDimensionSize SizeNavigation { get; set; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Z.Framework.DbEntity { public class CoreDbInitialiser: DropCreateDatabaseIfModelChanges<zEntity> { protected override void Seed(zEntity context) { context.T_ACCOUNT.Add(new T_ACCOUNT() { ID=1, Account_Name = "zk", Account_Pwd = " 202cb962ac59075b964b07152d234b70", Is_Valid = true, Is_Deleted = false, }); context.T_ACCOUNT_INFO.Add(new T_ACCOUNT_INFO() { ID = 1, User_id = 1, User_Name = "Mr. Z", User_Code = "0001", Is_Deleted = false, Create_Time = DateTime.Now }); context.T_ACCOUNT_ROLES.Add(new T_ACCOUNT_ROLES() { ID = 1, User_Id = 1, Level = 999, Create_Time = DateTime.Now }); base.Seed(context); } } }
using Reactive.Flowable.Subscriber; using System; namespace Reactive.Flowable { public class FlowableWithUpstream<T, R> : IFlowable<R> { private readonly IFlowable<T> upstream; Action<T, ISubscriber<R>> onNextFilter; private readonly Action<int, ISubscription> onRequestFilter; public FlowableWithUpstream(IFlowable<T> upstream, Action<T, ISubscriber<R>> onNextFilter, Action<int, ISubscription> onRequestFilter = null) { this.upstream = upstream; this.onNextFilter = onNextFilter; this.onRequestFilter = onRequestFilter ?? ((n, s) => { s.Request(n); }); } public IDisposable Subscribe(ISubscriber<R> subscriber) { var upSubscriber = new LambdaSubscriber<T>( onNext: FilterComposer(subscriber), onError: subscriber.OnError, onComplete: subscriber.OnComplete, onSubscribe: (s, c) => { subscriber.OnSubscribe(s); c(); }, onRequest: this.onRequestFilter); return upstream.Subscribe(upSubscriber); } protected Action<T, Action> FilterComposer(ISubscriber<R> subscriber) { return (x, c) => { onNextFilter(x, subscriber); c(); }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Linq.Mapping; namespace upSight.CartaoCorp { public class RetornoCabecalhoBaseEN { #region Propriedades [Column(Name = "IdRetIdentCab", DbType = "INT NOT NULL")] public int IdRetIdentCab { get; set; } [Column(Name = "IdArquivo", DbType = "INT NOT NULL")] public int IdArquivo { get; set; } [Column(Name = "DataGeracao", DbType = "DATETIME2 NOT NULL")] public DateTime DataGeracao { get; set; } [Column(Name = "SeqArquivo", DbType = "TINYINT NOT NULL")] public byte SeqArquivo { get; set; } [Column(Name = "NomeArquivo", DbType = "VARCHAR(50) NOT NULL")] public string NomeArquivo { get; set; } [Column(Name = "CodConvenio", DbType = "VARCHAR(10) NOT NULL")] public string CodConvenio { get; set; } [Column(Name = "CodEmpresa", DbType = "VARCHAR(14) NOT NULL")] public string CodEmpresa { get; set; } [Column(Name = "NumLinha", DbType = "INT")] public int NumLinha { get; set; } #endregion } }
namespace Cs_Notas.Infra.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class CidadesIbge : DbMigration { public override void Up() { CreateTable( "dbo.CidadesIbge", c => new { CidadesIbgeId = c.Int(nullable: false, identity: true), Codigo = c.Int(nullable: false), Uf = c.String(maxLength: 2, unicode: false), Nome = c.String(maxLength: 60, unicode: false), }) .PrimaryKey(t => t.CidadesIbgeId); } public override void Down() { DropTable("dbo.CidadesIbge"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Serialization.Mappers { public interface ICorrelationMatrixManager { object[] GetObjects(object[] header); } }
namespace Zebble { using System; using System.Reflection; using System.Threading.Tasks; public partial class WebView : View, IRenderedBy<WebViewRenderer>, FormField.IControl { string url, html, ResourceNamespace; Assembly ResourceAssembly; public readonly AsyncEvent BrowserNavigated = new AsyncEvent(); public readonly AsyncEvent<NavigatingEventArgs> BrowserNavigating = new AsyncEvent<NavigatingEventArgs>(); /// <summary> /// Parameters are Error code and error text. /// </summary> public readonly AsyncEvent<string> LoadingError = new AsyncEvent<string>(); public readonly AsyncEvent LoadFinished = new AsyncEvent(); public readonly AsyncEvent SourceChanged = new AsyncEvent(); internal Func<string, Task<string>> EvaluatedJavascript; internal Func<string, string[], Task<string>> EvaluatedJavascriptFunction; public WebView() => Css.Height(100); public WebView(string url) => Url = url; public WebView(Assembly resourceAssembly, string resourceNamespace) { ResourceAssembly = resourceAssembly; ResourceNamespace = resourceNamespace; } public bool MergeExternalResources { get; set; } = true; public object Value { get => html; set => html = value.ToStringOrEmpty(); } public string Html { get => html; set => SetHtml(value).RunInParallel(); } public Task SetHtml(string value) { html = value; if (value.HasValue()) url = null; return SourceChanged.Raise(); } public string Url { get => url; set => SetUrl(value); } public Task SetUrl(string value) { url = value; if (value.HasValue()) html = null; return SourceChanged.Raise(); } public void OnBrowserNavigated(string newUrl, string newContent) { url = newUrl; html = newContent; BrowserNavigated.Raise(); } public bool OnBrowserNavigating(string newUrl) { if (!BrowserNavigating.IsHandled()) return false; var eventArgs = new NavigatingEventArgs { Cancel = false, Url = newUrl }; BrowserNavigating.Raise(eventArgs); return eventArgs.Cancel; } public void EvaluateJavaScript(string script) => EvaluatedJavascript?.Invoke(script); public void EvaluateJavaScriptFunction(string function, string[] args) => EvaluatedJavascriptFunction?.Invoke(function, args); public string GetExecutableHtml() { try { var html = Html; if (html.LacksValue()) { if (Url.LacksValue() || Url.Contains(":")) return null; var file = Device.IO.File(Url); if (!file.Exists()) return "File not found: " + Url; html = file.ReadAllText(); } if (html.Lacks("<html", caseSensitive: false)) return html; html = html.TrimBefore("<html", caseSensitive: false); return new ResourceInliner(html) { ResourceAssembly = ResourceAssembly, ResourceNamespace = ResourceNamespace, MergeExternalResources = MergeExternalResources } .Inline(); } catch (Exception ex) { return "ERROR: " + ex; } } public void Dispose() { LoadingError?.Dispose(); LoadFinished?.Dispose(); BrowserNavigated?.Dispose(); SourceChanged?.Dispose(); EvaluatedJavascript = null; EvaluatedJavascriptFunction = null; base.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Student.Mangmnet.Models; using Student.DAL; using System.Threading.Tasks; namespace Student.Mangmnet.Controllers { public class SubjectController : Controller { public ActionResult Index(string id = null) { SubjectModels model = new SubjectModels { SubjectId = Guid.NewGuid().ToString() }; return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Add(SubjectModels model) { if (!ModelState.IsValid) { return View("Error"); } try { StudnetDB studnetDB = new StudnetDB(); studnetDB.Subjects.Add(entity: new Subject() { SubjectId = model.SubjectId, SubjectName = model.Name }); await studnetDB.SaveChangesAsync(); return RedirectToAction("Index", "Home"); } catch { return View("Error"); } } } }
namespace ApartmentApps.Api { public class ExternalUnitImportInfo : IExternalUnitImportInfo { public string FirstName { get; set; } public string LastName { get; set; } public string UnitNumber { get; set; } public string BuildingName { get; set; } public string Address { get; set; } public string City { get; set; } public string State { get; set; } public string PostalCode { get; set; } public string Email { get; set; } public string MiddleName { get; set; } public bool IsVacant { get; set; } public string PhoneNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace V50_IDOMBackOffice.AspxArea.Booking.Models { public class PaymentViewModel { public string Id { get; set; } public string BookingId { get; set; } public string docType { get; set; } public DateTime Date { get; set; } public decimal Value { get; set; } public string Title { get; set; } public string PaymentType { get; set; } } }
namespace CaseManagement.DataObjects { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("ReferralType")] public partial class ReferralType { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public ReferralType() { ClientVisitReferrals = new HashSet<ClientVisitReferral>(); } public int referralTypeId { get; set; } [Required] [StringLength(50)] public string referralTypeName { get; set; } [JsonIgnore] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<ClientVisitReferral> ClientVisitReferrals { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; [RequireComponent(typeof(CapsuleCollider), typeof(Rigidbody))] public class PlayerController_Noah : MonoBehaviour { [SerializeField] private Rigidbody _rb; public float SPEED; //Player speed public float JUMP_THRUST = 1850; //Player jump thrust public float JUMP_DURATION; //Player jump duration public bool _isDashing = false; public Transform SAFEROOM_TRANSFORM; public GameObject DASH_NOT_READY_ICON; //public MemoryScript MEMENTO; //TEMPORARY QUICK FIX DO NOT KEEP FOREVER Vector3 dashForce; Transform[] array; bool dashReady = true; public float DASH_COOLDOWN = 3f; enum VIEW {TD,OTS}; //Top-down, Over-the-shoulder private VIEW _view; public GameObject OTS_CAMERA; public GameObject TD_CAMERA; public GameObject xRayVisionA; public GameObject xRayVisionB; // Use this for initialization void Start() { PrefsPaneManager.instance.AddLivePreferenceFloat("Player Speed", 0f, 20f, SPEED, playerSpeedChanged); PrefsPaneManager.instance.AddLivePreferenceFloat("Dash Cooldown", 0f, 10f, DASH_COOLDOWN, updateDASH_COOLDOWN); EnterViewOTS(); } // Switch from Topdown camera to Overthe soulder void EnterViewOTS() { _view = VIEW.OTS; OTS_CAMERA.SetActive(true); TD_CAMERA.SetActive(false); } //Switch from Over the shoulder camera to top down void EnterViewTD() { _view = VIEW.TD; OTS_CAMERA.SetActive(false); TD_CAMERA.SetActive(true); } // Update is called once per frame void FixedUpdate() { float inputHorizontal = Input.GetAxisRaw("Horizontal"); float inputVertical = Input.GetAxisRaw("Vertical"); float inputRHorizontal = Input.GetAxisRaw("RHorizontal"); float inputRVertical = Input.GetAxisRaw("RVertical"); if (_isDashing == false) { Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("DashableWall"), false); //Get "forward" and "right" from the perspective of the camera. Used by OTS Camera. Vector3 cameraForward = OTS_CAMERA.transform.forward; Vector3 cameraRight = OTS_CAMERA.transform.right; cameraForward.y = 0f; cameraRight.y = 0f; cameraForward.Normalize(); cameraRight.Normalize(); switch(_view) { case VIEW.OTS: //If the player presses W / Left analog up, the player should move forward relative to the camera. Vector3 direction = cameraForward*inputVertical+cameraRight*inputHorizontal; direction = direction.normalized; _rb.velocity = new Vector3(SPEED * direction.x, 0, SPEED * direction.z); break; case VIEW.TD: //If the player presses W / Left Ananlog UP, the player should move north. direction = new Vector3(inputHorizontal,0f,inputVertical); direction = direction.normalized; _rb.velocity = new Vector3(SPEED * direction.x, 0, SPEED * direction.z); break; } if (Input.GetButtonDown("Vision")) { xRayVisionA.SetActive (!xRayVisionA.activeSelf); xRayVisionB.SetActive (!xRayVisionB.activeSelf); // StartCoroutine(FadeWalls(this.gameObject.transform.position, 5.0f)); } if (dashReady && Input.GetButtonDown("Dash")) { _isDashing = true; switch(_view) { case VIEW.OTS: dashForce = cameraForward*inputVertical+cameraRight*inputHorizontal; dashForce = dashForce.normalized; break; case VIEW.TD: dashForce = new Vector3(inputHorizontal, 0, inputVertical); dashForce = dashForce.normalized; break; } StartCoroutine(FadeWalls(this.gameObject.transform.position, 5.0f)); dashReady = false; DASH_NOT_READY_ICON.SetActive(true); StartCoroutine(DashCountdown()); } if (Input.GetButtonDown("Door")) { StartCoroutine(OpenDoors(this.gameObject.transform.position, 5.0f)); } if (Input.GetButtonDown("Drop")) { StartCoroutine(OpenDoors(this.gameObject.transform.position, 5.0f)); /* if(MEMENTO.GetHeldBy() == MemoryScript.HeldBy.Player) { MEMENTO.SetHeldBy(MemoryScript.HeldBy.None); } */ } } else { Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Player"), LayerMask.NameToLayer("DashableWall"), true); _rb.AddForce(dashForce * JUMP_THRUST); } if(Input.GetKeyDown("r")) { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } if(Input.GetKeyDown("v")) { if(_view == VIEW.OTS) EnterViewTD(); else EnterViewOTS(); } } public IEnumerator FadeWalls(Vector3 center, float radius) { Collider[] hitColliders = Physics.OverlapSphere(center, radius); int i = 0; while (i < hitColliders.Length) { if (hitColliders[i].tag == "Wall") { //print(hitColliders[i].name); hitColliders[i].SendMessage("Fade"); if (_isDashing) { //hitColliders[i].SendMessage("Disable_Collision"); //print("Disable collision"); } } if (hitColliders[i].tag == "Enemy") { hitColliders[i].SendMessage("ChangeMat"); } i++; yield return null; } yield return new WaitForSeconds(JUMP_DURATION); _isDashing = false; StopCoroutine(FadeWalls(this.gameObject.transform.position, 2.0f)); } public IEnumerator OpenDoors(Vector3 center, float radius) { Collider[] hitColliders = Physics.OverlapSphere(center, radius); int i = 0; while (i < hitColliders.Length) { if (hitColliders[i].tag == "Door") { //print(hitColliders[i].name); hitColliders[i].SendMessage("ChangeDoorState"); } i++; yield return null; } yield return null; StopCoroutine(OpenDoors(center, radius)); } public IEnumerator DashCountdown() { yield return new WaitForSeconds(DASH_COOLDOWN); dashReady = true; DASH_NOT_READY_ICON.SetActive(false); print("Dash is ready after waiting " + DASH_COOLDOWN); yield return null; } public void playerSpeedChanged(float value) { SPEED = value; } public void updateDASH_COOLDOWN(float value) { DASH_COOLDOWN = value; } void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Enemy") { /* if(MEMENTO.GetHeldBy() == MemoryScript.HeldBy.Player) { MEMENTO.SetHeldBy(MemoryScript.HeldBy.None); } */ transform.position = SAFEROOM_TRANSFORM.position; } } }
using Alabo.Data.People.Internals.Domain.Entities; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using MongoDB.Bson; namespace Alabo.Data.People.Internals.Domain.Services { public class InternalService : ServiceBase<Internal, ObjectId>, IInternalService { public InternalService(IUnitOfWork unitOfWork, IRepository<Internal, ObjectId> repository) : base( unitOfWork, repository) { } } }
using System.Reflection; [assembly: AssemblyTitle("ThreeHeartDancePartner")] [assembly: AssemblyDescription("")] [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")]
using System; using System.ComponentModel.DataAnnotations; // REMEMEBR TO IMPORT THIS!!! namespace DojoSurvey.Models { public class Survey { [Required] [MinLength(2)] public string Name { get; set; } [Required] public string Location { get; set; } [Required] public string Language { get; set; } [MinLength(10)] [MaxLength(50)] public string Comments { get; set; } }; };
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PastorDialogue : MonoBehaviour { private Text dialogue; private TextScrambler scrambler; public void Start() { scrambler = this.GetComponent<TextScrambler>(); scrambler.forceUpdate = true; dayDialogue(); } public void dayDialogue() { switch (NPCPastor.Hope) { case 0: scrambler.StringBuffer = "How are you feeling, my child? Remember no matter how bleak it looks, it will get better as long as you believe. Right?"; scrambler.forceUpdate = true; break; case 10: scrambler.StringBuffer = "God has abandoned us in our time of need. All I feel is pain and suffering. If this is the life we must lead then I shall end it"; scrambler.forceUpdate = true; break; case 20: scrambler.StringBuffer = "What's the point? This is so tiring. All you people are the same. 'Awe look at me, I'm depressed.' It is the punishment from God"; scrambler.forceUpdate = true; break; case 30: scrambler.StringBuffer = "Wow, you don't look so good. That's ok though I can give you some help.... just ... just give me a little time, unless you need help now"; scrambler.forceUpdate = true; break; case 40: scrambler.StringBuffer = "Who am I kidding I've got no time for this. There are so many people I've got to help it's overwhelming. I want to be there, so I don't have time for a therapist. I'm doing fine right?"; scrambler.forceUpdate = true; break; case 50: scrambler.StringBuffer = "Gosh there are a lot of people with depression. I'm glad God put me on this Earth with the ability to help each and everyone of them. I've got to help, don't you agree?"; scrambler.forceUpdate = true; break; case 60: scrambler.StringBuffer = "It's ok to feel bad sometimes. I'm always here for people 24/7. I am a messenger of God and I believe I am the only one who can help"; scrambler.forceUpdate = true; break; case 70: scrambler.StringBuffer = "I'm glad to see that you are looking better, I'm so glad ... but I don't know. I just feel tired all the time. I just gotta keep focusing on helping others"; scrambler.forceUpdate = true; break; case 80: scrambler.StringBuffer = "I'm sorry I can't help you today. I need to spend some time to focus on myself. I've got a therapy session in 20, but I don't know I've always been in control, maybe I should just forget about it"; scrambler.forceUpdate = true; break; case 90: scrambler.StringBuffer = "You were, right. I spent so mych time looking after those who needed support and I forgot to look after myself. The best thing I ever did"; scrambler.forceUpdate = true; break; //do nothing default: scrambler.StringBuffer = "How are you feeling, my child? Remember no matter how bleak it looks, it will get better as long as you believe. Right?"; scrambler.forceUpdate = true; break; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Collections.Generic; using System.Linq; using ApartmentApps.Client.Models; using Newtonsoft.Json.Linq; namespace ApartmentApps.Client.Models { public static partial class CourtesyCheckinBindingModelCollection { /// <summary> /// Deserialize the object /// </summary> public static IList<CourtesyCheckinBindingModel> DeserializeJson(JToken inputObject) { IList<CourtesyCheckinBindingModel> deserializedObject = new List<CourtesyCheckinBindingModel>(); foreach (JToken iListValue in ((JArray)inputObject)) { CourtesyCheckinBindingModel courtesyCheckinBindingModel = new CourtesyCheckinBindingModel(); courtesyCheckinBindingModel.DeserializeJson(iListValue); deserializedObject.Add(courtesyCheckinBindingModel); } return deserializedObject; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace KenanPROJEKT { public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ddlCar.DataBind(); ddlCar.SelectedIndex = 0; getInfo(); } } string er = ""; protected void btnAdd_Click(object sender, EventArgs e) { string constr = ConfigurationManager.ConnectionStrings["RentCarConnectionString"].ConnectionString; try { if (String.IsNullOrEmpty(txtFname.Value) || String.IsNullOrEmpty(txtLname.Value) || String.IsNullOrEmpty(txtEmail.Value) || String.IsNullOrEmpty(txtPhone.Value)) { lblFillAll.Visible = true; } else { using (SqlConnection connection = new SqlConnection(constr)) { String query = "INSERT INTO Reservations (First_Name, Last_Name, Email, Phone_Number, CarID, Date_Start, Date_End) VALUES (@firstname, @lastname, @email, @phone, @carid, @start, @end)"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@firstname", txtFname.Value); command.Parameters.AddWithValue("@lastname", txtLname.Value); command.Parameters.AddWithValue("@email", txtEmail.Value); command.Parameters.AddWithValue("@phone", txtPhone.Value); command.Parameters.AddWithValue("@carid", ddlCar.SelectedValue); command.Parameters.AddWithValue("@start", datepicker.Value); command.Parameters.AddWithValue("@end", datepicker2.Value); connection.Open(); int result = command.ExecuteNonQuery(); // Check Error if (result < 0) { lblFillAll.Text = "Error inserting data into Database!"; lblFillAll.Visible = true; } } } } } catch (Exception ex) { er = ex.ToString(); } finally { txtFname.Value = ""; txtLname.Value = ""; txtEmail.Value = ""; txtPhone.Value = ""; datepicker.Value = ""; datepicker2.Value = ""; if (String.IsNullOrEmpty(er)) ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Car has been booked in your name!')", true); } } protected void ddlCar_SelectedIndexChanged(object sender, EventArgs e) { getInfo(); } protected void getInfo() { string constr = ConfigurationManager.ConnectionStrings["RentCarConnectionString"].ConnectionString; try { using (SqlConnection connection = new SqlConnection(constr)) { String query = "SELECT Model, Year FROM Cars WHERE ID='" + ddlCar.SelectedValue + "'"; using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { if (reader.HasRows) { // Read advances to the next row. while (reader.Read()) { lblModel.Text = (reader["Model"].ToString()); lblYear.Text = (reader["Year"].ToString()); } } } } } } catch (Exception ex) { string er = ex.ToString(); } finally { } } } }
using System; using Windows.Foundation; using Windows.Graphics.Display; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace SampleUWP { public sealed partial class S02 : Page { // A pointer to MainPage is needed if you want to call methods or variables in MainPage. private readonly MainPage mainPage = MainPage.mainPagePointer; public S02() { InitializeComponent(); // Setup mainScroller to handle scrolling for this page. mainPage.MainScrollerOn(horz: ScrollMode.Disabled, vert: ScrollMode.Auto, vertVis: ScrollBarVisibility.Auto); } /// <summary> /// Explore various information that can be accessed from Page SizeChange event. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_SizeChanged(object sender, SizeChangedEventArgs e) { // Check out what is passed by 'e'. string output = "\nPage_SizeChanged---> "; output += "CurrentDeviceFamily=" + mainPage.currentDeviceFamily + ", "; // Retrieved when MainPage() loaded but chose to show here. //output += String.Format("e.GetTpe={0:} ", e.GetType()); //output += String.Format("e.OriginalSource={0:} ", e.OriginalSource); // Returns null in this case //output += String.Format("e.PreviousSize=({0:0.}) ", e.PreviousSize); output += string.Format("New Size=({0:0.}) ", e.NewSize); // Check out what is passed by sender and look up some unfamilar stuff. if (sender is Page page) { //output += String.Format("ActualWidth={0:0.} ", page.ActualWidth); // Same width as NewSize above //output += String.Format("ActualHeight={0:0.} ", page.ActualHeight); // Same height as NewSize above //output += String.Format("Width={0:0.} ", page.Width); //Returns NaN == Not a Number //output += String.Format("Height={0:0.} ", page.Height); //Returns NaN == Not a Number output += string.Format("GetType={0} ", page.GetType()); //Returns SampleUWP.P01 //output += String.Format("Parent={0} ", page.Parent); //output += String.Format("Frame={0} ", page.Frame); // Same as Parent above in this case //output += String.Format("RenderSize=({0:0.}) ", page.RenderSize); //output += String.Format("CancelDirManip={0:} ", page.CancelDirectManipulations()); // Does nothing and returns False DependencyObject parent = page.Parent; if(parent is Frame frame ) { output += "ParentFrameName=" + frame.Name + ", "; output += string.Format("ParentFrameSize=({0:0.}, {1:0.}).", frame.ActualWidth, frame.ActualHeight); } } PageInfo.Text = output; // Get other information and display it too WindowBounds(); WindowAppView(); WindowDisplayInfo(); } /// <summary> /// Force manual update the WindowBounds data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateWinInfo1_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. WindowBounds(); } /// <summary> /// Method to explore Window.Current.Bounds options. /// </summary> private void WindowBounds() { Rect window = Window.Current.Bounds; //double x = window.X; // Get/set left side of window //double y = window.Y; // Get/set top side of window double width = window.Width; // Get/set width of window double height = window.Height; // Get/set height of window double left = window.Left; // Get left side of window double top = window.Top; // Get top of window double right = window.Right; // Get right of window double bottom = window.Bottom; // Get bottom of window // More about formating doubles here: http://www.csharp-examples.net/string-format-double/ string output = "Window.Current.Bounds---> "; //output += String.Format("X,Y = ({0:0.}, {1:0.}), ", x, y); output += string.Format("Width, Height=({0:0.}, {1:0.}), ", width, height); output += string.Format("Left, Top = ({0:0.}, {1:0.}), ", left, top); output += string.Format("Right, Bottom = ({0:0.}, {1:0.}).", right, bottom); //output += String.Format("(X+Width), (Y+Height) = ({0:0.}, {1:0.}).", x + width, y + height); WinInfo1.Text = output; } /// <summary> /// Force manual update the WindowAppView data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateWinInfo2_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. WindowAppView(); } /// <summary> /// Method to explore ApplicationView options. /// </summary> private void WindowAppView() { ApplicationView appView = ApplicationView.GetForCurrentView(); string output = "ApplicationView---> "; output += string.Format("Current Orientation={0}, ", appView.Orientation); output += string.Format("AdjacentLeftEdge={0}, ", appView.AdjacentToLeftDisplayEdge); // Is window set to left edge of display. output += string.Format("AdjacentRightEdge={0}, ", appView.AdjacentToRightDisplayEdge); // Is window set to right edge of display' output += string.Format("Full Screen Mode={0}, ", appView.IsFullScreenMode); // Is window in full-screen mode. output += string.Format("Visible Bounds={0}.", appView.VisibleBounds); /* Can use following code to set name on application title bar for each page. But Microsoft is not doing it with their apps. * Somewhat redundant since page title is on title bar right below. appView.Title = "Home"; output += String.Format("Title={0} ", appView.Title); */ WinInfo2.Text = output; } /// <summary> /// Force manual update the WindowDisplayInfo data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateWinInfo3_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. WindowDisplayInfo(); } /// <summary> /// Method to explore DisplayInformation options. /// </summary> private void WindowDisplayInfo() { DisplayInformation displayInfo = DisplayInformation.GetForCurrentView(); string output = "DisplayInformation---> "; output += string.Format("Current Orientation={0}, ", displayInfo.CurrentOrientation); //output += String.Format("NativeOrientation={0} ", displayInfo.NativeOrientation); output += string.Format("API Diagonal={0:0.00}\", ", displayInfo.DiagonalSizeInInches); output += string.Format("Resolution Scale={0}, ", displayInfo.ResolutionScale); // Enumeration output += string.Format("LogicalDPI={0:0.}, ", displayInfo.LogicalDpi); output += string.Format("RawDpiX={0:0.}, ", displayInfo.RawDpiX); output += string.Format("RawDpiY={0:0.}, ", displayInfo.RawDpiY); output += string.Format("RawPixels/ViewPixel={0:0.000}.", displayInfo.RawPixelsPerViewPixel); //output += String.Format("ColorProfile={0} ", displayInfo.GetColorProfileAsync()); // Returns nothing useful WinInfo3.Text = output; } /// <summary> /// Toggle view to full screen mode or back. While in full screen mode activates getMonitorInfo button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ToggleFullScreenMode_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. ApplicationView appView = ApplicationView.GetForCurrentView(); if (appView.IsFullScreenMode) { appView.ExitFullScreenMode(); // Takes app out of full screen mode. GetMonitorInfo.IsEnabled = false; // Turn button off } else { appView.TryEnterFullScreenMode(); // Will attempt to place app in full screen mode. GetMonitorInfo.IsEnabled = true; // Turn button on } } /// <summary> /// getMonitorInfo button is enabled only after in full screen mode. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GetMonitorInfo_Click(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. GetMonitorResolution(); } /// <summary> /// Get the resolution of the current monitor. Also calculates the horizontal, vertical, and diagonal dimensions of /// the monitor. Must be in full screen mode before calling to get proper results. Timing issues!!! /// </summary> private void GetMonitorResolution() { string output; ApplicationView appView = ApplicationView.GetForCurrentView(); if (appView.IsFullScreenMode) { DisplayInformation displayInfo = DisplayInformation.GetForCurrentView(); //Enum orient = appView.Orientation; double width = appView.VisibleBounds.Width; double height = appView.VisibleBounds.Height; double scale = (double)displayInfo.ResolutionScale / 100.0; // Cast scale enumeration into double percentage DisplayOrientations currentOrient = displayInfo.CurrentOrientation; DisplayOrientations nativeOrient = displayInfo.NativeOrientation; double diagSize = (double)displayInfo.DiagonalSizeInInches; //double logicDPI = displayInfo.LogicalDpi; double xRawDPI = displayInfo.RawDpiX; double yRawDPI = displayInfo.RawDpiY; _ = displayInfo.RawPixelsPerViewPixel; double wRes = width * scale; double hRes = height * scale; double wInches = wRes / xRawDPI; double hInches = hRes / yRawDPI; double diagInches = Math.Sqrt(Math.Pow(wInches, 2.0) + Math.Pow(hInches, 2.0)); // Calculate the diagonal dimension. output = "GetMonitorResolution---> "; //output += String.Format("Width={0:0.} ", width); //output += String.Format("Height={0:0.} ", height); //output += String.Format("Scale={0:0.00} ", scale); output += string.Format("Resolution=({0:0.}, {1:0.}), ", wRes, hRes); output += string.Format("Width={0:0.00}\", ", wInches); output += string.Format("Height={0:0.00}\", ", hInches); output += string.Format("Diagonal={0:0.00}\", ", diagInches); output += string.Format("API Diagonal={0:0.00}\", ", diagSize); output += string.Format("Current Orientation={0}, ", currentOrient); output += string.Format("Native Orientation={0}.", nativeOrient); } else { output = "Error: Not in full screen mode before calling GetMonitorResolution() method."; } WinInfo4.Visibility = Visibility.Visible; WinInfo4.Text = output; } /// <summary> /// After page loads, set the state of getMonitorInfo button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_Loaded(object sender, RoutedEventArgs e) { _ = sender; // Discard unused parameter. _ = e; // Discard unused parameter. ApplicationView appView = ApplicationView.GetForCurrentView(); if (appView.IsFullScreenMode) GetMonitorInfo.IsEnabled = true; else GetMonitorInfo.IsEnabled = false; } } }
using AlgorithmProblems.Linked_List.Linked_List_Helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Linked_List { class CopyLinkedListWithRandomNode { public static LinkedListNodeWithRandomPointer<int> GetCopiedLinkedListWithRandomNode(LinkedListNodeWithRandomPointer<int> linkedListWithRndNode) { LinkedListNodeWithRandomPointer<int> currentNode = linkedListWithRndNode; LinkedListNodeWithRandomPointer<int> copiedLinkedListHead = null; // insert the copied nodes in between the original linked list node chain while(currentNode != null) { LinkedListNodeWithRandomPointer<int> copiedNode = new LinkedListNodeWithRandomPointer<int>(currentNode.Data); copiedNode.NextNode = currentNode.NextNode; if (copiedLinkedListHead == null) { copiedLinkedListHead = copiedNode; } currentNode.NextNode = copiedNode; currentNode = copiedNode.NextNode; } currentNode = linkedListWithRndNode; while(currentNode!=null) { LinkedListNodeWithRandomPointer<int> copiedNode = currentNode.NextNode; copiedNode.RandomNode = currentNode.RandomNode; currentNode = copiedNode.NextNode; copiedNode.NextNode = (copiedNode.NextNode != null) ? copiedNode.NextNode.NextNode : null; } return copiedLinkedListHead; } public static void TestGetCopiedLinkedListWithRandomNode() { LinkedListNodeWithRandomPointer<int> linkedListhead = LinkedListHelper.CreateSinglyLinkedListWithRandomPointer(10); Console.WriteLine("The linked list is as shown below:"); LinkedListHelper.PrintLinkedListWithRandomPointer(linkedListhead); LinkedListNodeWithRandomPointer<int> copiedlinkedListhead = GetCopiedLinkedListWithRandomNode(linkedListhead); Console.WriteLine("The copied linked list is as shown below:"); LinkedListHelper.PrintLinkedListWithRandomPointer(copiedlinkedListhead); } } }
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 CoVID { public partial class LoadForm : Form { public Action worker { get; set; } public LoadForm(Action worker) { InitializeComponent(); if (worker == null) { throw new ArgumentNullException(); } this.worker = worker; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); Task.Factory.StartNew(this.worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext()); } } }
namespace _08._MultiplyBigNumber { using System; using System.Numerics; public class Startup { public static void Main() { BigInteger firstNumber = BigInteger.Parse(Console.ReadLine()); BigInteger secondNumber = BigInteger.Parse(Console.ReadLine()); Console.WriteLine(firstNumber * secondNumber); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ButtonParameter : MonoBehaviour { [Tooltip("正常时文本大小")] public int fontNormalSize = 50; [Tooltip("悬浮时文本大小")] public int fonthighlightSize = 70; [Tooltip("正常时文本颜色")] public Color fontNormalColor = Color.white; [Tooltip("悬浮时文本颜色")] public Color fontHighlightedColor = Color.black; }
using Alabo.Cache; using Alabo.Domains.Repositories; using Alabo.Domains.Services; using Alabo.Helpers; using System; using ZKCloud.Open.ApiBase.Connectors; using ZKCloud.Open.ApiBase.Formatters; using ZKCloud.Open.DiyClient; namespace Alabo.Tool.Payment { public abstract class ApiStoreClient : RestClientBase, IApiStoreClient { protected ApiStoreClient(Uri baseUri, IConnector connector, IDataFormatter formatter) : base(baseUri, connector, formatter) { } public IObjectCache ObjectCache => Ioc.Resolve<IObjectCache>(); public T Repository<T>() where T : IRepository { return Ioc.Resolve<T>(); } public T Service<T>() where T : IService { return Ioc.Resolve<T>(); } } }
using System; using UnityEngine; using UnityEngine.UI; public class Level25 : MonoBehaviour { public Color clickedColor; public Color defaultColor; public AudioClip clip; public Sprite snakeSprite; private GameObject[] letters; private string command; private AudioSource audioSource; private GameObject player; private GameObject winPoint; private GameObject[] skeletons; private enum Commands { DOWN, LEFT, RIGHT, DOWEN } private void Start() { letters = GameObject.FindGameObjectsWithTag("Letters"); audioSource = GetComponent<AudioSource>(); player = GameObject.FindGameObjectWithTag("Player"); winPoint = GameObject.FindGameObjectWithTag("WinPoint"); skeletons = GameObject.FindGameObjectsWithTag("Object"); } public void OnLetterClick(UnityEngine.Object obj) { GameObject clickedObj = (GameObject)obj; Text text = clickedObj.GetComponent<Text>(); if (text.color != clickedColor) { text.color = clickedColor; command += text.text; } Debug.Log(command); CheckCommand(); } private void CheckCommand() { var playerMove = player.GetComponent<MovableObject>(); switch (command) { case "DOWEN": audioSource.PlayOneShot(clip); Array.ForEach(skeletons, x => { var sprite = x.GetComponent<SpriteRenderer>(); sprite.sprite = snakeSprite; }); ResetText(); break; case "DOWN": playerMove.Move(Vector2.down); ResetText(); break; case "LEFT": playerMove.Move(Vector2.left); ResetText(); break; case "UP": playerMove.Move(Vector2.up); ResetText(); break; case "RIGHT": playerMove.Move(Vector2.right); ResetText(); break; case "WIN": playerMove.transform.position = winPoint.transform.position; ResetText(); break; } CheckWin(); } public void ResetText() { foreach (var letter in letters) { Text text = letter.GetComponent<Text>(); text.color = defaultColor; } command = ""; } private void CheckWin() { var tiles = GameObject.FindGameObjectsWithTag("Tile"); bool outOfField = Array.Exists(tiles, tile => tile.transform.position == player.transform.position); if (!Utilites.IsTargetVisible(Camera.main, player) || !outOfField) { Utilites.RestartScene(); } Array.ForEach(skeletons, skeleton => { if (skeleton.transform.position == player.transform.position) { Utilites.RestartScene(); } }); if (player.transform.position == winPoint.transform.position) { Debug.Log("Win"); GameManager.instance.NextLevel(); } } }
using eMAM.Data.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace eMAM.Service.DbServices.Contracts { public interface IStatusService { Task<Status> GetInitialStatusAsync(); Task<Status> GetStatusByName(string statusName); //Task<Status> GetStatusAsync(string textStatus); } }
using System; using System.Linq; using Fingo.Auth.DbAccess.Models; using Fingo.Auth.DbAccess.Models.CustomData.Enums; using Fingo.Auth.DbAccess.Repository.Interfaces; using Fingo.Auth.Domain.CustomData.ConfigurationClasses; using Fingo.Auth.Domain.CustomData.ConfigurationClasses.Project; using Fingo.Auth.Domain.CustomData.ConfigurationClasses.User; using Fingo.Auth.Domain.CustomData.Factories.Actions.Interfaces; using Fingo.Auth.Domain.CustomData.Services.Interfaces; namespace Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation { public class EditProjectCustomDataToProject : IEditProjectCustomDataToProject { private readonly ICustomDataJsonConvertService _jsonConvertService; private readonly IProjectRepository _projectRepository; public EditProjectCustomDataToProject(IProjectRepository projectRepository , ICustomDataJsonConvertService jsonConvertService) { _jsonConvertService = jsonConvertService; _projectRepository = projectRepository; } public void Invoke(int projectId , string name , ConfigurationType type , ProjectConfiguration configuration , string oldName) { var project = _projectRepository.GetByIdWithCustomDatas(projectId); if (project == null) throw new ArgumentNullException($"Could not find project with id: {projectId}."); var customData = project.ProjectCustomData.FirstOrDefault(data => data.ConfigurationName == oldName); if (customData == null) throw new Exception($"You cannot edit non-existing custom data (name: {oldName})."); customData.ConfigurationName = name; customData.ConfigurationType = type; customData.SerializedConfiguration = _jsonConvertService.Serialize(configuration); EditConfigurationForUsers(name , type , configuration , project); _projectRepository.Edit(project); } private void EditConfigurationForUsers(string name , ConfigurationType type , ProjectConfiguration configuration , Project project) { switch (type) { case ConfigurationType.Boolean: { break; } case ConfigurationType.Number: { EditNumberConfigurationToUsers((NumberProjectConfiguration) configuration , project , name); break; } case ConfigurationType.Text: { EditTextConfigurationToUsers((TextProjectConfiguration) configuration , project , name); break; } default: throw new ArgumentOutOfRangeException(nameof(type) , type , null); } } //private void EditBooleanConfigurationToUsers(Project project , string configurationName , string oldName) //{ // if (configurationName == oldName) // return; // foreach (var projectProjectUser in project.ProjectUsers) // { // foreach (var projectCustomData in project.ProjectCustomData.Where(m=> m.ConfigurationName == oldName)) // { // try // { // var userCustomData = // projectCustomData.UserCustomData.FirstOrDefault(m => m.UserId == projectProjectUser.UserId); // projectCustomData.UserCustomData.Remove(userCustomData); // userCustomData.ModificationDate = DateTime.UtcNow; // projectCustomData.UserCustomData.Add(userCustomData); // } // catch (Exception) // { // //ignore // } // } // } //} private void EditNumberConfigurationToUsers(NumberProjectConfiguration configuration , Project project , string configurationName) { var projectCustomData = project.ProjectCustomData.FirstOrDefault(m => m.ConfigurationName == configurationName); foreach (var userCustomData in projectCustomData.UserCustomData) try { var userConfiguration = (NumberUserConfiguration) _jsonConvertService.DeserializeUser(ConfigurationType.Number , userCustomData.SerializedConfiguration); var userValueUpdateIsNeeded = (userConfiguration.Value < configuration.LowerBound) || (userConfiguration.Value > configuration.UpperBound); if (!userValueUpdateIsNeeded) continue; userConfiguration.Value = configuration.Default; userCustomData.SerializedConfiguration = _jsonConvertService.Serialize(userConfiguration); userCustomData.ModificationDate = DateTime.UtcNow; } catch (Exception) { //ignore } } private void EditTextConfigurationToUsers(TextProjectConfiguration configuration , Project project , string configurationName) { var projectCustomData = project.ProjectCustomData.FirstOrDefault(m => m.ConfigurationName == configurationName); foreach (var userCustomData in projectCustomData.UserCustomData) try { var userConfiguration = (TextUserConfiguration) _jsonConvertService.DeserializeUser(ConfigurationType.Text , userCustomData.SerializedConfiguration); var userValueUpdateIsNeeded = !(configuration.PossibleValues.Contains(userConfiguration.Value) || (configuration.Default == userConfiguration.Value)); if (!userValueUpdateIsNeeded) continue; userConfiguration.Value = configuration.Default; userCustomData.SerializedConfiguration = _jsonConvertService.Serialize(userConfiguration); userCustomData.ModificationDate = DateTime.UtcNow; } catch (Exception) { //ignore } } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using EdjCase.JsonRpc.Router; using EdjCase.JsonRpc.Router.Defaults; using FiiiChain.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiiiChain.Wallet.API { public class BaseRpcController : RpcController { public RpcMethodErrorResult Error(int errorCode, string message, Exception exception = null) { if(errorCode != ErrorCode.UNKNOWN_ERROR) { LogHelper.Error(message, exception); } else { LogHelper.Fatal(message, exception); } return base.Error(errorCode, message, new { Time = Time.EpochTime }); } } }
/** 版本信息模板在安装目录下,可自行修改。 * tb_error.cs * * 功 能: N/A * 类 名: tb_error * * Ver 变更日期 负责人 变更内容 * ─────────────────────────────────── * V0.01 2017-04-05 10:52:23 N/A 初版 * * Copyright (c) 2012 Maticsoft Corporation. All rights reserved. *┌──────────────────────────────────┐ *│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │ *│ 版权所有:动软卓越(北京)科技有限公司              │ *└──────────────────────────────────┘ */ using System; namespace ND.FluentTaskScheduling.Model { /// <summary> /// tb_error:实体类(属性说明自动提取数据库字段的描述信息) /// </summary> public partial class tb_error { public tb_error() {} #region Model private int _id; private string _msg; private int _errortype; private DateTime _errorcreatetime; private int _taskid; private int _nodeid; /// <summary> /// /// </summary> public int id { set{ _id=value;} get{return _id;} } /// <summary> /// /// </summary> public string msg { set{ _msg=value;} get{return _msg;} } /// <summary> /// /// </summary> public int errortype { set{ _errortype=value;} get{return _errortype;} } /// <summary> /// /// </summary> public DateTime errorcreatetime { set{ _errorcreatetime=value;} get{return _errorcreatetime;} } /// <summary> /// /// </summary> public int taskid { set{ _taskid=value;} get{return _taskid;} } /// <summary> /// /// </summary> public int nodeid { set{ _nodeid=value;} get{return _nodeid;} } #endregion Model } }
using HtmlAgilityPack; using System; using System.Collections; 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 HtmlDocument = HtmlAgilityPack.HtmlDocument; namespace GETMOOTOOL { public partial class Form1 : Form { private static string strSearchUrl = "https://avmoo.cyou/cn/search/"; public Form1() { InitializeComponent(); this.lbl_Count.Text = ""; this.textBoxSearchUrl.Text = strSearchUrl; } DataClass data = new DataClass(); FileClass f = new FileClass(); //从code查询页面开始,多个code需要以逗号分隔开来 private void but_ok1_Click(object sender, EventArgs e) { if (textBoxCode.Text.Trim().Length < 1) { SetListBoxMessage("Code不能为空"); return; } string[] strCodes = textBoxCode.Text.Trim().ToUpper().Split(','); int intCount = 0; foreach (string code in strCodes) { intCount++; lbl_Count.Text = string.Format("{0}/{1}", intCount, strCodes.Length); if (code.Trim().Length > 0) { if (data.CheckMo(code.Trim())) { SetListBoxMessage("已经收录此影片:"+ code.Trim()); continue; } string url = ""; string strSmallImgUrl = ""; try { //从CODE开始 string urlSearch = textBoxSearchUrl.Text.Trim() + code.Trim(); HtmlWeb web = new HtmlWeb(); //从url中加载 HtmlDocument sdoc = web.Load(urlSearch); //2种方式获取搜索结果的url //HtmlNodeCollection sNode = sdoc.DocumentNode.SelectNodes("//*[@id='waterfall']"); //url = sNode[0].SelectSingleNode(".//a").Attributes["href"].Value; try { HtmlNode tNode = sdoc.DocumentNode.SelectSingleNode("//h4"); if (tNode.InnerText.Trim().Contains("搜寻没有结果")) { SetListBoxMessage("Code:" + code + " 没有找到"); continue; } } catch (Exception) { } //HtmlNodeCollection aNode = doc.DocumentNode.SelectNodes("//*[@class='col-md-9 screencap']"); //*号代表通配符,表示所有class为此名的节点 //HtmlNode img = aNode[0].SelectSingleNode(".//img"); //strImgUrl = aNode[0].SelectSingleNode(".//img").Attributes["src"].Value; //img.Attributes["src"].Value; //HtmlNode sNode = sdoc.DocumentNode.SelectSingleNode("//div[@id='waterfall']"); HtmlNodeCollection nodes = sdoc.DocumentNode.SelectNodes("//a[@class='movie-box']"); foreach (var item in nodes) { HtmlNode sNode = item.SelectSingleNode(".//date"); if (sNode.InnerHtml.Trim().ToUpper() == code.Trim()) { //HtmlNodeCollection htmlNodesUrl = item.SelectNodes(".//href"); url = item.Attributes["href"].Value; //HtmlNodeCollection htmlNodesIndexImgUrl = item.SelectNodes(".//img"); strSmallImgUrl = item.SelectSingleNode(".//img").Attributes["src"].Value;//htmlNodesIndexImgUrl[0].Attributes["src"].Value; break; } } //HtmlNodeCollection htmlNodesUrl = sNode.SelectNodes(".//a"); //HtmlNodeCollection htmlNodesIndexImgUrl = sNode.SelectNodes(".//img"); //url = htmlNodesUrl[0].Attributes["href"].Value; //strSmallImgUrl = htmlNodesIndexImgUrl[0].Attributes["src"].Value; SetListBoxMessage(url); SetListBoxMessage(strSmallImgUrl); } catch (Exception) { SetListBoxMessage("CODE没有搜索到结果,中断执行。"); return; } GetMovieIndexHtmlInfo(url, strSmallImgUrl); } } } //从影片主页开始 private void but_ok2_Click(object sender, EventArgs e) { //从影片主页开始 if (textBoxUrl.Text.Trim().Length < 1) { SetListBoxMessage("URL不能为空"); return; } GetMovieIndexHtmlInfo(textBoxUrl.Text.Trim(), ""); } /// <summary> /// GetMovieIndexPageInfo /// </summary> /// <param name="strUrl"></param> private void GetMovieIndexHtmlInfo(string strUrl, string strSmallImgUrl) { bool boolGetActerInfo = false; string strNoNameActer = "NoName"; Movie m = new Movie(); m.SmallImgUrl = strSmallImgUrl; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(strUrl); //加载影片主页 //获取影片代码和影片名字 HtmlNode tNode = doc.DocumentNode.SelectSingleNode("//h3"); //有些字符不能作为文件名使用,需要替换掉 string[] strNonFileNames = new string[] { "?", "*", ":", "<", ">", "\\", "/", "|", "\"" }; string strMovieNameTemp = tNode.InnerText; foreach (string strchar in strNonFileNames) { strMovieNameTemp = strMovieNameTemp.Replace(strchar, " "); } m.MovieName = strMovieNameTemp; //用空格替换不能做文件名的字符 m.Code = m.MovieName.Split(' ')[0]; //这里提前获取code以便判断是否已经获取过了,提前结束 if (data.CheckMo(m.Code)) { SetListBoxMessage("已经收录此影片"); return; } SetListBoxMessage(m.MovieName); SetListBoxMessage(m.Code); //2种方式获取影片的海报 //HtmlNodeCollection aNode = doc.DocumentNode.SelectNodes("//*[@class='col-md-9 screencap']"); //*号代表通配符,表示所有class为此名的节点 //HtmlNode img = aNode[0].SelectSingleNode(".//img"); //strImgUrl = aNode[0].SelectSingleNode(".//img").Attributes["src"].Value; //img.Attributes["src"].Value; HtmlNode aNode = doc.DocumentNode.SelectSingleNode("//div[@class='col-md-9 screencap']"); HtmlNodeCollection htmlNodesImgUrl = aNode.SelectNodes(".//img"); m.ImgUrl = htmlNodesImgUrl[0].Attributes["src"].Value; SetListBoxMessage(m.ImgUrl); //获取影片的基本信息 //HtmlNodeCollection bNode = doc.DocumentNode.SelectNodes("//*[@class='col-md-3 info']"); HtmlNode bNode = doc.DocumentNode.SelectSingleNode("//div[@class='col-md-3 info']"); HtmlNodeCollection bCollection = bNode.ChildNodes; string[] strsAllData = new string[100]; int icount = 0; foreach (var item in bCollection) { if (item.ChildNodes.Count > 0) { for (int i = 0; i < item.ChildNodes.Count; i++) { if (item.ChildNodes[i].InnerHtml.Trim().Length > 0) { string[] strs = item.ChildNodes[i].InnerHtml.Trim().Split('>'); if (strs.Length > 1) { SetListBoxMessage(strs[1].Trim().Replace("</a", "")); strsAllData[icount] = strs[1].Trim().Replace("</a", ""); icount++; } else { SetListBoxMessage(item.ChildNodes[i].InnerHtml.Trim().Replace(":", "")); strsAllData[icount] = item.ChildNodes[i].InnerHtml.Trim().Replace(":", ""); icount++; } } } } } if (strsAllData.Length > 0) { for (int i = 0; i < strsAllData.Length; i++) { switch (strsAllData[i]) { case "识别码": m.Code = strsAllData[i + 1]; break; case "发行时间": m.PublishTime = strsAllData[i + 1]; break; case "长度": m.Times = strsAllData[i + 1].Replace("分钟", ""); break; case "导演": m.Director = strsAllData[i + 1]; break; case "制作商": m.Maker = strsAllData[i + 1]; break; case "发行商": m.Publisher = strsAllData[i + 1]; break; case "系列": m.Series = strsAllData[i + 1]; break; case "类别": for (int j = i + 1; j < strsAllData.Length + 1; j++) { if (strsAllData[j] == null) { break; } m.ListType.Add(strsAllData[j]); } break; default: break; } } } try { //获取女演员的姓名、主页和照片 HtmlNode cNode = doc.DocumentNode.SelectSingleNode("//div[@id='avatar-waterfall']"); HtmlNodeCollection htmlNodesActerIndex = cNode.SelectNodes(".//a"); //获取下面的全部a标签 HtmlNodeCollection htmlNodesActerImg = cNode.SelectNodes(".//img"); //获取下面的全部img标签 HtmlNodeCollection htmlNodesActerName = cNode.SelectNodes(".//span");//获取下面的全部span标签 foreach (var item in htmlNodesActerIndex) { m.ListActerIndexUrl.Add(item.Attributes["href"].Value); SetListBoxMessage(item.Attributes["href"].Value); } foreach (var item in htmlNodesActerImg) { m.ListActerImgUrl.Add(item.Attributes["src"].Value); SetListBoxMessage(item.Attributes["src"].Value); } foreach (var item in htmlNodesActerName) { m.ListActerName.Add(item.InnerHtml.Trim()); SetListBoxMessage(item.InnerHtml.Trim()); } } catch (Exception) { boolGetActerInfo = true; SetListBoxMessage("无演员名单"); } try { //获取影片快照 HtmlNodeCollection dNode = doc.DocumentNode.SelectNodes("//a[@class='sample-box']"); foreach (var item in dNode) { m.ListSnapshotUrl.Add(item.Attributes["href"].Value); SetListBoxMessage(item.Attributes["href"].Value); } } catch (Exception) { SetListBoxMessage("无影片快照"); } try { //获取缩小的影片快照 HtmlNode eNode = doc.DocumentNode.SelectSingleNode("//div[@id='sample-waterfall']"); HtmlNodeCollection htmlNodesShort = eNode.SelectNodes(".//img"); //获取下面的全部img标签 foreach (var item in htmlNodesShort) { m.ListSmallSnapshotUrl.Add(item.Attributes["src"].Value); SetListBoxMessage(item.Attributes["src"].Value); } } catch (Exception) { SetListBoxMessage("无影片快照"); } //////////////////////////////////////////// ////所有获取到的演员和影片信息插入数据库//// //////////////////////////////////////////// //这里需要在数据库中判断表中是否有女演员信息,若没有的话,需要循环抓取插入 //bool boolGetimg = true; if (m.ListActerName.Count > 0) { for (int i = 0; i < m.ListActerName.Count; i++) { if (data.CheckActer(m.ListActerName[i].ToString())) //判断是否有此女演员资料,若无,则进入演员主页抓取资料插入表中 { boolGetActerInfo = true; } else { boolGetActerInfo = GetActerIndexHtmlInfo(m.ListActerName[i].ToString(), m.ListActerImgUrl[i].ToString(), m.ListActerIndexUrl[i].ToString()); if (!boolGetActerInfo) { SetListBoxMessage("获取女演员:" + m.ListActerName[i].ToString() + " 资料失败"); break; } } if (boolGetActerInfo) { //开始获取影片海报和快照图片,并写入到硬盘返回本地网站url更新list, //由于多演员的影片每个演员专辑下都要保存图片,所以获取大小封面的方法要多跑 if (m.ImgUrl.Length > 0) { m.ImgUrl = f.SaveMovieImg(ref m, m.Code, m.MovieName, m.ListActerName[i].ToString(), m.ImgUrl); } if (m.SmallImgUrl.Length > 0) { m.SmallImgUrl = f.SaveMovieSmallImg(ref m, m.Code, m.MovieName, m.ListActerName[i].ToString(), m.SmallImgUrl); } for (int k = 0; k < m.ListSnapshotUrl.Count; k++) { m.bShotImg.Add(null); m.bSmallShotImg.Add(null); if (m.ListSnapshotUrl[k].ToString().Length > 0) { m.ListSnapshotUrl[k] = f.SaveMovieShotImg(ref m, m.Code, m.MovieName, m.ListActerName[i].ToString(), m.ListSnapshotUrl[k].ToString(), k + 1); } if (m.ListSmallSnapshotUrl[k].ToString().Length > 0) { m.ListSmallSnapshotUrl[k] = f.SaveMovieSmallShotImg(ref m, m.Code, m.MovieName, m.ListActerName[i].ToString(), m.ListSmallSnapshotUrl[k].ToString(), k + 1); } } } } } else { //开始获取影片海报和快照图片,并写入到硬盘返回本地网站url更新list(无演员的情况) if (m.ImgUrl.Length > 0) { m.ImgUrl = f.SaveMovieImg(ref m, m.Code, m.MovieName, strNoNameActer, m.ImgUrl); } if (m.SmallImgUrl.Length > 0) { m.SmallImgUrl = f.SaveMovieSmallImg(ref m, m.Code, m.MovieName, strNoNameActer, m.SmallImgUrl); } for (int k = 0; k < m.ListSnapshotUrl.Count; k++) { m.bShotImg.Add(null); m.bSmallShotImg.Add(null); if (m.ListSnapshotUrl[k].ToString().Length > 0) { m.ListSnapshotUrl[k] = f.SaveMovieShotImg(ref m, m.Code, m.MovieName, strNoNameActer, m.ListSnapshotUrl[k].ToString(), k + 1); } if (m.ListSmallSnapshotUrl[k].ToString().Length > 0) { m.ListSmallSnapshotUrl[k] = f.SaveMovieSmallShotImg(ref m, m.Code, m.MovieName, strNoNameActer, m.ListSmallSnapshotUrl[k].ToString(), k + 1); } } } if (boolGetActerInfo) { //开始写入影片信息到数据表 string strDirectorid = ""; string strMakerid = ""; string strPublisherid = ""; string strSeriesid = ""; //获取影片各属性id if (m.Director.Length > 0) { strDirectorid = data.CheckInsertDirector(m.Director); } if (m.Maker.Length > 0) { strMakerid = data.CheckInsertMaker(m.Maker); } if (m.Publisher.Length > 0) { strPublisherid = data.CheckInsertPublisher(m.Publisher); } if (m.Series.Length > 0) { strSeriesid = data.CheckInsertSeries(m.Series); } if (m.ListType.Count > 0) { foreach (var item in m.ListType) { data.CheckInsertType(item.ToString()); } } if (data.InsertMovieInfo(m, strDirectorid, strMakerid, strPublisherid, strSeriesid)) { SetListBoxMessage("影片抓取成功"); } } SetListBoxMessage(""); } /// <summary> /// GetActerIndexPageInfo /// </summary> /// <param name="strName"></param> /// <param name="strPhotoUrl"></param> /// <param name="strUrl"></param> /// <returns></returns> private bool GetActerIndexHtmlInfo(string strName, string strPhotoUrl, string strIndexUrl) { bool boolResult = false; Acter ac = new Acter(); ac.Name = strName; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(strIndexUrl); //加载女演员主页 try { HtmlNode aNode = doc.DocumentNode.SelectSingleNode("//div[@class='photo-info']"); HtmlNodeCollection htmlNodesActerInfo = aNode.SelectNodes(".//p"); //获取下面的全部p标签 foreach (var item in htmlNodesActerInfo) { if (item.InnerText.Trim().Length > 1) { if (item.InnerText.Trim().Contains("生日")) { ac.Birthday = item.InnerText.Trim().Split(':')[1].Trim(); SetListBoxMessage(ac.Birthday); } else if (item.InnerText.Trim().Contains("年龄")) { ac.Age = item.InnerText.Trim().Split(':')[1].Trim(); SetListBoxMessage(ac.Age); } else if (item.InnerText.Trim().Contains("身高")) { ac.Height = item.InnerText.Trim().Split(':')[1].Trim().Replace("cm", ""); SetListBoxMessage(ac.Height); } else if (item.InnerText.Trim().Contains("罩杯")) { ac.Cup = item.InnerText.Trim().Split(':')[1].Trim(); SetListBoxMessage(ac.Cup); } else if (item.InnerText.Trim().Contains("胸围")) { ac.Bust = item.InnerText.Trim().Split(':')[1].Trim().Replace("cm", ""); SetListBoxMessage(ac.Bust); } else if (item.InnerText.Trim().Contains("腰围")) { ac.Waistline = item.InnerText.Trim().Split(':')[1].Trim().Replace("cm", ""); SetListBoxMessage(ac.Waistline); } else if (item.InnerText.Trim().Contains("臀围")) { ac.Hips = item.InnerText.Trim().Split(':')[1].Trim().Replace("cm", ""); SetListBoxMessage(ac.Hips); } else if (item.InnerText.Trim().Contains("出生地")) { ac.BirthPlace = item.InnerText.Trim().Split(':')[1].Trim(); SetListBoxMessage(ac.BirthPlace); } else if (item.InnerText.Trim().Contains("爱好")) { ac.Hobby = item.InnerText.Trim().Split(':')[1].Trim(); SetListBoxMessage(ac.Hobby); } } } //女演员的头像下载并保存,并返回本地网址url路径 strPhotoUrl = f.SaveActerImg(strName, strPhotoUrl); //女演员资料插入数据库返回布尔值 boolResult = data.InsetActerInfo(ac, strPhotoUrl); } catch(Exception ex) { SetListBoxMessage("获取女演员基本资料时出错:" + ex.ToString()); } return boolResult; } //ListBox输出信息 internal void SetListBoxMessage(string str) { if (listBoxResult.InvokeRequired) { Action<string> actionDelegate = (x) => { listBoxResult.Items.Add(str); listBoxResult.TopIndex = listBoxResult.Items.Count - (int)(listBoxResult.Height / listBoxResult.ItemHeight); }; listBoxResult.Invoke(actionDelegate, str); } else { listBoxResult.Items.Add(str); listBoxResult.TopIndex = listBoxResult.Items.Count - (int)(listBoxResult.Height / listBoxResult.ItemHeight); } } } }
/*------------------------------------------------------------------------------------------------------------- * Programa: Ejercicio 9 * Autor: Douglas W. Jurado Peña * Versión: DAM 2018/2019 * Descripción: Escribe un programa que tome todos los ficheros dados como argumentos en la línea de comando y los muestre por * pantalla el contenido de uno tras otro, separando cada contenido por una línea horizontal y el nombre del fichero que * se mostrará. -------------------------------------------------------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace R8_Ejercicio9 { class Program { static void Main(string[] args) { FileInfo archivo; FileStream flujo; StreamReader lector; for (int i = 0; i < args.Length; i++) { flujo = new FileStream(args[i], FileMode.Open, FileAccess.Read); lector = new StreamReader(flujo); archivo = new FileInfo(args[i]); Console.WriteLine("\n\nNombre --> {0}", archivo.Name); Console.WriteLine(lector.ReadToEnd()); Console.WriteLine("".PadLeft(40, '─')); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; using MongoNet.Controller; namespace MongoNet { class Program { static void Main(string[] args) { var connectionStr = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; var getControl = new GetController(); var delControl = new DeleteController(); // ATTENTIONS TABLE: // List true ? show list of traffics from your datetime (timestamp) to end : show last traffic; // 1630730919 from 8 days ago to now (day 5) 3 day in total //getControl.getTrafficsGtTime(connStr: connectionStr, list: true, timestamp: 1630730919); // Getting specific traffic by timestamp //getControl.getOneTraffic(connStr: connectionStr, timestamp: 1630730919); // Put your object id //delControl.deleteTrafficByObjID(connStr: connectionStr, objID: "613da5ef39c8be2ac4bc3b8f"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using Atomic.DbProvider; using Autofac; using Autofac.Builder; using Autofac.Core.Lifetime; namespace Atomic.Dependency { /// <summary> /// 依赖注入管理者 /// </summary> public class DependencyManager : IDependencyManager, IDependencyLifetimeScope, IDisposable { #region Variable /// <summary> /// IOC当前容器接口实例 /// </summary> private Autofac.IContainer _container = null; /// <summary> /// IOC的lifetimeScope接口实例 /// </summary> private IDependencyLifetimeScope _lifetimeScop = null; /// <summary> /// 当前只读的不解析的类型集合 /// </summary> private List<Type> _notResolveTypes = new List<Type>(); #endregion #region IDependencyManager /// <summary> /// 当前指定不解析的类型只读集合 /// </summary> public ReadOnlyCollection<Type> NotResolveTypes { get { return this._notResolveTypes.AsReadOnly(); } } /// <summary> /// 追加指定不解析的类型 /// </summary> /// <param name="types"></param> public void AddNotResolveTypes(params Type[] types) { if (null == types || types.Length <= 0) return; foreach (var type in types) { if (this._notResolveTypes.Contains(type)) continue; this._notResolveTypes.Add(type); } } /// <summary> /// 移除已指定的不解析的类型 /// </summary> /// <param name="types"></param> public void DelNotResolveTypes(params Type[] types) { if (null == types || types.Length <= 0) return; foreach (var type in types) { if (!this._notResolveTypes.Contains(type)) continue; this._notResolveTypes.Remove(type); } } /// <summary> /// 依赖引擎初始化(再次初始化等于重新构造) /// </summary> public void Initialize() { #region 1.初始化固定系统级注册 ContainerBuilder builder = new ContainerBuilder(); builder.Register<ITypeFinder>(c => new TypeDefaultFinder()).SingleInstance(); builder.Register<IDbMappingHandler>(c => new DbMappingHandler()).SingleInstance(); //加密&解密 this.CryptographyRegistration(builder); this._container = builder.Build(); ITypeFinder typeFinder = this._container.Resolve<ITypeFinder>(); if (null == typeFinder) throw new Exception("typeFinder is not register!"); #endregion #region 2.IDependencyLifetimeScope引擎接口注册 IEnumerable<Type> lifetimeScopeTypes = typeFinder.FindClassesOfType<IDependencyLifetimeScope>(); int lifetimeScopeClassTotal = lifetimeScopeTypes.Count(d => d.FullName != this.GetType().FullName); if (lifetimeScopeClassTotal <= 0) { this._lifetimeScop = this; } else { if (lifetimeScopeClassTotal > 1) throw new Exception("IDependencyLifetimeScope接口的实现只用在全局实现一次即可,切勿多次实现!"); this._lifetimeScop = Activator.CreateInstance(lifetimeScopeTypes.First()) as IDependencyLifetimeScope; } #endregion #region 3.IDependencyRegisterHook 外部挂钩注册 IEnumerable<Type> hookTypes = typeFinder.FindClassesOfType<IDependencyRegisterHook>(); if (hookTypes.Any()) { builder = new ContainerBuilder(); List<IDependencyRegisterHook> hookList = new List<IDependencyRegisterHook>(); foreach (var hookT in hookTypes) { hookList.Add(Activator.CreateInstance(hookT) as IDependencyRegisterHook); } hookList = hookList.AsQueryable().OrderBy(d => d.Priority).ToList(); hookList.ForEach(o => o.Register(builder, typeFinder)); builder.Update(this._container); } #endregion #region 99.挂载自身接口与实现的注册(单例) builder = new ContainerBuilder(); builder.RegisterInstance(this).As(typeof(IDependencyManager), typeof(IDependencyResolver)).SingleInstance(); builder.Update(this._container); #endregion #region 100.将注册的IDependencyRebuildDelegate接口实现进行纳入执行 IEnumerable<Type> rebuildDelegateTypes = typeFinder.FindClassesOfType<IDependencyInitComplete>(); List<IDependencyInitComplete> taskList = new List<IDependencyInitComplete>(); foreach (var taskT in rebuildDelegateTypes) { taskList.Add(Activator.CreateInstance(taskT) as IDependencyInitComplete); } foreach (var taskOpt in taskList.AsQueryable().OrderBy(d => d.Priority)) { taskOpt.OnCompleted(this._container); } #endregion } #endregion #region IDependencyResolver /// <summary> /// 是否可被解析出来 /// </summary> /// <param name="type"></param> /// <param name="regName"></param> /// <returns></returns> public bool IsRegistered(Type type, string regName = null) { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); if (string.IsNullOrEmpty(regName)) return scope.IsRegistered(type); else return scope.IsRegisteredWithName(regName, type); } /// <summary> /// 是否可被解析出来 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="regName"></param> /// <returns></returns> public bool IsRegistered<T>(string regName = null) { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); if (string.IsNullOrEmpty(regName)) return scope.IsRegistered<T>(); else return scope.IsRegisteredWithName<T>(regName); } /// <summary> /// 根据参数类型进行依赖解析 /// </summary> /// <param name="type"></param> /// <param name="regName"></param> /// <param name="parameters"></param> /// <returns></returns> public object Resolve(Type type, string regName = null, params KeyValuePair<string, object>[] parameters) { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); if (null != parameters && parameters.Length > 0) { List<Autofac.Core.Parameter> paramList = new List<Autofac.Core.Parameter>(); foreach (var item in parameters) { paramList.Add(new NamedParameter(item.Key, item.Value)); } if (string.IsNullOrEmpty(regName)) return scope.Resolve(type, paramList); else return scope.ResolveNamed(regName, type, paramList); } else { if (string.IsNullOrEmpty(regName)) return scope.Resolve(type); else return scope.ResolveNamed(regName, type); } } /// <summary> /// 根据泛型T进行依赖解析 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="regName"></param> /// <param name="parameters"></param> /// <returns></returns> public T Resolve<T>(string regName = null, params KeyValuePair<string, object>[] parameters) where T : class { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); if (null != parameters && parameters.Length > 0) { List<Autofac.Core.Parameter> paramList = new List<Autofac.Core.Parameter>(); foreach (var item in parameters) { paramList.Add(new NamedParameter(item.Key, item.Value)); } if (string.IsNullOrEmpty(regName)) return scope.Resolve<T>(paramList); else return scope.ResolveNamed<T>(regName, paramList); } else { if (string.IsNullOrEmpty(regName)) return scope.Resolve<T>(); else return scope.ResolveNamed<T>(regName); } } /// <summary> /// 根据泛型T进行依赖解析 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameters"></param> /// <returns></returns> public T[] ResolveAll<T>(params KeyValuePair<string, object>[] parameters) { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); if (null != parameters && parameters.Length > 0) { List<Autofac.Core.Parameter> paramList = new List<Autofac.Core.Parameter>(); foreach (var item in parameters) { paramList.Add(new NamedParameter(item.Key, item.Value)); } return scope.Resolve<IEnumerable<T>>(paramList).ToArray(); } else { return scope.Resolve<IEnumerable<T>>().ToArray(); } } /// <summary> /// 尝试解析指定的类型 /// </summary> /// <param name="serviceType"></param> /// <param name="instance"></param> /// <returns></returns> public bool TryResolve(Type serviceType, out object instance) { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); return scope.TryResolve(serviceType, out instance); } /// <summary> /// 解析未注册的类型 /// </summary> /// <param name="type"></param> /// <returns></returns> public object ResolveUnregistered(Type type) { Autofac.ILifetimeScope scope = this._lifetimeScop.GetScope(this._container); var constructors = type.GetConstructors(); foreach (var constructor in constructors) { try { var parameters = constructor.GetParameters(); var parameterInstances = new List<object>(); foreach (var parameter in parameters) { var service = scope.Resolve(parameter.ParameterType); if (service == null) { throw new Exception(string.Format("未知的参数类型{0}", parameter.ParameterType)); } parameterInstances.Add(service); } return Activator.CreateInstance(type, parameterInstances.ToArray()); } catch { continue; } } throw new Exception("未发现满足依赖解析的构造函数"); } #endregion #region IDependencyLifetimeScope /// <summary> /// 获取生命周期实例 /// </summary> /// <param name="container"></param> /// <returns></returns> ILifetimeScope IDependencyLifetimeScope.GetScope(Autofac.IContainer container) { return this._container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag); } #endregion #region IDisposable /// <summary> /// 实例析构资源释放 /// </summary> public void Dispose() { if (null != this._container) { this._container.Dispose(); } } #endregion #region Private Methods /// <summary> /// 加密/解密接口注册 /// </summary> /// <param name="builder"></param> private void CryptographyRegistration(ContainerBuilder builder) { builder.RegisterType<DesSymmetricAlgorithm>() .As(typeof(IEncryptAlgorithm), typeof(IDecryptAlgorithm), typeof(IDesSymmetricAlgorithm)) .Named<IEncryptAlgorithm>(CryptoMethods.DES) .Named<IDecryptAlgorithm>(CryptoMethods.DES) .Named<IDesSymmetricAlgorithm>(CryptoMethods.DES).InstancePerDependency(); } #endregion } }
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 mainMDI { public partial class ReturnFrm : Form { public ReturnFrm() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { if(txtBookNumber.Text == "") { if(cobBookTitle.Text == "") { MessageBox.Show("Please enter book title", "Incomplete", MessageBoxButtons.OK, MessageBoxIcon.Information); } MessageBox.Show("Please enter book number","Incomplete",MessageBoxButtons.OK,MessageBoxIcon.Information); txtBookNumber.Focus(); } } } }
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.Xml; using System.Xml.Linq; using System.IO; using System.Windows.Data; using EdicionSwExProperty; using Lite.Resources.Localization; using System.Windows.Navigation; using System.ServiceModel; using SpatialEye.Framework.Client; using System.Runtime.Serialization; using System.ServiceModel.Web; using System.Windows.Browser; using System.Runtime.Serialization.Json; using System.Text; using SpatialEye.Framework.ComponentModel.Design; using SpatialEye.Framework.Features; namespace Lite { public partial class EdicionSwView : UserControl { XElement doc = new XElement("Tabla"); string strgeometry = string.Empty; public EdicionSwView() { InitializeComponent(); Indicador.Visibility = Visibility.Collapsed; LeerXml(); } #region Eventos //Evento del combo que inicia seleccionando una tabla y generar los controles public void cboTablas_SelectionChanged(object sender, SelectionChangedEventArgs e) { try { Indicador.InProgress = true; Indicador.Visibility = Visibility.Visible; if (cboTablas.SelectedIndex >= 0) { if ((string)cboTablas.SelectedValue != "Seleccione") { GetTableName((string)cboTablas.SelectedValue); } else { stkDatos.Children.Clear(); } } Indicador.InProgress = false; Indicador.Visibility = Visibility.Collapsed; } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); Indicador.InProgress = false; Indicador.Visibility = Visibility.Collapsed; } } //Evento para realizar la inserción de datos private void btnInserta_Click(object sender, RoutedEventArgs e) { string type_accion = "ALTA"; try { MessageBoxResult result = MessageBox.Show("Desea insertar la información.?", "Edición", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { if (validaStatusNuevo() == false) { MessageBox.Show("Estatus no válido para insertar"); } else { if (strgeometry == "punto") { if (txtLatitudP.Text == string.Empty) { MessageBox.Show("Latitud no válida"); return; } if (txtLongitudP.Text == string.Empty) { MessageBox.Show("Longitud no válida"); return; } } else if (strgeometry == "linea") { if (txtLatitudT.Text == string.Empty) { MessageBox.Show("Latitud no válida"); return; } if (txtLongitudT.Text == string.Empty) { MessageBox.Show("Longitud no válida"); return; } } else if (strgeometry == "area") { if (txtLatitudTC.Text == string.Empty) { MessageBox.Show("Latitud no válida"); return; } if (txtLongitudTC.Text == string.Empty) { MessageBox.Show("Longitud no válida"); return; } } post_webservice(type_accion); } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } //Evento para la modificación de datos private void btnModifica_Click(object sender, RoutedEventArgs e) { string type_accion = "MODIFICAR"; try { MessageBoxResult result = MessageBox.Show("Desea modificar la información.?", "Edición", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { if (validaStatusNuevo() == false) { MessageBox.Show("Estatus no válido para modificar"); return; } //Validar si es para la Tabla Optical Splitter //Validar que no se reduzca el número de ports de 8 a 16 unicamente // if ((string)cboTablas.SelectedValue == "Optical Splitter") { //Recorrer Controles tipo ComboBox foreach (var child in stkDatos.Children.OfType<ComboBoxExt>()) { var splitcambio = from splt in doc.Descendants("split") where (string)splt.Attribute("name") == (string)child.SelectedValue.ToString() select splt.Attribute("value").Value; var split = from splt in doc.Descendants("split") where (string)splt.Attribute("name") != (string)child.SelectedValue.ToString() select splt.Attribute("value").Value; if(splitcambio.Count() > 0) { if(split.Count()>0) { for(int s =0; s< split.Count(); s++) { if(Convert.ToInt16(splitcambio.First()) < Convert.ToInt16(split.ElementAt(s))) { MessageBox.Show("Valor no válido para modificar."); return; } } //Si no cambio el valor no enviar nada int max = 0; foreach (string cant in lblNames.Content.ToString().Split('|')) { max++; } string[,] lsNames = new string[max, 2]; int i = 0; foreach (string name in lblNames.Content.ToString().Split('|')) { lsNames[i, 0] = name; i++; } int j = 0; foreach (string value in lblValues.Content.ToString().Split('|')) { lsNames[j, 1] = value; j++; } bool bolID = false; bool boolVal = false; foreach (var childtxt in stkDatos.Children.OfType<TextBoxEx>()) { for (int x = 0; x < max; x++) { //Si el nombre del control y valor del textbox son iguales poner bandera en true if((string)childtxt.Name == lsNames[x,0].ToString() && (string)childtxt.Text == lsNames[x, 1].ToString() && bolID== false) { bolID = true; } //Si el nombre del control y el valor del combobox son iguales poner bandera en true if ( (string)child.Name.ToString() == lsNames[x, 0].ToString() && (string)child.SelectedValue.ToString() == lsNames[x, 1].ToString() && boolVal == false) { boolVal = true; } //Si las 2 banderas son true terminar if(bolID == true && boolVal== true) { return; } } } } } else { MessageBox.Show("Valor no válido para modificar."); return; } } } post_webservice(type_accion); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } //Evento para la baja de datos private void btnElimina_Click(object sender, RoutedEventArgs e) { string type_accion = "BAJA"; try { MessageBoxResult result = MessageBox.Show("Desea eliminar la información.?", "Edición", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { if (validaStatusNuevo() == false) { MessageBox.Show("Estatus no válido para eliminar"); return; } post_webservice(type_accion); } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } //Evento para limpiar los datos de los controles private void btnLimpia_Click(object sender, RoutedEventArgs e) { try { this.Limpia(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } } //Evento para obtener los valores del elemento seleccionado del mapa private void btnObtener_Click(object sender, RoutedEventArgs e) { string tabla = (string)this.lblTabla.Content; if (tabla != string.Empty) { this.cboTablas.SelectedValue = tabla; GetTableName((string)tabla); } //Limpiar this.Limpia(); if (lblNames.Content != null && lblValues.Content != null) { //Crear Lista int max = 0; foreach (string cant in lblNames.Content.ToString().Split('|')) { max++; } string[,] lsNames = new string[max, 2]; int i = 0; foreach (string name in lblNames.Content.ToString().Split('|')) { lsNames[i, 0] = name; i++; } int j = 0; foreach (string value in lblValues.Content.ToString().Split('|')) { lsNames[j, 1] = value; j++; } //Recorrer los controles y validar coincidencias e insertar valor en el control if (lsNames.Length > 0) { //Recorrer Controles de tipo TextBox foreach (var child in stkDatos.Children.OfType<TextBoxEx>()) { //Recorrer Lista for (int x = 0; x < max; x++) { if (child.Name == lsNames[x, 0]) { child.Text = lsNames[x, 1]; } } } //Recorrer Controles tipo ComboBox foreach (var child in stkDatos.Children.OfType<ComboBoxExt>()) { //Recorrer Lista for (int x = 0; x < max; x++) { /*SI EL COMBO ES Visible? activarlo*/ if(child.Name == "visible?") { child.IsEnabled = true; } if (child.Name == lsNames[x, 0]) { //Validación de combo visible?, convertir los valores booleanos en string para asignarlos al combo if (child.Name == "visible?") { if (Convert.ToBoolean(lsNames[x, 1]) == true) { child.SelectedValue = "true"; } else { child.SelectedValue = "false"; } } else { child.SelectedValue = lsNames[x, 1]; } } } } //Recorrer Controles tipo Date foreach(var child in stkDatos.Children.OfType<DatePickerExt>()) { //Recorrer Lista for (int x = 0; x < max; x++) { if (child.Name == lsNames[x, 0]) { child.Text = lsNames[x, 1]; } } } } } } #endregion #region Metodos //Metódo para leer el archivo xml con la información de los datos void LeerXml() { try { //string source = Application.Current.Host.Source.ToString(); //int lastSlash = source.LastIndexOf(@"/") + 1; //string xmlLocation = source.Substring(0, lastSlash) + "Datos.xml"; //Uri url = new Uri(xmlLocation); WebClient wc = new WebClient(); wc.OpenReadCompleted += wc_OpenReadCompleted; Uri uri = new Uri("Datos.xml", UriKind.RelativeOrAbsolute); wc.OpenReadAsync(uri); //wc.OpenReadAsync(url); } catch (Exception ex) { MessageBox.Show("Error:" + ex.Message); } } //Metódo para cargar los datos del XML al Combo private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { try { if (e.Error != null) { //MessageBox.Show("Error: " + e.Error.Message); return; } using (Stream s = e.Result) { doc = XElement.Load(s); //lblInventario.Content = doc.ToString(SaveOptions.OmitDuplicateNamespaces); var tables = ( from tab in doc.Elements("table") select tab.Attribute("name_external").Value ).ToList(); tables.Add("Seleccione"); cboTablas.ItemsSource = tables; cboTablas.SelectedItem = "Seleccione"; } } catch { } } //Método para obtener el nombre de la tabla seleccionada en el combo public void GetTableName(string tableName) { bool ingrupo = false; this.txtLatitudP.Text = string.Empty; this.txtLongitudP.Text = string.Empty; this.txtLatitudT.Text = string.Empty; this.txtLongitudT.Text = string.Empty; this.txtLatitudTC.Text = string.Empty; this.txtLongitudTC.Text = string.Empty; //Validaciones List<LiteEdicionSWDefinition> lista = new List<LiteEdicionSWDefinition>(); var filtro = from tabla in doc.Descendants("table") where (string)tabla.Attribute("name_external") == (string)tableName select tabla; lista = ( from field in filtro.Elements("field") select new LiteEdicionSWDefinition { Internal_Name = field.Attribute("internal_name") != null ? field.Attribute("internal_name").Value : "false", External_Name = field.Attribute("external_name") != null ? field.Attribute("external_name").Value : "false", Type = field.Attribute("type") != null ? field.Attribute("type").Value : "false", Visible = field.Attribute("visible") != null ? field.Attribute("visible").Value : "false", Datalist = field.Attribute("datalist") != null ? field.Attribute("datalist").Value : "false", Size = field.Attribute("size") != null ? field.Attribute("size").Value : "false", Mandatory = field.Attribute("mandatory") != null ? field.Attribute("mandatory").Value : "false", Enabled = field.Attribute("enabled") != null ? field.Attribute("enabled").Value : "false" } ).ToList(); subGeneraControles(lista); //Activar si es Punto o Trazo List<LiteEdicionSWDefinition> lstGeometry = new List<LiteEdicionSWDefinition>(); lstGeometry = (from tabla in doc.Descendants("table") where (string)tabla.Attribute("name_external") == (string)tableName select new LiteEdicionSWDefinition { Geometry = tabla.Attribute("geometry").Value, } ).ToList(); if (lstGeometry.Count > 0) { strgeometry = lstGeometry[0].Geometry; if (strgeometry == "punto") { this.txtLatitudP.Visibility = Visibility.Visible; this.txtLongitudP.Visibility = Visibility.Visible; this.txtLatitudT.Visibility = Visibility.Collapsed; this.txtLongitudT.Visibility = Visibility.Collapsed; this.txtLatitudTC.Visibility = Visibility.Collapsed; this.txtLongitudTC.Visibility = Visibility.Collapsed; } else if (strgeometry == "linea") { this.txtLatitudP.Visibility = Visibility.Collapsed; this.txtLongitudP.Visibility = Visibility.Collapsed; this.txtLatitudT.Visibility = Visibility.Visible; this.txtLongitudT.Visibility = Visibility.Visible; this.txtLatitudTC.Visibility = Visibility.Collapsed; this.txtLongitudTC.Visibility = Visibility.Collapsed; } else if (strgeometry == "area") { this.txtLatitudP.Visibility = Visibility.Collapsed; this.txtLongitudP.Visibility = Visibility.Collapsed; this.txtLatitudT.Visibility = Visibility.Collapsed; this.txtLongitudT.Visibility = Visibility.Collapsed; this.txtLatitudTC.Visibility = Visibility.Visible; this.txtLongitudTC.Visibility = Visibility.Visible; } } //grupos seguridad var grupos = ( from tab in doc.Elements("group") select tab.Attribute("name").Value ).ToList(); if (grupos.Count > 0 && lblGrupos.Content !=null ) { for (int i = 0; i < grupos.Count; i++) { foreach (string value in lblGrupos.Content.ToString().Split('|')) { //Si esta en el grupo salir if (grupos[i].ToString() == value) { ingrupo = true; break; } } } } //Validar si se encuentra en el grupo if (ingrupo == false) { this.btnInserta.IsEnabled = false; this.btnModifica.IsEnabled = false; this.btnElimina.IsEnabled = false; this.btnLimpia.IsEnabled = false; this.btnObtener.IsEnabled = false; } else { //Validar insert var insert = from tabla in doc.Descendants("table") where (string)tabla.Attribute("name_external") == (string)tableName select tabla.Attribute("insert").Value; var delete = from tabla in doc.Descendants("table") where (string)tabla.Attribute("name_external") == (string)tableName select tabla.Attribute("delete").Value; var modify = from tabla in doc.Descendants("table") where (string)tabla.Attribute("name_external") == (string)tableName select tabla.Attribute("modify").Value; if (insert.Count() >0 && insert.First().ToString() == "true" ) { this.btnInserta.IsEnabled = true; } else { this.btnInserta.IsEnabled = false; } if(delete.Count()> 0 && delete.First().ToString()== "true") { this.btnElimina.IsEnabled = true; } else { this.btnElimina.IsEnabled = false; } if(modify.Count()>0 && modify.First().ToString() == "true") { this.btnModifica.IsEnabled = true; } else { this.btnModifica.IsEnabled = false; } this.btnLimpia.IsEnabled = true; this.btnObtener.IsEnabled = true; } } //Método para generar los controles dínamicos a partir de una list de elementos del XML private void subGeneraControles(List<LiteEdicionSWDefinition> lista) { stkDatos.Children.Clear(); LiteEdicionSWDefinition Objetos = new LiteEdicionSWDefinition(); Binding binding_numero = new Binding() { Source = Objetos, Path = new PropertyPath("Number"), Mode = BindingMode.TwoWay, NotifyOnValidationError = true, ValidatesOnExceptions = true, UpdateSourceTrigger= UpdateSourceTrigger.Default }; for (int i = 0; i < lista.Count; i++) { //Si es text crear un textbox if (lista[i].Type == "text" && lista[i].Visible == "true") { Label lbl = new Label(); lbl.Width = 200; lbl.Margin = new Thickness(10, 0, 0, 0); lbl.Content = lista[i].External_Name; lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; lbl.VerticalAlignment = System.Windows.VerticalAlignment.Top; stkDatos.Children.Add(lbl); TextBoxEx txt = new TextBoxEx(); txt.Width = 300; txt.Margin = new Thickness(10, 0, 0, 0); txt.Name = lista[i].Internal_Name; txt.external_name = lista[i].External_Name; if (txt.Name == "user_gsa") { txt.Text = Convert.ToString( UserLabel.Content); } txt.mandatory = lista[i].Mandatory; txt.IsEnabled = Convert.ToBoolean(lista[i].Enabled); txt.numero = "false"; if (!string.IsNullOrEmpty(lista[i].Size) == true) { txt.MaxLength = Convert.ToInt16(lista[i].Size); } txt.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; txt.VerticalAlignment = System.Windows.VerticalAlignment.Top; stkDatos.Children.Add(txt); } //Si es number crear textbox if (lista[i].Type == "number" && lista[i].Visible == "true") { Label lbl = new Label(); lbl.Width = 300; lbl.Margin = new Thickness(10, 0, 0, 0); lbl.Content = lista[i].External_Name; lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; stkDatos.Children.Add(lbl); TextBoxEx txt = new TextBoxEx(); txt.Width = 300; txt.Margin = new Thickness(10, 0, 0, 0); txt.Name = lista[i].Internal_Name; txt.external_name = lista[i].External_Name; txt.SetBinding(TextBoxEx.TextProperty, binding_numero); txt.mandatory = lista[i].Mandatory; txt.IsEnabled = Convert.ToBoolean(lista[i].Enabled); txt.numero = "true"; if (!string.IsNullOrEmpty(lista[i].Size) == true) { txt.MaxLength = Convert.ToInt16(lista[i].Size); } txt.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; stkDatos.Children.Add(txt); } //si es multiple crear combobox if (lista[i].Type == "multiple" && lista[i].Visible == "true") { Label lbl = new Label(); lbl.Width = 300; lbl.Margin = new Thickness(10, 0, 0, 0); lbl.Content = lista[i].External_Name; lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; stkDatos.Children.Add(lbl); ComboBoxExt cbo = new ComboBoxExt(); cbo.Width = 300; var array = lista[i].Datalist.Split(','); cbo.ItemsSource = array; cbo.Name = lista[i].Internal_Name; cbo.external_name = lista[i].External_Name; cbo.Margin = new Thickness(10, 0, 0, 0); cbo.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; cbo.mandatory = lista[i].Mandatory; cbo.IsEnabled = Convert.ToBoolean(lista[i].Enabled); cbo.SelectedIndex = 0; stkDatos.Children.Add(cbo); } //si es date agregar un datepicker if (lista[i].Type == "date" && lista[i].Visible == "true") { Label lbl = new Label(); lbl.Width = 300; lbl.Margin = new Thickness(10, 0, 0, 0); lbl.Content = lista[i].External_Name; lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; stkDatos.Children.Add(lbl); DatePickerExt dtp = new DatePickerExt(); dtp.Width = 120; dtp.Margin = new Thickness(10, 0, 0, 0); dtp.Name = lista[i].Internal_Name; dtp.external_name = lista[i].External_Name; dtp.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; dtp.mandatory = lista[i].Mandatory; dtp.IsEnabled = Convert.ToBoolean(lista[i].Enabled); dtp.SelectedDateFormat = DatePickerFormat.Short; dtp.SelectedDate = Convert.ToDateTime( DateTime.Today.ToShortDateString()); stkDatos.Children.Add(dtp); } } } //Método para validar si existen campos mandatory que estan sin llenar private bool ValidaMandatory(string type_accion) { bool band; band = true; if (stkDatos.Children.Count <= 0) { band = false; MessageBox.Show("No existe Información."); } foreach (var child in stkDatos.Children.OfType<TextBoxEx>()) { var txt = child.mandatory; if (type_accion == "ALTA" && child.Name == "id") { } else { if (!string.IsNullOrEmpty(txt) == true) { if (child.mandatory == "true" && string.IsNullOrWhiteSpace(child.Text) == true) { MessageBox.Show("El Campo " + (string)child.external_name + ", es necesario."); band = false; } } } } foreach (var child in stkDatos.Children.OfType<ComboBoxExt>()) { var txt = child.mandatory; if (!string.IsNullOrEmpty(txt) == true) { if (child.mandatory == "true" && string.IsNullOrWhiteSpace((string)child.SelectedValue) == true) { MessageBox.Show("El Campo " + (string)child.external_name + ", es necesario."); band = false; } } } foreach (var child in stkDatos.Children.OfType<DatePickerExt>()) { var txt = child.mandatory; if (!string.IsNullOrEmpty(txt) == true) { if (child.mandatory == "true" && string.IsNullOrWhiteSpace(child.Text) == true) { MessageBox.Show("El Campo " + (string)child.external_name + ", es necesario."); band = false; } } } return band; } //Metódo para validar textbox como numero bool ValidaNumber() { bool band = true; foreach(var child in stkDatos.Children.OfType<TextBoxEx>()) { //Si el textbox debe llevar texto if (child.numero == "true") { //Validar si es número if (IsNumeric(child.Text) == false ) { MessageBox.Show("El campo " + (string)child.external_name + " debe ser númerico."); band = false; } } } return band; } //Función checa si es number public static Boolean IsNumeric(string valor) { Double result; return Double.TryParse(valor, out result); } //Metódo para invocar al WebService void post_webservice(string type_accion) { //WebService ServiceEditarLevantamiento.EditEnviarLevantamientoPortTypeClient proxy = new ServiceEditarLevantamiento.EditEnviarLevantamientoPortTypeClient(); ServiceEditarLevantamiento.EditEnviarLevantamientoRQType peticionType = new ServiceEditarLevantamiento.EditEnviarLevantamientoRQType(); try { ServiceEditarLevantamiento.enviarLevantamientoRequest peticion = new ServiceEditarLevantamiento.enviarLevantamientoRequest(); peticion.EditEnviarLevantamientoRQ = peticionType; //Si hay un error no continuar string strJSON = string.Empty; strJSON = create_string_Json(type_accion); if ( strJSON == string.Empty) { MessageBox.Show("No fue posible generar la información."); return; } else { peticionType.InformacionElementos = strJSON; } Indicador.InProgress = true; Indicador.Visibility = Visibility.Visible; proxy.enviarLevantamientoCompleted += new EventHandler<ServiceEditarLevantamiento.enviarLevantamientoCompletedEventArgs>(levantamiento_completado); proxy.enviarLevantamientoAsync(peticion); } catch (CommunicationException ex) { MessageBox.Show(ex.Message); Indicador.InProgress = false; Indicador.Visibility = Visibility.Collapsed; } } void levantamiento_completado(object sender, ServiceEditarLevantamiento.enviarLevantamientoCompletedEventArgs e) { try { bool exist_box = true; if (e.Result == null) { MessageBox.Show("Error de Conectividad con el Servidor"); } else { string msg = e.Result.EditEnviarLevantamientoRS.GisRespuestaProceso.CodigoRespuesta; string msg2 = e.Result.EditEnviarLevantamientoRS.GisRespuestaProceso.DescripcionError; if (!string.IsNullOrEmpty(msg2)) { if (msg2.Contains("Caja de Empalme") == true) { exist_box = false; } } if (msg == "OK") { MessageBox.Show("Proceso generado con exito."); } else { if (exist_box == true) { MessageBox.Show("No se realizo el proceso."); } else { MessageBox.Show(msg2); } } } Indicador.InProgress = false; Indicador.Visibility = Visibility.Collapsed; } catch (Exception ex) { MessageBox.Show(ex.Message); } } //Armar cadena JSON string create_string_Json( string type_accion ) { string strLatitud = string.Empty; string strLongitud = string.Empty; string strJson = string.Empty; string strAtributo = string.Empty; if (ValidaMandatory(type_accion) == true) { if (ValidaNumber() == true) { List<LiteEdicionSWDefinition> lista = new List<LiteEdicionSWDefinition>(); lista = (from tabla in doc.Descendants("table") where (string)tabla.Attribute("name_external") == (string)cboTablas.SelectedValue select new LiteEdicionSWDefinition { Name = tabla.Attribute("name").Value, Geometry = tabla.Attribute("geometry").Value, Dataset = tabla.Attribute("dataset").Value } ).ToList(); if (lista.Count <= 0) { MessageBox.Show("No es posible encontrar el nombre interno de la tabla."); return ""; } string table = string.Empty; string geometry = string.Empty; string dataset = string.Empty; table = lista[0].Name; geometry = lista[0].Geometry; dataset = lista[0].Dataset; //Generar Cadena de texto para guardar en la propiedad de atributo del JSON //Recorrer controles foreach (var child in stkDatos.Children.OfType<ComboBoxExt>()) { if ((string)cboTablas.SelectedValue == "Optical Splitter" && child.Name == "name2") { child.Name = "spec_id"; } strAtributo = strAtributo + child.Name + "$" + child.SelectedValue + "||"; } foreach (var child in stkDatos.Children.OfType<TextBoxEx>()) { //SI el control es id y es alta no agregar al JSON if (child.Name == "id" && type_accion == "ALTA") { strAtributo = strAtributo + ""; } else { strAtributo = strAtributo + Convert.ToString(child.Name) + "$" + child.Text + "||"; } } foreach (var child in stkDatos.Children.OfType<DatePickerExt>()) { string date = Convert.ToDateTime(child.Text).ToShortDateString().ToString(); string day = Convert.ToDateTime(child.Text).Day.ToString(); string month = Convert.ToDateTime(child.Text).Month.ToString(); string year = Convert.ToDateTime(child.Text).Year.ToString(); //strAtributo = strAtributo + Convert.ToString(child.Name) + "$" + date + "||"; strAtributo = strAtributo + Convert.ToString(child.Name) + "$" + day.PadLeft(2, '0') + '/' + month.PadLeft(2, '0') + '/' + year.PadLeft(4, '0') + "||"; } //Remover ultimos caracteres || var strlargo = strAtributo.Length; strAtributo = strAtributo.Remove(strlargo - 2, 2); //Validar que longitud y latitud se asigna, punto o trazo if (!string.IsNullOrEmpty(Convert.ToString(txtLatitudP.Text)) && strgeometry == "punto") { strLatitud = Convert.ToString(txtLatitudP.Text); } else if (!string.IsNullOrEmpty(Convert.ToString(txtLatitudT.Text)) && strgeometry == "linea") { strLatitud = Convert.ToString(txtLatitudT.Text); } else if (!string.IsNullOrEmpty(Convert.ToString(txtLatitudTC.Text)) && strgeometry == "area") { //Crear Lista con Lat int max = 0; //Obtener el tamaño de la cadena foreach (string cant in txtLatitudTC.Text.Split(',')) { max++; } //Crear la matriz string[] lstGeom = new string[max]; int i = 0; //Recorrer la cadena de latitud y obtener sus elementos foreach (string geom in txtLatitudTC.Text.Split(',')) { lstGeom[i] = geom; i++; } strLatitud = Convert.ToString(txtLatitudTC.Text); strLatitud = strLatitud + "," + lstGeom[0].ToString(); } if (!string.IsNullOrEmpty(Convert.ToString(txtLongitudP.Text)) && strgeometry == "punto") { strLongitud = Convert.ToString(txtLongitudP.Text); } else if (!string.IsNullOrEmpty(Convert.ToString(txtLongitudT.Text)) && strgeometry == "linea") { strLongitud = Convert.ToString(txtLongitudT.Text); } else if (!string.IsNullOrEmpty(Convert.ToString(txtLongitudTC.Text)) && strgeometry == "area") { //Crear Lista con Lon int max = 0; //Obtener el tamaño de la cadena foreach (string cant in txtLongitudTC.Text.Split(',')) { max++; } //Crear la matriz string[] lstGeom = new string[max]; int i = 0; //Recorrer la cadena de latitud y obtener sus elementos foreach (string geom in txtLongitudTC.Text.Split(',')) { lstGeom[i] = geom; i++; } strLongitud = Convert.ToString(txtLongitudTC.Text); strLongitud = strLongitud + "," + lstGeom[0].ToString(); } //Obtener la cadena JSON strJson = WriteFromObject(strLatitud, strLongitud, Convert.ToString(strAtributo), table, type_accion, geometry, dataset); }//endif validate number }//endif Mandatory return strJson; } // Crear un Objeto y serializarlo a JSON. public static string WriteFromObject(string strLat, string strLon, string atributte, string name_table, string accion_type, string geometry, string vdataset) { try { //Crear Lista con Lat,Lon int max = 0; //Obtener el tamaño de la cadena foreach (string cant in strLat.Split(',')) { max++; } //Crear la matriz string[,] lstGeom = new string[max, 2]; int i = 0; //Recorrer la cadena de latitud y obtener sus elementos foreach (string geom in strLat.Split(',')) { lstGeom[i,0] = geom; i++; } int j = 0; //Recorrer la cadena de longitud y obtener sus elementos foreach (string geom in strLon.Split(',')) { lstGeom[j,1] = geom; j++; } List<Punto> lista = new List<Punto>(); //Si viene vacio es que es una modificación o eliminación sin trazo if (!string.IsNullOrWhiteSpace(strLat) && !string.IsNullOrWhiteSpace(strLon)) { for (int lat = 0; lat < max; lat++) { //Create Points Punto objPunto = new Punto() { lat = lstGeom[lat, 0], lng = lstGeom[lat, 1] }; lista.Add(objPunto); } } //Create Geometry Geometria objGeometria = new Geometria() { puntos = lista , texto = "", tipo_geometria = geometry }; //Create Geometrys Geometrias objGeometrias = new Geometrias() { geometria = objGeometria }; //Create Atributos Atributos objAtributos = new Atributos() { atributo = atributte }; //Create Registro Registro objRegistro = new Registro() { geometrias = objGeometrias, accion = accion_type, dataset = vdataset, //"design_admin", atributos = objAtributos, nombre_tabla = name_table }; List<Registro> lstRegistro = new List<Registro>(); lstRegistro.Add(objRegistro); //Create Registros Registros objRegistros = new Registros() { registro = lstRegistro }; //Create InfoFieldsis InfoFieldsis objInfoFieldsis = new InfoFieldsis() { registros = objRegistros, id_proyecto = "", total_registros = 1, id_movil = "", definitivo = "1" }; RootObject objRootObject = new RootObject() { info_fieldsis = objInfoFieldsis }; //Create a stream to serialize the object to. MemoryStream ms = new MemoryStream(); // Serializer the User object to the stream. DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject)); ser.WriteObject(ms, objRootObject); byte[] json = ms.ToArray(); ms.Close(); return Encoding.UTF8.GetString(json, 0, json.Length); } catch (Exception e) { MessageBox.Show("Error: '{0}'" + e.Message); return ""; } } //Metódo para limpiar los controles void Limpia() { this.txtLatitudP.Text = string.Empty; this.txtLongitudP.Text = string.Empty; this.txtLatitudT.Text = string.Empty; this.txtLongitudT.Text = string.Empty; this.txtLatitudTC.Text = string.Empty; this.txtLongitudTC.Text = string.Empty; if (stkDatos.Children.Count > 0) { foreach (var child in stkDatos.Children.OfType<TextBoxEx>()) { var txt = child.mandatory; if (!string.IsNullOrEmpty(txt) == true) { child.Text = String.Empty; } if (child.Name == "user_gsa") { child.Text = Convert.ToString(UserLabel.Content); } } foreach (var child in stkDatos.Children.OfType<DatePickerExt>()) { child.Text = String.Empty; } foreach (var child in stkDatos.Children.OfType<ComboBoxExt>()) { if (child.Name == "status") { child.SelectedIndex = 0; } if (child.Name == "visible?") { child.IsEnabled = false; child.SelectedIndex = 0; } } } } //Metódo para validar si el status es Nuevo bool validaStatusNuevo() { bool band = true; if (stkDatos.Children.Count > 0) { foreach (var child in stkDatos.Children.OfType<ComboBoxExt>()) { if (child.Name == "status") { if (child.SelectedValue.ToString() == "NUEVO") { band = true; } else { band = false; } } } } return band; } #endregion }//end class }//end namespace
using eCommerceSE.Cliente; using eCommerceSE.Model; using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI; namespace Enviosbase.Establecimiento { public partial class EstablecimientoList : System.Web.UI.Page { string llave = ConfigurationManager.AppSettings["Usuario"].ToString(); protected void Page_Load(object sender, EventArgs e) { if (Session["IdUsuario"] == null) { Response.Redirect("/Login.aspx"); } if (!Page.IsPostBack) { List<EstablecimientoModel> lista = new EstablecimientoCliente(llave).GetAll(); string content = ""; foreach (EstablecimientoModel item in lista) { content += "<tr>" + "<td>" + item.Id + "</td>" + "<td>" + item.Nombre + "</td>" + "<td>" + item.Documento + "</td>" + "<td>" + new CategoriaEstablecimientoCliente(llave).GetById(item.IdCategoria.Value).Nombre + "</td>" + "<td><div class='image-input image-input-empty image-input-outline' id='kt_image_5' >" + "<div class='image-input-wrapper' id='kt_image_load' style=\"background-image: url('" + item.Imagen + "')\"></div></div></td>" + "<td>" + new PaisCliente(llave).GetById(item.IdPais).Nombre + "</td>" + "<td>" + new DepartamentoCliente(llave).GetById(item.IdDepto).Nombre + "</td>" + "<td>" + new MunicipioCliente(llave).GetById(item.IdMunicipio).Nombre + "</td>" + "<td>" + item.Direccion + "</td>" + //"<td>" + item.GeoLat + "</td>" + "<td>" + new ResponsableCliente(llave).GetById(item.IdResponsable).Nombre + "</td>" + "<td>" + item.Telefono + "</td>" + "<td>" + item.Celular + "</td>" + "<td>" + item.Correo + "</td>" + "<td>" + item.HoraInicioLunes + " a " + item.HoraFinLunes + "</td>" + "<td>" + item.HoraInicioMartes + " a " + item.HoraFinMartes + "</td>" + "<td>" + item.HoraInicioMiercoles + " a " + item.HoraFinMiercoles + "</td>" + "<td>" + item.HoraInicioJueves + " a " + item.HoraFinJueves + "</td>" + "<td>" + item.HoraInicioViernes + " a " + item.HoraFinViernes + "</td>" + "<td>" + item.HoraInicioSabado + " a " + item.HoraFinSabado + "</td>" + "<td>" + item.HoraInicioDomingo + " a " + item.HoraFinDomingo + "</td>" + "<td>" + item.FechaRegistro + "</td>" + "<td>" + Estado(Convert.ToBoolean(item.Estado)) + "</td>" + "<td><span class=\"col-md-12\"><a href=\"EstablecimientoEdit.aspx?View=0&Id=" + item.Id + "\"><i class=\"fa fa-eye\"></i> Ver </a></span>" + "<span class=\"col-md-12\"><a href=\"EstablecimientoEdit.aspx?View=1&Id=" + item.Id + "\"><i class=\"fa fa-edit\"></i> Editar </a></span>" + "<span class=\"col-md-12\"><a href=\"EstablecimientoEdit.aspx?Estado=1&Id=" + item.Id + "\"><i class=\"fa fa-trash\"></i> Cambiar estado </a></span>" + "</td></tr>"; } ltTableItems.Text = content; } } protected void btnNew_Click(object sender, EventArgs e) { Response.Redirect("EstablecimientoEdit.aspx"); } public string Estado(bool state) { if (state) return "Activo"; else return "Inactivo"; } } }
using System; namespace TestApplication { internal class Artwork { public void run() { //this method is going to create an artwork } public void test () { // this is going to be my work string name = "Diana"; Console.WriteLine(name); } public void featureBranchMethod() { Console.WriteLine("Feature method"); } public void bored() { Console.WriteLine("whatever"); } } }
using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; using EPiServer.Web; using System.ComponentModel.DataAnnotations; namespace EpiserverSiteFromScratch.Models.Pages { [ContentType(DisplayName = "StartPage", GUID = "7c20e845-7fde-4c82-ad9b-43d1369a8a9d", Description = "StartPage")] public class StartPage : SitePageData { [CultureSpecific] [Display( Name = "Main content", Description = "The ", GroupName = SystemTabNames.Content, Order = 20)] public virtual ContentArea Maincontentarea { get; set; } [CultureSpecific] [Display( Name = "Header", Description = "Header", GroupName = SystemTabNames.Content, Order = 10)] public virtual string Heading{ get; set; } [Display( Name = "logo sidhuvud", Description = "logo", GroupName = SystemTabNames.Content, Order = 30)] [UIHint(UIHint.Image)] public virtual ContentReference logo { 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; namespace z88dk_compile_options_helper_beta { public partial class target : Form { public target() { InitializeComponent(); this.StartPosition = FormStartPosition.Manual; this.Location = new Point(0, 0); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +zx "; zccvariables.machine = "zx"; button1.Enabled = true; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ts2068 "; zccvariables.machine = "ts2068"; button1.Enabled = true; } private void radioButton49_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +zx81 "; zccvariables.machine = "zx81"; button1.Enabled = true; } private void radioButton42_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +zx80 "; zccvariables.machine = "zx80"; button1.Enabled = true; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +abc80 "; zccvariables.machine = "abc80"; button1.Enabled = true; } private void radioButton4_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +abc800 "; zccvariables.machine = "abc800"; button1.Enabled = true; } private void radioButton5_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ace "; zccvariables.machine = "ace"; button1.Enabled = true; } private void radioButton6_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +aquarius "; zccvariables.machine = "aquarius"; button1.Enabled = true; } private void radioButton7_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +c128 "; zccvariables.machine = "c128"; button1.Enabled = true; } private void radioButton8_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +c7420 "; zccvariables.machine = "c7420"; button1.Enabled = true; } private void radioButton9_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +cpc "; zccvariables.machine = "cpc"; button1.Enabled = true; } private void radioButton10_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +cpm "; zccvariables.machine = "cpm"; button1.Enabled = true; } private void radioButton11_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +embedded "; zccvariables.machine = "embedded"; button1.Enabled = true; } private void radioButton12_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +enterprise "; zccvariables.machine = "enterprise"; button1.Enabled = true; } private void radioButton13_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +gal "; zccvariables.machine = "gal"; button1.Enabled = true; } private void radioButton14_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +lambda "; zccvariables.machine = "lambda"; button1.Enabled = true; } private void radioButton15_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +lynx "; zccvariables.machine = "lynx"; button1.Enabled = true; } private void radioButton16_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +m5 "; zccvariables.machine = "m5"; button1.Enabled = true; } private void radioButton17_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +mc1000 "; zccvariables.machine = "mc1000"; button1.Enabled = true; } private void radioButton18_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +msx "; zccvariables.machine = "msx"; button1.Enabled = true; } private void radioButton19_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +mtx "; zccvariables.machine = "mtx"; button1.Enabled = true; } private void radioButton20_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +nascom "; zccvariables.machine = "nascom"; button1.Enabled = true; } private void radioButton21_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +nc "; zccvariables.machine = "nc"; button1.Enabled = true; } private void radioButton22_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +newbrain "; zccvariables.machine = "newbrain"; button1.Enabled = true; } private void radioButton23_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +osca "; zccvariables.machine = "osca"; button1.Enabled = true; } private void radioButton24_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +oz "; zccvariables.machine = "oz"; button1.Enabled = true; } private void radioButton25_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +p2000 "; zccvariables.machine = "p2000"; button1.Enabled = true; } private void radioButton26_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +pc6001 "; zccvariables.machine = "pc6001"; button1.Enabled = true; } private void radioButton27_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +pps "; zccvariables.machine = "pps"; button1.Enabled = true; } private void radioButton28_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +rcmx000 "; zccvariables.machine = "rcmx000"; button1.Enabled = true; } private void radioButton29_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +rex "; zccvariables.machine = "rex"; button1.Enabled = true; } private void radioButton30_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +sam "; zccvariables.machine = "sam"; button1.Enabled = true; } private void radioButton31_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +sc3000 "; zccvariables.machine = "sc3000"; button1.Enabled = true; } private void radioButton32_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +sms "; zccvariables.machine = "sms"; button1.Enabled = true; } private void radioButton33_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +sos "; zccvariables.machine = "sos"; button1.Enabled = true; } private void radioButton34_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +srr "; zccvariables.machine = "srr"; button1.Enabled = true; } private void radioButton35_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +svi "; zccvariables.machine = "svi"; button1.Enabled = true; } private void radioButton36_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ti8x "; zccvariables.machine = "ti8x"; button1.Enabled = true; } private void radioButton37_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ti82 "; zccvariables.machine = "ti82"; button1.Enabled = true; } private void radioButton38_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ti83 "; zccvariables.machine = "ti83"; button1.Enabled = true; } private void radioButton39_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ti85 "; zccvariables.machine = "ti85"; button1.Enabled = true; } private void radioButton40_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +ti86 "; zccvariables.machine = "ti86"; button1.Enabled = true; } private void radioButton41_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +trs80 "; zccvariables.machine = "trs80"; button1.Enabled = true; } private void radioButton43_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +vg5k "; zccvariables.machine = "vg5k"; button1.Enabled = true; } private void radioButton44_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +vz "; zccvariables.machine = "vz"; button1.Enabled = true; } private void radioButton45_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +x1 "; zccvariables.machine = "x1"; button1.Enabled = true; } private void radioButton46_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +x07 "; zccvariables.machine = "x07"; button1.Enabled = true; } private void radioButton47_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +z88 "; zccvariables.machine = "z88"; button1.Enabled = true; } private void radioButton48_CheckedChanged(object sender, EventArgs e) { textBox1.Text = "zcc +zcc "; zccvariables.machine = "zcc"; button1.Enabled = true; } //next screen private void button1_Click(object sender, EventArgs e) { //this.Hide(); //quick start if (zccvariables.mainMenuChoice == 1) { quick_start frm = new quick_start(textBox1.Text); frm.Show(); this.Close(); } //wizard if (zccvariables.mainMenuChoice == 2) { compiler_choice frm = new compiler_choice(textBox1.Text); frm.Show(); this.Close(); } //list wizard if (zccvariables.mainMenuChoice == 3) { //Form1 frm = (Form1)Application.OpenForms["Form1"]; //List_wizard(textBox1.Text); //List_wizard frm = (List_wizard)Application.OpenForms["List_wizard"]; //frm.Show(); //List_wizard //zccvariables.choosenTarget = true; List_wizard frm = new List_wizard(textBox1.Text); frm.Show(); this.Close(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RedBlackTreeProject { class RBTree { private RBTreeNode root = null; private RBTreeNode newNode; private RBTreeNode deleteChild; private int level; private static int defaultPrintNodeLength = 4; private RBTreeStepsForm stepsForm; public RBTree(RBTreeStepsForm stepsForm) { this.stepsForm = stepsForm; } internal RBTreeNode Root { get { return root; } } public int Level { get { return level; } } public static int DefaultLength { get { return defaultPrintNodeLength; } } public static void ResetDefaultLength() { defaultPrintNodeLength = 4; } public void Reset() { root = null; newNode = null; level = 0; } public void AddElement(int value) { if (value.ToString().Length + 2 > RBTree.defaultPrintNodeLength) { int newLength = value.ToString().Length + 2; if (newLength % 2 == 1) { newLength += 1; } RBTree.defaultPrintNodeLength = newLength; } newNode = new RBTreeNode(value, true); stepsForm.AddStep("Dodaje se novi čvor N crvene boje: " + newNode + "."); if (root == null) { root = newNode; stepsForm.AddSubStep(string.Format("Novi čvor N {0} je korijen stabla, boja mu se mijenja u crnu.", newNode)); root.isRed = false; } else { InsertIntoTree(value); RBTreeNode parent = newNode.parentNode; if (!parent.isRed) { stepsForm.AddSubStep("Roditelj P " + parent + " je crne boje. Nema potrebe za rekonstrukcijom."); } while (newNode.parentNode != null && newNode.parentNode.isRed) { stepsForm.AddSubStep(string.Format("Roditelj P {0} je crvene boje.", newNode.parentNode)); RBTreeNode grandparent = newNode.parentNode.parentNode; RBTreeNode uncle; // p(N) == g(N).left if (newNode.parentNode == newNode.parentNode.parentNode.leftNode) { uncle = newNode.parentNode.parentNode.rightNode; stepsForm.AddSubStep(string.Format("P {0} je lijevo dijete od djeda G {1}. "+ "Ujak U {2} je desno dijete od G {1}.", newNode.parentNode, newNode.parentNode.parentNode, uncle)); if (uncle != null && uncle.isRed) { stepsForm.AddSubStep(string.Format("U {0} je crven. P {1} postaje crn, "+ "U {0} postaje crn, G {2} postaje crven.", uncle, newNode.parentNode, newNode.parentNode.parentNode)); newNode.parentNode.isRed = false; uncle.isRed = false; newNode.parentNode.parentNode.isRed = true; newNode = newNode.parentNode.parentNode; } else { parent = newNode.parentNode; grandparent = parent.parentNode; stepsForm.AddSubStep(string.Format("U {0} je crn.", uncle)); if (newNode == parent.rightNode) { stepsForm.AddSubStep(string.Format("Novi čvor N {0} je desno dijete od P {1}. "+ "Obavlja se lijeva rotacija N {0} oko P {1}.", newNode, parent)); grandparent.leftNode = newNode; FixParent(grandparent.leftNode, grandparent); parent.rightNode = newNode.leftNode; FixParent(parent.rightNode, parent); newNode.leftNode = parent; FixParent(newNode.leftNode, newNode); stepsForm.AddSubStep(string.Format("N {0} postaje P {1}.", newNode, parent)); newNode = parent; } RBTreeNode tempParent = newNode.parentNode; RBTreeNode tempGrandparent = tempParent.parentNode; RBTreeNode tempGrandGrandparent = tempGrandparent.parentNode; stepsForm.AddSubStep(string.Format("Obavlja se desna rotacija roditelja od N p(N) {0} oko djeda od N g(N) {1}.", tempParent, tempGrandparent)); Rotation(newNode.parentNode, newNode.parentNode.parentNode, true); stepsForm.AddSubStep(string.Format("P {0} postaje crn, G {1} postaje crven.", newNode.parentNode, newNode.parentNode.parentNode)); if (newNode.parentNode != null) { newNode.parentNode.isRed = false; } newNode.parentNode.parentNode.isRed = true; } } else { uncle = newNode.parentNode.parentNode.leftNode; stepsForm.AddSubStep(string.Format("P {0} je desno dijete od djeda G {1}. Ujak U {2} je lijevo dijete od G {1}.", parent, grandparent, uncle)); if (uncle != null && uncle.isRed) { stepsForm.AddSubStep(string.Format("U {0} je crven. P {1} postaje crn, U {0} postaje crn, G {2} postaje crven.", uncle, newNode.parentNode, newNode.parentNode.parentNode)); newNode.parentNode.isRed = false; uncle.isRed = false; newNode.parentNode.parentNode.isRed = true; newNode = newNode.parentNode.parentNode; } else { parent = newNode.parentNode; grandparent = parent.parentNode; stepsForm.AddSubStep(string.Format("U {0} je crn.", uncle)); if (newNode == parent.leftNode) { stepsForm.AddSubStep(string.Format("Novi čvor N {0} je lijevo dijete od P {1}. Obavlja se desna rotacija N {0} oko P {1}.", newNode, parent)); grandparent.rightNode = newNode; FixParent(grandparent.rightNode, grandparent); parent.leftNode = newNode.rightNode; FixParent(parent.leftNode, parent); newNode.rightNode = parent; FixParent(newNode.rightNode, newNode); stepsForm.AddSubStep(string.Format("N {0} postaje P {1}.", newNode, parent)); newNode = parent; } RBTreeNode tempParent = newNode.parentNode; RBTreeNode tempGrandparent = tempParent.parentNode; RBTreeNode tempGrandGrandparent = tempGrandparent.parentNode; stepsForm.AddSubStep(string.Format("Obavlja se lijeva rotacija roditelja od N p(N) {0} oko djeda od N g(N) {1}.", tempParent, tempGrandparent)); Rotation(newNode.parentNode, newNode.parentNode.parentNode, false); stepsForm.AddSubStep(string.Format("P {0} postaje crn, G {1} postaje crven.", newNode.parentNode, newNode.parentNode.parentNode)); if (newNode.parentNode != null) { newNode.parentNode.isRed = false; } grandparent.isRed = true; } } } RBTreeNode node = parent; while (node.parentNode != null) { node = node.parentNode; } if (node.isRed) { stepsForm.AddSubStep(string.Format("Korijen {0} postaje crn.", root)); node.isRed = false; } } } private void InsertIntoTree(int value) { int currentLevel = 0; RBTreeNode node = root; while (node != null) { currentLevel++; if (value < node.value) { if (node.leftNode == null) { if (currentLevel > level) { level = currentLevel; } node.leftNode = newNode; FixParent(node.leftNode, node); break; } else { node = node.leftNode; } } else { if (node.rightNode == null) { if (currentLevel > level) { level = currentLevel; } node.rightNode = newNode; FixParent(node.rightNode, node); break; } else { node = node.rightNode; } } } } private void Rotation(RBTreeNode rotated, RBTreeNode centered, Boolean leftSide) { RBTreeNode parentCentered = centered.parentNode; // p(N) == root if (parentCentered == null) { if (leftSide) { // g(N).left = p(N).right centered.leftNode = rotated.rightNode; FixParent(centered.leftNode, centered); // p(N).right = g(N) rotated.rightNode = centered; FixParent(rotated.rightNode, rotated); } else { // g(N).right = p(N).left centered.rightNode = rotated.leftNode; FixParent(centered.rightNode, centered); // p(N).left = g(N) rotated.leftNode = centered; FixParent(rotated.leftNode, rotated); } root = rotated; rotated.parentNode = parentCentered; } else if (leftSide) { if (parentCentered.leftNode == centered) { // p(g(N)).left = p(N) parentCentered.leftNode = rotated; FixParent(parentCentered.leftNode, parentCentered); // g(N).left = p(N).right centered.leftNode = rotated.rightNode; FixParent(centered.leftNode, centered); // p(N).right = g(N) rotated.rightNode = centered; FixParent(rotated.rightNode, rotated); } else { // p(g(N)).right = p(N) parentCentered.rightNode = rotated; FixParent(parentCentered.rightNode, parentCentered); // g(N).left = p(N).right centered.leftNode = rotated.rightNode; FixParent(centered.leftNode, centered); // p(N).right = g(N) rotated.rightNode = centered; FixParent(rotated.rightNode, rotated); } } else { if (parentCentered.rightNode == centered) { // p(g(N)).right = p(N) parentCentered.rightNode = rotated; FixParent(parentCentered.rightNode, parentCentered); // g(N).right = p(N).left centered.rightNode = rotated.leftNode; FixParent(centered.rightNode, centered); // p(N).left = g(N) rotated.leftNode = centered; FixParent(rotated.leftNode, rotated); } else { // p(g(N)).left = p(N) parentCentered.leftNode = rotated; FixParent(parentCentered.leftNode, parentCentered); // g(N).right = p(N).left centered.rightNode = rotated.leftNode; FixParent(centered.rightNode, centered); // p(N).left = g(N) rotated.leftNode = centered; FixParent(rotated.leftNode, rotated); } } } private void FixParent(RBTreeNode childNode, RBTreeNode parentNode) { if (childNode != null) { childNode.parentNode = parentNode; } } private Boolean RemoveFromTree(int value) { RBTreeNode deleteNode = FindValue(value); if (deleteNode == null) return false; if (deleteNode == root && deleteNode.leftNode == null && deleteNode.rightNode == null) { root = null; return false; } deleteChild = null; if (deleteNode == null) return true; RBTreeNode replaceNode = FindReplace(deleteNode); Boolean replaceColor = replaceNode.isRed; if (replaceNode == deleteNode) { // delnode != root if (deleteNode.parentNode != null) { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; deleteChild.parentNode = deleteNode.parentNode; if (deleteNode.parentNode.leftNode == deleteNode) { deleteNode.parentNode.leftNode = deleteChild; } else { deleteNode.parentNode.rightNode = deleteChild; } } deleteNode = null; return replaceColor; } if (replaceNode.value <= deleteNode.value) { if (deleteNode.leftNode == replaceNode) { deleteNode.leftNode = replaceNode.leftNode; if (deleteNode.leftNode != null) { deleteNode.leftNode.parentNode = deleteNode; deleteChild = deleteNode.leftNode; } else { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; deleteNode.leftNode = deleteChild; } deleteChild.parentNode = deleteNode; deleteNode.value = replaceNode.value; replaceNode = null; } else { RBTreeNode parentOfReplace = replaceNode.parentNode; parentOfReplace.rightNode = replaceNode.leftNode; if (parentOfReplace.rightNode == null) { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; parentOfReplace.rightNode = deleteChild; deleteChild.parentNode = parentOfReplace; } else { if (parentOfReplace.rightNode.leftNode != null) { parentOfReplace.rightNode.leftNode.parentNode = parentOfReplace; deleteChild = parentOfReplace.rightNode.leftNode; } else { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; parentOfReplace.rightNode.leftNode = deleteChild; deleteChild.parentNode = parentOfReplace; } } deleteNode.value = replaceNode.value; replaceNode = null; } } else { if (deleteNode.rightNode == replaceNode) { deleteNode.rightNode = replaceNode.rightNode; if (deleteNode.rightNode != null) { deleteChild = deleteNode.rightNode; } else { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; deleteNode.rightNode = deleteChild; } deleteChild.parentNode = deleteNode; deleteNode.value = replaceNode.value; replaceNode = null; } else { RBTreeNode parentOfReplace = replaceNode.parentNode; parentOfReplace.leftNode = replaceNode.rightNode; if (parentOfReplace.leftNode == null) { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; parentOfReplace.leftNode = deleteChild; deleteChild.parentNode = parentOfReplace; } else { if (parentOfReplace.leftNode.rightNode != null) { parentOfReplace.leftNode.rightNode.parentNode = parentOfReplace; deleteChild = parentOfReplace.leftNode.rightNode; } else { deleteChild = new RBTreeNode(-1, false); deleteChild.isNullLeaf = true; parentOfReplace.leftNode.rightNode = deleteChild; deleteChild.parentNode = parentOfReplace; } } deleteNode.value = replaceNode.value; replaceNode = null; } } return replaceColor; } private RBTreeNode FindReplace(RBTreeNode deleteNode) { RBTreeNode replaceNode = deleteNode; if (deleteNode.leftNode != null) { RBTreeNode node = deleteNode.leftNode; while (node.rightNode != null) { node = node.rightNode; } replaceNode = node; } else if (deleteNode.rightNode != null) { RBTreeNode node = deleteNode.rightNode; while (node.leftNode != null) { node = node.leftNode; } replaceNode = node; } return replaceNode; } private RBTreeNode FindValue(int value) { RBTreeNode node = root; while (node != null) { if (value == node.value) { break; } if (value < node.value) { node = node.leftNode; } else { node = node.rightNode; } } return node; } public void RemoveElement(int value) { stepsForm.AddStep("Briše se čvor s vrijednošću " + value + "."); Boolean replaceColorIsRed = RemoveFromTree(value); if (deleteChild == null) return; if (root == null) return; if (deleteChild == null || replaceColorIsRed == true) { if (deleteChild != null && deleteChild.isNullLeaf) { if (deleteChild.parentNode.leftNode == deleteChild) { deleteChild.parentNode.leftNode = null; } else { deleteChild.parentNode.rightNode = null; } deleteChild = null; } return; } while (deleteChild != root && !deleteChild.isRed) { stepsForm.AddSubStep(string.Format("Dijete N {0} je crne boje.",deleteChild)); if (deleteChild == deleteChild.parentNode.leftNode) { stepsForm.AddSubStep(string.Format("N {0} je lijevo dijete roditelja P {1}.", deleteChild, deleteChild.parentNode)); RBTreeNode sibling = deleteChild.parentNode.rightNode; if (sibling.isRed) { stepsForm.AddSubStep(string.Format("S {0}, drugo dijete od P {1} je crvene boje, boji se u crnu.", sibling, deleteChild.parentNode)); sibling.isRed = false; stepsForm.AddSubStep(string.Format("Roditelj od N P {0} se boji u crvenu.", deleteChild.parentNode)); deleteChild.parentNode.isRed = true; stepsForm.AddSubStep(string.Format("Obavlja se lijeva rotacija S {0} oko P {1}.", sibling, deleteChild.parentNode)); deleteChild.parentNode.rightNode = sibling.leftNode; sibling.leftNode.parentNode = deleteChild.parentNode; sibling.leftNode = deleteChild.parentNode; if (deleteChild.parentNode == root) { root = sibling; sibling.parentNode = null; } else { if (deleteChild.parentNode == deleteChild.parentNode.parentNode.leftNode) { deleteChild.parentNode.parentNode.leftNode = sibling; } else { deleteChild.parentNode.parentNode.rightNode = sibling; } sibling.parentNode = deleteChild.parentNode.parentNode; } deleteChild.parentNode.parentNode = sibling; } sibling = deleteChild.parentNode.rightNode; if ((sibling.leftNode == null || !sibling.leftNode.isRed) && (sibling.rightNode == null || !sibling.rightNode.isRed)) { stepsForm.AddSubStep(string.Format("Djeca od S {0} su crna. S {0} se boji u crvenu.", sibling)); sibling.isRed = true; if (deleteChild.isNullLeaf) { if (deleteChild.parentNode.leftNode == deleteChild) { deleteChild.parentNode.leftNode = null; } else { deleteChild.parentNode.rightNode = null; } } stepsForm.AddSubStep(string.Format("Roditelj od N P {0} postaje novi N.", deleteChild.parentNode)); deleteChild = deleteChild.parentNode; } else { if (sibling.rightNode == null || !sibling.rightNode.isRed) { stepsForm.AddSubStep(string.Format("Desno dijete od S SR {0} je crne boje. Lijevo dijete od S SL {1} se boji u crnu.", sibling.rightNode, sibling.leftNode)); sibling.leftNode.isRed = false; stepsForm.AddSubStep(string.Format("S {0} se boji u crvenu.", sibling)); sibling.isRed = true; stepsForm.AddSubStep(string.Format("Obavlja se desna rotacija SL {0} oko S {1}.", sibling.leftNode, sibling)); deleteChild.parentNode.rightNode = sibling.leftNode; sibling.leftNode.parentNode = deleteChild.parentNode; sibling.leftNode = sibling.leftNode.rightNode; FixParent(sibling.leftNode, sibling); deleteChild.parentNode.rightNode.rightNode = sibling; sibling.parentNode = deleteChild.parentNode.rightNode; } sibling = deleteChild.parentNode.rightNode; stepsForm.AddSubStep(string.Format("S {0} se boji u boju od roditelja P {1}.", sibling, deleteChild.parentNode)); sibling.isRed = deleteChild.parentNode.isRed; stepsForm.AddSubStep(string.Format("P {0} se boji u crnu.", deleteChild.parentNode)); deleteChild.parentNode.isRed = false; stepsForm.AddSubStep(string.Format("Desno dijete od S SR {0} se boji u crnu.", sibling.rightNode)); if (sibling.rightNode != null) { sibling.rightNode.isRed = false; } stepsForm.AddSubStep(string.Format("Obavlja se lijeva rotacija S {0} oko P {1}.", sibling, deleteChild.parentNode)); deleteChild.parentNode.rightNode = sibling.leftNode; FixParent(deleteChild.parentNode.rightNode, deleteChild.parentNode); if (deleteChild.parentNode == root) { root = sibling; sibling.parentNode = null; } else { if (deleteChild.parentNode == deleteChild.parentNode.parentNode.leftNode) { deleteChild.parentNode.parentNode.leftNode = sibling; } else { deleteChild.parentNode.parentNode.rightNode = sibling; } sibling.parentNode = deleteChild.parentNode.parentNode; } sibling.leftNode = deleteChild.parentNode; deleteChild.parentNode.parentNode = sibling; stepsForm.AddSubStep(string.Format("Korijen {0} postaje novi N.", root)); if (deleteChild.isNullLeaf) { if (deleteChild.parentNode.leftNode == deleteChild) { deleteChild.parentNode.leftNode = null; } else { deleteChild.parentNode.rightNode = null; } } deleteChild = root; } } else { stepsForm.AddSubStep(string.Format("N {0} je desno dijete roditelja P {1}.", deleteChild, deleteChild.parentNode)); RBTreeNode sibling = deleteChild.parentNode.leftNode; if (sibling.isRed) { stepsForm.AddSubStep(string.Format("S {0}, drugo dijete od P {1} je crvene boje, boji se u crnu.", sibling, deleteChild.parentNode)); sibling.isRed = false; stepsForm.AddSubStep(string.Format("Roditelj od N P {0} se boji u crvenu.", deleteChild.parentNode)); deleteChild.parentNode.isRed = true; stepsForm.AddSubStep(string.Format("Obavlja se desna rotacija S {0} oko P {1}.", sibling, deleteChild.parentNode)); deleteChild.parentNode.leftNode = sibling.rightNode; sibling.rightNode.parentNode = deleteChild.parentNode; sibling.rightNode = deleteChild.parentNode; if (deleteChild.parentNode == root) { root = sibling; sibling.parentNode = null; } else { if (deleteChild.parentNode == deleteChild.parentNode.parentNode.rightNode) { deleteChild.parentNode.parentNode.rightNode = sibling; } else { deleteChild.parentNode.parentNode.leftNode = sibling; } sibling.parentNode = deleteChild.parentNode.parentNode; } deleteChild.parentNode.parentNode = sibling; } sibling = deleteChild.parentNode.leftNode; if ((sibling.leftNode == null || !sibling.leftNode.isRed) && (sibling.rightNode == null || !sibling.rightNode.isRed)) { stepsForm.AddSubStep(string.Format("Djeca od S {0} su crna. S {0} se boji u crvenu.", sibling)); sibling.isRed = true; if (deleteChild.isNullLeaf) { if (deleteChild.parentNode.leftNode == deleteChild) { deleteChild.parentNode.leftNode = null; } else { deleteChild.parentNode.rightNode = null; } } stepsForm.AddSubStep(string.Format("Roditelj od N P {0} postaje novi N.", deleteChild.parentNode)); deleteChild = deleteChild.parentNode; } else { if (sibling.leftNode == null || !sibling.leftNode.isRed) { stepsForm.AddSubStep(string.Format("Lijevo dijete od S SL {0} je crne boje. Desno dijete od S SR {1} se boji u crnu.", sibling.leftNode, sibling.rightNode)); sibling.rightNode.isRed = false; stepsForm.AddSubStep(string.Format("S {0} se boji u crvenu.", sibling)); sibling.isRed = true; stepsForm.AddSubStep(string.Format("Obavlja se lijeva rotacija SR {0} oko S {1}.", sibling.rightNode, sibling)); deleteChild.parentNode.leftNode = sibling.rightNode; FixParent(deleteChild.parentNode.leftNode, deleteChild.parentNode); sibling.rightNode = sibling.rightNode.leftNode; FixParent(sibling.rightNode, sibling); deleteChild.parentNode.leftNode.leftNode = sibling; sibling.parentNode = deleteChild.parentNode.leftNode; } sibling = deleteChild.parentNode.leftNode; stepsForm.AddSubStep(string.Format("S {0} se boji u boju od roditelja P {1}.", sibling, deleteChild.parentNode)); sibling.isRed = deleteChild.parentNode.isRed; stepsForm.AddSubStep(string.Format("P {0} se boji u crnu.", deleteChild.parentNode)); deleteChild.parentNode.isRed = false; stepsForm.AddSubStep(string.Format("Lijevo dijete od S SL {0} se boji u crnu.", sibling.leftNode)); if (sibling.leftNode != null) { sibling.leftNode.isRed = false; } stepsForm.AddSubStep(string.Format("Obavlja se desna rotacija S {0} oko P {1}.", sibling, deleteChild.parentNode)); deleteChild.parentNode.leftNode = sibling.rightNode; FixParent(deleteChild.parentNode.leftNode, deleteChild.parentNode); if (deleteChild.parentNode == root) { root = sibling; sibling.parentNode = null; } else { if (deleteChild.parentNode == deleteChild.parentNode.parentNode.rightNode) { deleteChild.parentNode.parentNode.rightNode = sibling; } else { deleteChild.parentNode.parentNode.leftNode = sibling; } sibling.parentNode = deleteChild.parentNode.parentNode; } sibling.rightNode = deleteChild.parentNode; deleteChild.parentNode.parentNode = sibling; stepsForm.AddSubStep(string.Format("Korijen {0} postaje novi N.", root)); if (deleteChild.isNullLeaf) { if (deleteChild.parentNode.rightNode == deleteChild) { deleteChild.parentNode.rightNode = null; } else { deleteChild.parentNode.leftNode = null; } } deleteChild = root; } } } stepsForm.AddSubStep(string.Format("N {0} se boji u crnu.", deleteChild)); deleteChild.isRed = false; } private int calculatePadding(int treeLevel) { // rezultat rekurzivne relacije: return (RBTree.DefaultLength / 2) * (int) Math.Pow(2, treeLevel+1) - (RBTree.DefaultLength / 2); } public override string ToString() { List<RBTreeNode> previousNodes = new List<RBTreeNode>() { root }; List<RBTreeNode> currentNodes = new List<RBTreeNode>(); int currentLevel = level; int defaultLength = RBTree.DefaultLength; int previousPadding; int padding = previousPadding = calculatePadding(currentLevel); string treeRows = ""; string treeRow = string.Format("{0, " + (padding + defaultLength) + "}", root); treeRows += treeRow + "\n"; while (currentLevel-- > 0) { treeRow = ""; string connectionRow = ""; padding = calculatePadding(currentLevel); Boolean first = true; currentNodes.Clear(); currentNodes.AddRange(previousNodes); previousNodes.Clear(); int wireLength; foreach (RBTreeNode node in currentNodes) { if (node == null) { treeRow += string.Format("{0, " + (padding + defaultLength) + "}", ""); connectionRow += string.Format("{0, " + (padding + defaultLength) + "}", ""); previousNodes.Add(null); if (first) { first = false; padding *= 2; previousPadding *= 2; } //connectionRow += string.Format("{0, " + (padding + defaultLength) + "}", ""); treeRow += string.Format("{0, " + (padding + defaultLength) + "}", ""); connectionRow += string.Format("{0, " + (padding + defaultLength) + "}", ""); previousNodes.Add(null); } else { int nodeLength = node.ToString().Length; int leftNodeLength = 0; wireLength = 0; if (node.leftNode != null) { leftNodeLength = node.leftNode.ToString().Length; } treeRow += string.Format("{0, " + (padding + defaultLength) + "}", node.leftNode); connectionRow += string.Format("{0, " + (padding + defaultLength) + "}", ""); string connection = ""; if (node.leftNode != null) connection = " "; //connectionRow += string.Format("{0, " + (padding + defaultLength - leftNodeLength / 2) + "}", connection); //connectionRow += string.Format("{0, " + (leftNodeLength / 2) + "}", ""); //connectionRow += string.Format("{0, " + (padding + defaultLength) + "}", connection); previousNodes.Add(node.leftNode); if (first) { first = false; padding *= 2; previousPadding *= 2; } wireLength = padding / 2 - 1; if (wireLength > 0 && node.leftNode != null) { connectionRow += new string('_', wireLength); } if (node.leftNode != null) { connectionRow += "/"; } else { connectionRow += string.Format("{0, " + (wireLength + 1) + "}", ""); } /* else { //connectionRow += string.Format("{0, " + (wireLength + 1) + "}", ""); } */ //connectionRow += new string('-', wireLength) +"/"; int rightNodeLength = 0; if (node.rightNode != null) { rightNodeLength = node.rightNode.ToString().Length; } treeRow += string.Format("{0, " + (padding + defaultLength) + "}", node.rightNode); if (node.rightNode != null) { connectionRow += "\\"; wireLength = padding / 2 - 1 + RBTree.DefaultLength - rightNodeLength; if (wireLength > 0) { connectionRow += new string('_', wireLength); } connectionRow += string.Format("{0, " + (rightNodeLength) + "}", ""); } else { connectionRow += string.Format("{0, " + (padding / 2 - 1 + RBTree.DefaultLength) + "}", ""); } connection = ""; if (node.rightNode != null) connection = " "; if (wireLength > 0 && node.rightNode != null) { connection = "\\" + new string('_', wireLength) + connection; } //connectionRow += string.Format("{0, " + (padding/2 + defaultLength - rightNodeLength/2) + "}", connection); //connectionRow += string.Format("{0, " + (rightNodeLength/2) + "}", ""); previousNodes.Add(node.rightNode); } } treeRows += connectionRow + "\n"; treeRows += treeRow + "\n"; previousPadding = padding / 2; } return treeRows; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class simonWaiting : MonoBehaviour { private float timer; private bool started = false; public float counter; public GameObject Heart; private void Start() { } void Update () { if (!started) { Heart.SetActive(false); started = true; timer = Time.time + counter; } else{ if (timer < Time.time) { started = false; GetComponent<empatizarController>().levelup = true; this.enabled = false; } } } }
using System; namespace ex20 { public class Pedido { public string[] itens; public string Client; public string Restaurant; public string PayForm; private void makeRequisition(string arg1){ Console.ForegroundColor=ConsoleColor.DarkMagenta; Console.WriteLine("Entregando para o cliente:.{0}",Client); Console.WriteLine("Pedido no restaurante:.....{0}",Restaurant); Console.WriteLine("Forma de pagamento:........{0}",PayForm); Console.ResetColor(); string[] array=arg1.Split("/"); Console.WriteLine("Lista do pedido:"); Console.ForegroundColor=ConsoleColor.DarkYellow; foreach (string item in array) { Console.WriteLine(item); } Console.ResetColor(); } public Pedido(string arg1,string arg2,string arg3,string arg4){ if(arg4.Length >0){ Client=arg2; Restaurant=arg3; PayForm=arg4; makeRequisition(arg1); }else{ Console.ForegroundColor=ConsoleColor.DarkRed; Console.WriteLine("Forma de pagamento nao especificada,desligando..."); Console.ResetColor(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using System.Data.SqlServerCe; using System.IO; using System.Windows.Forms; namespace Speech_Example { class DataBase { public static void Insert_values(MP3 mp3file, int id) { SqlConnection connect = new SqlConnection(); connect.ConnectionString = "Data Source=.;Initial Catalog=Speech;Integrated Security=True"; SqlCommand command = new SqlCommand("INSERT MP3 (Mp3_id, Mp3_file,Description) VALUES (@id,@m3,@d)", connect); SqlParameter par = new SqlParameter("@m3", SqlDbType.Binary); par.Value = mp3file.Mp3byte; command.Parameters.Add(par); SqlParameter par1 = new SqlParameter("@id", SqlDbType.Int); par1.Value = id; command.Parameters.Add(par1); SqlParameter par2 = new SqlParameter("@d", SqlDbType.NVarChar); par2.Value = mp3file.Word; command.Parameters.Add(par2); try { connect.Open(); command.ExecuteNonQuery(); int w = 0; int[] xyc = null; double[,] res = null; alglib.kmeansgenerate(mp3file.Matrix, mp3file.Matrix.GetLength(0), mp3file.Matrix.GetLength(1), 1, 2, out w, out res, out xyc); //for (int j = 0; j < mp3file.Frames.Length; j++) //{ SqlCommand command2 = new SqlCommand("INSERT MFCC (Coef1,Coef2,Coef3,Coef4,Coef5,Coef6,Coef7,Coef8,Coef9,Coef10,Coef11,Coef12,Coef13,Mp3_id) VALUES (@coef1,@coef2,@coef3,@coef4,@coef5,@coef6,@coef7,@coef8,@coef9,@coef10,@coef11,@coef12,@coef13,@id)", connect); SqlParameter[] mpar = new SqlParameter[13]; for (int i = 0; i < mpar.Length; i++) { mpar[i] = new SqlParameter("coef" + (i + 1).ToString(), SqlDbType.Float); mpar[i].Value = (float)res[i,0]; } command2.Parameters.AddRange(mpar); SqlParameter sqid = new SqlParameter("@id", SqlDbType.Int); sqid.Value = id; command2.Parameters.Add(sqid); command2.ExecuteNonQuery(); //} } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connect.Close(); } } public static MP3 [] Read_from_baze() { SqlConnection connect = new SqlConnection(); Dictionary<string, int> dic = new Dictionary<string, int>(); dic.Add("Один", 0); dic.Add("Два", 1); dic.Add("Пять", 2); dic.Add("Шесть", 3); dic.Add("Семь", 4); connect.ConnectionString = "Data Source=.;Initial Catalog=Speech;Integrated Security=True"; string query = "SELECT Description,MP3.Mp3_id,Coef1,Coef2,Coef3,Coef4,Coef5,Coef6,Coef7,Coef8,Coef9,Coef10,Coef11,Coef12,Coef13 FROM MFCC inner join MP3 on MFCC.Mp3_id=MP3.Mp3_id Order by MP3.Mp3_id"; try { connect.Open(); SqlCommand command = new SqlCommand(query, connect); var Reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection); List<MP3> listmp3 = new List<MP3>(); List<double> data = new List<double>(); List<double> all_data = new List<double>(); int id = 0; string descr = ""; while (Reader.Read() == true) { if (id != Convert.ToInt32(Reader.GetValue(1)) && id == 0) { id = Convert.ToInt32(Reader.GetValue(1)); descr = Reader.GetValue(0).ToString(); } if (id != Convert.ToInt32(Reader.GetValue(1))) { MP3 m = new MP3(); // в поле где раньше хранилсь нормализированные данные из мр3 файла записываем значения всех mfcc коэффициентов m.Matrix = new double[data.Count, 1]; for (int h = 0; h < data.Count; h++) m.Matrix[h, 0] = data[h]; m.Word = descr; data.Clear(); listmp3.Add(m); id = Convert.ToInt32(Reader.GetValue(1)); descr = Reader.GetValue(0).ToString(); } if (id == Convert.ToInt32(Reader.GetValue(1))) { for (int i = 2; i < 15; i++) { data.Add(Convert.ToDouble(Reader.GetValue(i))); } } } MP3 m1 = new MP3(); // в поле где раньше хранилсь нормализированные данные из мр3 файла записываем значения всех mfcc коэффициентов m1.Matrix = new double[data.Count, 1]; for (int h = 0; h < data.Count; h++) m1.Matrix[h, 0] = data[h]; m1.Word = descr; data.Clear(); listmp3.Add(m1); Reader.Close(); return listmp3.ToArray(); } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } finally { connect.Close(); } } public static void Delete() { SqlConnection connect = new SqlConnection(); connect.ConnectionString = "Data Source=.;Initial Catalog=Speech;Integrated Security=True"; string query = "DELETE FROM MP3"; SqlCommand command = new SqlCommand(query, connect); string query1 = "DELETE FROM MFCC"; SqlCommand command1 = new SqlCommand(query1, connect); try { connect.Open(); command.ExecuteNonQuery(); command1.ExecuteNonQuery(); } catch (Exception e) { MessageBox.Show(e.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { connect.Close(); } } public static int GetId() { SqlConnection connect = new SqlConnection(); connect.ConnectionString = "Data Source=.;Initial Catalog=Speech;Integrated Security=True"; string query = "SELECT Mp3_id FROM MFCC MP3 Order by MP3.Mp3_id DESC"; connect.Open(); SqlCommand command = new SqlCommand(query, connect); var Reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection); int Id = 0; if(Reader.Read()==true) Id= Convert.ToInt32(Reader.GetValue(0)); Reader.Close(); connect.Close(); return Id; } } }
using OctoFX.Core.Model; namespace OctoFX.Core.Repository { public interface IBeneficiaryAccountRepository : IOctoFXRepository<BeneficiaryAccount> { } public class BeneficiaryAccountRepository : OctoFXRepository<BeneficiaryAccount>, IBeneficiaryAccountRepository { public BeneficiaryAccountRepository(OctoFXContext context) { Context = context; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using AlmenaraGames; #if UNITY_EDITOR using UnityEditor; #endif namespace AlmenaraGames{ [HelpURL("https://almenaragames.github.io/#CSharpClass:AlmenaraGames.MultiAudioListener")] [AddComponentMenu("Almenara Games/MLPAS/Multi Audio Listener")] public class MultiAudioListener : MonoBehaviour { [Tooltip("Sets a position offset to the listener")] [SerializeField] private Vector3 positionOffset = Vector3.zero; bool init=false; private Transform realListener; /// <summary> /// The listener with the offsets applied. /// </summary> [HideInInspector] public Transform RealListener{get{if (!init){Awake();} return realListener;}} /// <summary> /// Sets a position offset to the listener. /// </summary> public Vector3 PositionOffset{ get { //Some other code return LocalOffset?transform.TransformVector(positionOffset):positionOffset; } set { positionOffset = value; } } /// <summary> /// Applied the offset in local space. /// </summary> public bool LocalOffset=false; [Tooltip("Overrides the listener direction, useful for fixed camera angle games like Top Downs or 2D Platformers. Use (0, 0, 0) to disable the forward override")] /// <summary> /// Overrides the listener direction, useful for fixed camera angle games like Top Downs or 2D Platformers. Use (0,0,0) to disable the forward override. /// </summary> public Vector3 OverrideForward = Vector3.zero; /// <summary> /// Applied the forward direction in local space. /// </summary> public bool LocalForward=false; private int globalIndex = -1; /// <summary> /// Gets the listener index, WARNING: Don't modify this value. /// </summary> /// <value>The index.</value> public int Index {get{ return globalIndex; }set{globalIndex = value;}} [Tooltip("This reverb preset will going to affect all nearest Multi Audio Sources, if \"useReverbZones\" is TRUE then this is going to be the default value when the listener is outside of a Multi Reverb Zone")] /// <summary> /// This reverb preset will going to affect all nearest Multi Audio Sources, if "useReverbZones" is TRUE then this is going to be the default value when the <see cref="MultiAudioListener"/> is outside of a <see cref="MultiReverbZone"/> /// </summary> public AudioReverbPreset ReverbPreset; [Tooltip("If set to TRUE the Multi Audio Listener will going to check whether or not is inside a Multi Reverb Zone")] /// <summary> /// If set to TRUE the <see cref="MultiAudioListener"/> will going to check whether or not is inside a <see cref="MultiReverbZone"/>. /// </summary> public bool useReverbZones = true; private AudioReverbPreset initialReverbPreset; float reverbZoneCheckTimer=0f; private bool isApplicationQuitting = false; void Awake() { if (init) return; init = true; GameObject realListenerGo = new GameObject ("realListener"); realListener = realListenerGo.transform; RealListener.parent = this.transform; RealListener.localPosition = Vector3.zero; realListenerGo.hideFlags = HideFlags.HideInHierarchy; } void Start() { initialReverbPreset = ReverbPreset; } // Use this for initialization void OnEnable () { if (OverrideForward != Vector3.zero) { RealListener.forward = !LocalForward?OverrideForward:transform.TransformVector(OverrideForward); } else { RealListener.localEulerAngles = Vector3.zero; } RealListener.position = transform.position + PositionOffset; MultiAudioManager.Instance.AddAvailableListener (this); MultiAudioManager.noListeners = false; } // Update is called once per frame void OnDisable () { if (isApplicationQuitting) return; MultiPoolAudioSystem.audioManager.RemoveAudioListener (this); } void OnApplicationQuit () { isApplicationQuitting = true; } void CheckReverbZones() { if (ReverbPreset != initialReverbPreset) { ReverbPreset = initialReverbPreset; } int maxIndex = MultiPoolAudioSystem.audioManager.reverbZonesCount; if (maxIndex > 0) { for (int i = 0; i < maxIndex; i++) { var rz = MultiPoolAudioSystem.audioManager.reverbZones [i]; if (rz.enabled && rz.col.enabled && rz.IsInside (RealListener.position)) { ReverbPreset = rz.ReverbPreset; } } } } void Update() { if (useReverbZones) { reverbZoneCheckTimer += Time.deltaTime; if (reverbZoneCheckTimer >= 0.1f) { reverbZoneCheckTimer = 0f; CheckReverbZones (); } } } void LateUpdate() { if (OverrideForward != Vector3.zero) { RealListener.forward = !LocalForward?OverrideForward:transform.TransformVector(OverrideForward); } else { RealListener.localEulerAngles = Vector3.zero; } RealListener.position = transform.position + PositionOffset; if (globalIndex != -1) { MultiPoolAudioSystem.audioManager.listenersPositions [globalIndex] = RealListener.position; MultiPoolAudioSystem.audioManager.listenersForwards [globalIndex] = RealListener.right; } if (ReverbPreset == AudioReverbPreset.User) ReverbPreset = AudioReverbPreset.Generic; } void OnDrawGizmosSelected() { Vector3 testForward = OverrideForward.normalized; Gizmos.color = Color.clear; if (Mathf.Abs(testForward.z)>0 && Mathf.Abs(testForward.z)>Mathf.Abs(testForward.x)) Gizmos.color = Color.blue; else if (Mathf.Abs(testForward.x)>0 && Mathf.Abs(testForward.x)>Mathf.Abs(testForward.z)) Gizmos.color = Color.red; if (Mathf.Abs(testForward.y)>0.5) Gizmos.color = Color.green; Gizmos.DrawWireSphere(transform.position + PositionOffset + (!LocalForward?OverrideForward.normalized:transform.TransformVector(OverrideForward.normalized)),0.25f); if (PositionOffset != Vector3.zero) { Gizmos.color = Color.cyan; Gizmos.DrawLine (transform.position, transform.position + PositionOffset); Gizmos.DrawIcon (transform.position, "AlmenaraGames/MLPAS/AudioListenerNoCenterIco"); Gizmos.DrawIcon (transform.position + PositionOffset, "AlmenaraGames/MLPAS/AudioListenerIco"); } else { Gizmos.DrawIcon (transform.position, "AlmenaraGames/MLPAS/AudioListenerIco"); } } #if UNITY_EDITOR [CustomEditor(typeof(MultiAudioListener)), CanEditMultipleObjects] public class MultiAudioListenerEditor : Editor { SerializedObject listenerObj; private Texture logoTex; private Texture logoTex2; private static readonly string[] _dontIncludeMe = new string[]{"m_Script"}; void OnEnable() { listenerObj = new SerializedObject (targets); } public override void OnInspectorGUI() { listenerObj.Update(); if ((target as MultiAudioListener).ReverbPreset == AudioReverbPreset.User) { (target as MultiAudioListener).ReverbPreset = AudioReverbPreset.Off; } DrawPropertiesExcluding(listenerObj, _dontIncludeMe); listenerObj.ApplyModifiedProperties(); } } #endif } }
namespace SelectionCommittee.BLL.DataTransferObject { public class EnrolleeDTO { public string Id { get; set; } public string Email { get; set; } public string Password { get; set; } public string UserName { get; set; } public string Name { get; set; } public string Surname { get; set; } public string Patronymic { get; set; } public string Photo { get; set; } public string Role { get; set; } public int? CityId { get; set; } public int RegionId { get; set; } public int EducationalInstitutionId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AutoVsManualReset { public class _ManualResetEvent { EventWaitHandle _wait_handle = new ManualResetEvent(false); public _ManualResetEvent() { } public void Init() { new Thread(WaitingMethod).Start(); new Thread(WaitingMethod).Start(); new Thread(WaitingMethod).Start(); Thread.Sleep(1500); _wait_handle.Set(); } private void WaitingMethod() { Console.WriteLine("Waiting...."); _wait_handle.WaitOne(); Console.WriteLine("...Completed!"); } } }
using Unity.Entities; using Unity.Burst; using Unity.Collections; public class MeleeDamageSystem : ComponentSystem { private EntityQuery _overlappingMeleePlayerGroup; protected override void OnCreate() { _overlappingMeleePlayerGroup = GetEntityQuery( ComponentType.ReadOnly<PlayerComponent>(), ComponentType.ReadOnly<OverlappingTriggerVolume>(), ComponentType.ReadOnly<OverlappingMelee>()); } [BurstCompile] protected override void OnUpdate() { var overlappingComponents = GetComponentDataFromEntity<OverlappingTriggerVolume>(true); var healthComponents = GetComponentDataFromEntity<Health>(); using (var overlappingEntities = _overlappingMeleePlayerGroup.ToEntityArray(Allocator.TempJob)) { for (int i = 0; i < overlappingEntities.Length; i++) { var entity = overlappingEntities[i]; var overlappingComponent = overlappingComponents[entity]; if (overlappingComponent.HasJustEntered) { var healthComponent = healthComponents[entity]; healthComponent.Value -= 10; healthComponents[entity] = healthComponent; } } } } }
using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using WorkScheduleManagement.Data.Entities.Requests; using WorkScheduleManagement.Data.Enums; using WorkScheduleManagement.Persistence; namespace WorkScheduleManagement.Application.CQRS.Queries { public static class GetRequestById { public record Query(string Id) : IRequest<Request>; public class Handler : IRequestHandler<Query, Request> { private readonly AppDbContext _context; public Handler(AppDbContext context) { _context = context; } public async Task<Request> Handle(Query request, CancellationToken cancellationToken) { var receivedRequest = await _context .Requests .Where(r => r.Id.ToString() == request.Id) .Include(r => r.Approver) .Include(r => r.RequestTypes) .Include(r => r.RequestStatus) .FirstOrDefaultAsync(); switch (receivedRequest.RequestTypes.Id) { case RequestType.OnHoliday: var holidayRequest = await _context.HolidayRequest .Where(r => r.Id == receivedRequest.Id) .Include(r => r.HolidayList) .Include(r => r.Replacer) .FirstOrDefaultAsync(); return new HolidayRequest { Id = holidayRequest.Id, RequestTypes = receivedRequest.RequestTypes, RequestStatus = receivedRequest.RequestStatus, Approver = receivedRequest.Approver, Replacer = holidayRequest.Replacer, HolidayList = holidayRequest.HolidayList, Comment = holidayRequest.Comment }; case RequestType.OnVacation: var vacationRequest = await _context.VacationRequests .Where(r => r.Id == receivedRequest.Id) .Include(r => r.VacationType) .Include(r => r.Replacer) .FirstOrDefaultAsync(); return new VacationRequest { Id = vacationRequest.Id, RequestTypes = receivedRequest.RequestTypes, RequestStatus = receivedRequest.RequestStatus, Approver = receivedRequest.Approver, Replacer = vacationRequest.Replacer, VacationType = vacationRequest.VacationType, Comment = vacationRequest.Comment, DateFrom = vacationRequest.DateFrom, DateTo = vacationRequest.DateTo, IsShifting = vacationRequest.IsShifting }; case RequestType.OnRemoteWork: var remoteWorkRequest = await _context.RemoteWorkRequest .Where(r => r.Id == receivedRequest.Id) .Include(r => r.RemotePlans) .FirstOrDefaultAsync(); return new RemoteWorkRequest { Id = remoteWorkRequest.Id, RequestTypes = receivedRequest.RequestTypes, RequestStatus = receivedRequest.RequestStatus, Approver = receivedRequest.Approver, RemotePlans = remoteWorkRequest.RemotePlans, Comment = remoteWorkRequest.Comment, }; case RequestType.OnDayOffInsteadOverworking: var dayOffInsteadOverworkingRequest = await _context.DayOffInsteadOverworkingRequest .Where(r => r.Id == receivedRequest.Id) .Include(r => r.Replacer) .Include(r => r.DaysOffInsteadOverworking) .FirstOrDefaultAsync(); return new DayOffInsteadOverworkingRequest { Id = dayOffInsteadOverworkingRequest.Id, RequestTypes = receivedRequest.RequestTypes, RequestStatus = receivedRequest.RequestStatus, Approver = receivedRequest.Approver, Replacer = dayOffInsteadOverworkingRequest.Replacer, Comment = dayOffInsteadOverworkingRequest.Comment, DateFrom = dayOffInsteadOverworkingRequest.DateFrom, DateTo = dayOffInsteadOverworkingRequest.DateTo, DaysOffInsteadOverworking = dayOffInsteadOverworkingRequest.DaysOffInsteadOverworking }; case RequestType.OnDayOffInsteadVacation: var dayOffInsteadVacationRequest = await _context.DayOffInsteadVacationRequest .Where(r => r.Id == receivedRequest.Id) .Include(r => r.Replacer) .Include(r => r.DaysOffInsteadVacation) .FirstOrDefaultAsync(); return new DayOffInsteadVacationRequest() { Id = dayOffInsteadVacationRequest.Id, RequestTypes = receivedRequest.RequestTypes, RequestStatus = receivedRequest.RequestStatus, Approver = receivedRequest.Approver, Replacer = dayOffInsteadVacationRequest.Replacer, Comment = dayOffInsteadVacationRequest.Comment, DaysOffInsteadVacation = dayOffInsteadVacationRequest.DaysOffInsteadVacation }; default: return null; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassiAstratte2 { public abstract class Solid { double _specificWeight; string _name; //costruttore base non isntanziabile public Solid(double specificWeigth, string name) { _specificWeight = specificWeigth; _name = name; } public double Weight() { return Volume() * _specificWeight; } public string NameSolid() { return _name; } //metodi astratti public abstract double Volume(); // metodo astratto public abstract double Surface(); // metodo astratto } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace AnyTest.Model { public class Student { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public long Id { get; set; } [ForeignKey(nameof(Id))] public virtual Person Person { get; set; } public virtual ICollection<StudentTest> Tests { get; set; } public virtual ICollection<StudentCourse> Courses { get; set; } public virtual ICollection<TestPass> Passes { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MessageTranslate { public class TCP { public static Socket BuildServer(string Ip, int Port) { IPAddress ip = IPAddress.Parse(Ip); IPEndPoint ipe = new IPEndPoint(ip, Port); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Bind(ipe); return s; } /// <summary> /// 服务侦听 /// </summary> /// <param name="Backlog">挂起的连接请求</param> /// <param name="SvrSocket">服务套接字</param> public static void ServerListen(int Backlog, Socket SvrSocket) { SvrSocket.Listen(Backlog);//开始监听 while (true) { //if (Commond.IsClose) // break; //服务器监听,建立socket Socket ClientSocket = SvrSocket.Accept(); ClientSocket.ReceiveTimeout = 3000; //创建线程 Thread thSocket = new Thread(new ParameterizedThreadStart(MultiSocket)); //线程启动,参数为socket thSocket.Start(ClientSocket); //MultiSocket(ClientSocket); } } /// <summary> /// 处理 /// </summary> /// <param name="ClientSocket">客户端对象</param> public static void MultiSocket(Object cSocket) { Socket ClientSocket = cSocket as Socket; byte[] ReceiveData = new byte[1024]; try { //自动断线时间为30秒 ClientSocket.ReceiveTimeout = 30000; if (ClientSocket.Poll(30000000, SelectMode.SelectRead)) { //连续收发 while (true) { int DataLength = ClientSocket.Receive(ReceiveData); if (DataLength <= 0) { Thread.ResetAbort(); ClientSocket.Close(); } else { //处理 } } } else { ClientSocket.Close(); } } catch (Exception ex) { //写到日志和前台 ClientSocket.Close(); ClientSocket.Dispose(); LogWrite.WriteError(ex.Message); } } /// <summary> /// Tcp指令发送 /// </summary> /// <param name="ClientSocket">自定义Socket对象</param> /// <returns>发送结果</returns> public static void Send(Socket socket) { } } }
using System; namespace TheZhazha.Events { public delegate void MoodChangedEventHandler(object sender, MoodChangedEventArgs e); public class MoodChangedEventArgs : EventArgs { public string Mood { get; private set; } public MoodChangedEventArgs(string mood) { Mood = mood; } } }
using RRExpress.AppCommon; using RRExpress.AppCommon.Attributes; using System.Collections.Generic; namespace RRExpress.ViewModels { /// <summary> /// 个人信息修改页 /// </summary> [Regist(InstanceMode.Singleton)] public class EditMyInfoViewModel : BaseVM { public override string Title { get { return "个人信息修改"; } } public List<string> Sexs { get; } public string Sex { get; set; } public EditMyInfoViewModel() { this.Sexs = new List<string>() { "男","女","保密" }; } } }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.IO; namespace GhostscriptSharp { public class GhostscriptManager : IDisposable { #region Constants public const String KernelDllName = "kernel32.dll"; #endregion #region Hooks into the kernel32 DLL (for loading unmanaged code) [DllImport(KernelDllName, SetLastError = true)] static extern IntPtr LoadLibrary(string lpFileName); [DllImport(KernelDllName, SetLastError = true)] static extern int FreeLibrary(IntPtr hModule); [DllImport(KernelDllName, SetLastError = true)] static extern int SetDllDirectory(string lpPathName); #endregion #region Globals protected static object resourceLock = new object(); protected static String[] defaultArgs; protected static String[] DefaultArgs { get { if (defaultArgs == null) { defaultArgs = new String[] { "-dPARANOIDSAFER", // Run in safe mode "-dBATCH", // Exit after completing commands "-dNOPAUSE", // Do not pause for each page "-dNOPROMPT" // Don't prompt for user input }; } return defaultArgs; } } protected static String ghostscriptLibraryPath; public static String GhostscriptLibraryPath { get { return ghostscriptLibraryPath == null ? String.Empty : ghostscriptLibraryPath; } set { ghostscriptLibraryPath = value; } } protected static GhostscriptManager _instance; public static GhostscriptManager GetInstance() { lock (resourceLock) { if (_instance == null) { _instance = new GhostscriptManager(); } return _instance; } } #endregion protected IntPtr libraryHandle; protected bool revisionInfoLoaded; protected String productName; protected String copyright; protected Int32 revision; protected Int32 revisionDate; protected GhostscriptSettings settings; public GhostscriptSettings Settings { get { return settings; } } protected GhostscriptManager() { revisionInfoLoaded = false; libraryHandle = IntPtr.Zero; LoadGhostscriptLibrary(); this.settings = new GhostscriptSettings(); } protected void LoadGhostscriptLibrary() { SetDllDirectory(GhostscriptLibraryPath); libraryHandle = LoadLibrary(API.GhostscriptDllName); } protected void UnloadGhostscriptLibrary() { if (libraryHandle != IntPtr.Zero) { FreeLibrary(libraryHandle); libraryHandle = IntPtr.Zero; } } /// <summary> /// Run the Ghostscript interpreter providing the output file and input file(s) /// </summary> /// <param name="outputPath">The path to create the output file. Put '%d' the path to create multiple numbered files, one for each page</param> /// <param name="inputPaths">One or more input files</param> public void DoConvert(String outputPath, params String[] inputPaths) { IntPtr gsInstancePtr; lock (resourceLock) { API.CreateAPIInstance(out gsInstancePtr, IntPtr.Zero); try { if (StdOut != null || StdErr != null) { API.StdoutCallback stdout; #region Set StdOut if (StdOut != null) { stdout = (caller_handle, buf, len) => { StdOut(this, new StdOutputEventArgs(buf.Substring(0, len))); return len; }; } else { stdout = EmptyStdoutCallback; } #endregion API.StdoutCallback stderr; #region Set StdErr if (StdErr != null) { stderr = (caller_handle, buf, len) => { StdOut(this, new StdOutputEventArgs(buf.Substring(0, len))); return len; }; } else { stderr = EmptyStdoutCallback; } #endregion API.Set_Stdio(gsInstancePtr, EmptyStdinCallback, stdout, stderr); } String[] args = null; { List<String> lArgs = new List<string>(); lArgs.Add("GhostscriptSharp"); // First arg is ignored, corresponds to argv[0] lArgs.AddRange(GhostscriptManager.DefaultArgs); lArgs.AddRange(this.Settings.GetGhostscriptArgs()); lArgs.Add(String.Format("-sOutputFile={0}", outputPath)); lArgs.AddRange(inputPaths); args = lArgs.ToArray(); } int result = API.InitAPI(gsInstancePtr, args.Length, args); if (result < 0) { throw new GhostscriptException("Ghostscript conversion error", result); } } finally { API.ExitAPI(gsInstancePtr); API.DeleteAPIInstance(gsInstancePtr); } } } #region Revision Info Properties /// <summary> /// Name of the product obtained from the Ghostscript DLL e.g. "GPL Ghostscript" /// </summary> public String ProductName { get { if (!revisionInfoLoaded) { LoadRevisionInfo(); } return productName; } } /// <summary> /// Copyright Information obtained from the Ghostscript DLL /// </summary> public String Copyright { get { if (!revisionInfoLoaded) { LoadRevisionInfo(); } return copyright; } } /// <summary> /// Revision Number of the Ghostscript DLL e.g. 871 for v8.71 /// </summary> public Int32 Revision { get { if (!revisionInfoLoaded) { LoadRevisionInfo(); } return revision; } } /// <summary> /// Revision Date of the Ghostscript DLL in the format yyyyMMdd /// </summary> public Int32 RevisionDate { get { if (!revisionInfoLoaded) { LoadRevisionInfo(); } return revisionDate; } } /// <summary> /// Get Ghostscript Library revision info /// </summary> /// <param name="strProduct"></param> /// <param name="strCopyright"></param> /// <param name="intRevision"></param> /// <param name="intRevisionDate"></param> protected void LoadRevisionInfo() { API.GS_Revision rev; API.GetRevision(out rev, API.GS_Revision_Size_Bytes); this.productName = rev.strProduct; this.copyright = rev.strCopyright; this.revision = rev.intRevision; this.revisionDate = rev.intRevisionDate; this.revisionInfoLoaded = true; } #endregion #region stdin, stdout, stderr handlers //public delegate void StdinReader(StringBuilder input); public delegate void StdOutputHandler(object sender, StdOutputEventArgs args); //public event StdinReader StdIn; public event StdOutputHandler StdOut; public event StdOutputHandler StdErr; /// <summary> /// "Default" implementation of StdinCallback - gives Ghostscript EOF whenever it requests input /// </summary> /// <param name="caller_handle"></param> /// <param name="buf"></param> /// <param name="len"></param> /// <returns>0 (EOF) whenever GS requests input</returns> protected API.StdinCallback EmptyStdinCallback = new API.StdinCallback(delegate(IntPtr caller_handle, IntPtr buf, Int32 len) { return 0; // return EOF always }); //protected API.StdinCallback EmptyStdinCallback = (caller_handle, buf, len) => //{ // return 0; // return EOF always //}; /// <summary> /// "Default" implementation of StdoutCallback - does nothing with output, returns all characters handled /// </summary> /// <param name="caller_handle"></param> /// <param name="buf"></param> /// <param name="len"></param> /// <returns>len (the number of characters handled) whenever GS outputs anything</returns> protected API.StdoutCallback EmptyStdoutCallback = (caller_handle, buf, len) => { return len; // return all bytes handled }; #endregion #region IDisposable Members public void Dispose() { UnloadGhostscriptLibrary(); } #endregion #region Convenience Methods /// <summary> /// Convert a postscript file to a pdf /// </summary> /// <param name="outputPath">The path to create the output file. Put '%d' the path to create multiple numbered files, one for each page</param> /// <param name="inputPaths">One or more input files</param> public static void PsToPdf(String outputPath, params String[] inputPaths) { GhostscriptManager gsm = GhostscriptManager.GetInstance(); bool libraryLoaded = (gsm.libraryHandle != IntPtr.Zero); if (!libraryLoaded) { gsm.LoadGhostscriptLibrary(); } GhostscriptSettings oldSettings = gsm.Settings; gsm.settings = new GhostscriptSettings(); gsm.Settings.Device = GhostscriptSharp.Settings.GhostscriptDevices.pdfwrite; gsm.Settings.Page.AllPages = true; gsm.Settings.Quiet = true; gsm.DoConvert(outputPath, inputPaths); if (!libraryLoaded) { gsm.UnloadGhostscriptLibrary(); } gsm.settings = oldSettings; } #endregion } }
using System; using System.Text; using System.Text.RegularExpressions; namespace _03_Cubic_s_Messages { public class _03_Cubic_s_Messages { public static void Main() { var input = ""; while ((input = Console.ReadLine()) != "Over!") { var n = int.Parse(Console.ReadLine()); var escapedValidPAttern = new Regex($@"^(\d+)([A-Za-z]{{{n}}})([^A-Za-z]*)$"); var match = escapedValidPAttern.Match(input); if (match.Success) { var message = match.Groups[2].Value; var verificationCode = Decoder(match.Groups[1].Value, match.Groups[3].Value, message); Console.WriteLine($"{message} == {verificationCode}"); } } } public static string Decoder(string first, string second, string message) { var inputString = first; var sb = new StringBuilder(); var digitPattern = new Regex(@"\d"); var secondPartMatches = digitPattern.Matches(second); foreach (Match match in secondPartMatches) { inputString += match.Value; } foreach (var item in inputString) { var digit = item - '0'; if (digit >= 0 && digit < message.Length) { sb.Append(message[digit]); } else { sb.Append(" "); } } return sb.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RechargePellet : RechargeMarker, PoolObject { [Header("Recharge Pellet Settings")] public float Lifetime; private float aliveTime; [Header("Pool Object Settings")] [SerializeField] protected string _key; public string Key { get { return _key; } set { _key = value; } } [SerializeField] protected int _startingCount; public int StartingCount { get { return _startingCount; } set { _startingCount = value; } } public static RechargePellet Create() { var name = "Recharge-Pellet"; PoolManager pm = PoolManager.Instance; if (!pm.ContainsKey(name)) { RechargePellet prefab = Resources.Load<RechargePellet>($"Prefabs/{name}"); prefab.Key = name; pm.CreatePool(prefab); } RechargePellet seg = pm.Next<RechargePellet>(name); return seg; } public override void ActivatedAction() { Recycle(); } public void Update() { aliveTime += Time.deltaTime; if(Lifetime < aliveTime){ Recycle(); } } public void Recycle() { aliveTime = 0; this.gameObject.SetActive(false); PoolManager.Instance.Recycle(this); } public override bool IsConditionMet(bool jumping, bool attachedToRail, float direction) { return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.ComponentModel; namespace KartSystem { public class CashDocumentSpecRecord : Entity { public CashDocumentSpecRecord() { } [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "CashDocumentSpecRecord"; } } /// <summary> /// Идентификатор /// </summary> [DisplayName("Идентификатор")] public long Id { get; set; } /// <summary> /// Наименование операции /// </summary> [DisplayName("Наименование операции")] public string CashOpName { get; set; } /// <summary> /// Наименование поставщика /// </summary> [DisplayName("Наименование поставщика")] public string Supplier { get; set; } /// <summary> /// Имя сотрудника /// </summary> [DisplayName("Имя сотрудника")] public string Customer { get; set; } /// <summary> /// Дата документа /// </summary> [DisplayName("Дата документа")] public DateTime DateDoc { get; set; } /// <summary> /// Цена документа /// </summary> [DisplayName("Цена документа")] public decimal SummDoc { get; set; } /// <summary> /// Флаг операции /// </summary> [DisplayName("Флаг операции")] public int Direction { get; set; } /// <summary> /// Номер документа /// </summary> [DisplayName("Номер документа")] public string cashdoctype { get; set; } /// <summary> /// Баланс /// </summary> [DisplayName("Баланс")] public decimal Balance { get; set; } } }
using System; using System.Linq; using System.Reflection; using Sandbox.Game.Entities; using Torch.Managers.PatchManager; using VRage.Game; using VRage.Sync; using VRageMath; namespace DataValidateFix { internal static class ReflectionExtensions { private static readonly FieldInfo ValueChangedEventInfo = typeof(SyncBase).GetPrivateFieldInfo("ValueChanged"); internal static PropertyInfo GetPublicPropertyInfo(this Type type, string propertyName) => type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance) ?? throw new MissingMemberException(type.Name, propertyName); internal static FieldInfo GetPrivateFieldInfo(this Type type, string fieldName) => type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance) ?? throw new MissingFieldException(type.Name, fieldName); internal static T GetPrivateConstValue<T>(this Type type, string fieldName) => (T) (type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static) ?? throw new MissingFieldException(type.Name, fieldName)).GetValue(null); internal static MethodInfo GetMethod(this Type type, string methodName, params Type[] types) => type.GetMethod(methodName, types) ?? throw new MissingMethodException(type.Name, methodName); internal static T GetValue<T>(this FieldInfo fieldInfo, object obj) where T : class => (T) fieldInfo.GetValue(obj); internal static Sync<T, SyncDirection.BothWays> GetSync<T>(this FieldInfo fieldInfo, object obj) => (Sync<T, SyncDirection.BothWays>) fieldInfo.GetValue(obj); internal static void TypedValueChanged<T>( this Sync<T, SyncDirection.BothWays> sync, Action<Sync<T, SyncDirection.BothWays>> action) { sync.ValueChanged += syncBase => action((Sync<T, SyncDirection.BothWays>) syncBase); } internal static void TypedValueChangedFirst<T>( this Sync<T, SyncDirection.BothWays> sync, Action<Sync<T, SyncDirection.BothWays>> action) { var @event = (MulticastDelegate) ValueChangedEventInfo.GetValue(sync); var invocationList = @event.GetInvocationList().Cast<Action<SyncBase>>().ToList(); invocationList.ForEach(it => sync.ValueChanged -= it); sync.ValueChanged += syncBase => action((Sync<T, SyncDirection.BothWays>) syncBase); invocationList.ForEach(it => sync.ValueChanged += it); } internal static void ValueChangedInRange<T>( this Sync<T, SyncDirection.BothWays> sync, T min, T max) where T : IComparable { sync.TypedValueChangedFirst(it => { var value = it.Value; if (value.CompareTo(max) > 0) sync.Value = max; //NaN less than any number else if (value.CompareTo(min) < 0) sync.Value = min; }); } internal static void ValueChangedInRange( this Sync<Vector3, SyncDirection.BothWays> sync, Vector3 min, Vector3 max) { sync.TypedValueChangedFirst(it => { var value = it.Value; if (!value.IsInsideInclusive(ref min, ref max)) { it.Value = value.Clamp(ref min, ref max); } }); } internal static void PatchInit<T>(this PatchContext patchContext, Action<T> patch) { var init = typeof(T).GetMethod( "Init", typeof(MyObjectBuilder_CubeBlock), typeof(MyCubeGrid) ); patchContext.GetPattern(init).Suffixes.Add(patch.Method); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class OptionSliderBehaviour : MonoBehaviour { public Text minval; public Text maxval; public Text curval; public Text title; public Slider slider; public void Start() { title.text = slider.onValueChanged.GetPersistentMethodName(0); minval.text = slider.minValue+""; maxval.text = slider.maxValue+""; slider.onValueChanged.AddListener((v)=> { curval.text = v+""; }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Orleans; namespace Grains { public class UserGrain : Grain, IUserGrain { public Task InitUser() { return TaskDone.Done; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPC.SQLAPI { /// <summary> /// An interface to represent converters from SQL results represented by a <see cref="RowReader"/> to concrete model types. /// </summary> /// <typeparam name="TResult"></typeparam> public interface SQLResultConverter<out TResult> { /// <summary> /// Converts column data from a SQL resultset into a <typeparamref name="TResult"/> instance. /// </summary> /// <param name="rr"></param> /// <returns></returns> TResult Convert(RowReader rr); } }
// Copyright © 2020 Void-Intelligence All Rights Reserved. namespace Vortex.Activation.Utility { public enum EActivationType { Invalid, Arctan, BinaryStep, BipolarSigmoid, Elu, Exponential, HardSigmoid, HardTanh, Identity, Loggy, Logit, LRelu, Mish, Relu, Selu, Sigmoid, Softmax, Softplus, Softsign, Swish, Tanh } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ace { /// <summary> /// 3Dオブジェクトの更新と描画を管理するレイヤーの機能を提供するクラス /// </summary> public class Layer3D : Layer, IDestroy { /// <summary> /// コンストラクタ /// </summary> public Layer3D() { coreLayer3D = Engine.ObjectSystemFactory.CreateLayer3D(); var p = coreLayer3D.GetPtr(); if (GC.Layer3Ds.GetObject(p) != null) { throw new Exception(); } GC.Layer3Ds.AddObject(p, this); objects_ = new List<Object3D>(); commonObject = coreLayer3D; } #region GC対策 ~Layer3D() { Destroy(); } public bool IsDestroyed { get { return coreLayer3D == null; } } public void Destroy() { lock (this) { if (coreLayer3D == null) return; GC.Collector.AddObject(coreLayer3D); coreLayer3D = null; } System.GC.SuppressFinalize(this); } #endregion swig.CoreLayer3D coreLayer3D { get; set; } /// <summary> /// このレイヤーが管理している3Dオブジェクトのコレクションを取得する。 /// </summary> public IEnumerable<Object3D> Objects { get { return objects_; } } /// <summary> /// このレイヤーに指定した3Dオブジェクトを追加する。 /// </summary> /// <param name="object3D">追加する3Dオブジェクト</param> public void AddObject(Object3D object3D) { if (object3D.Layer != null) { throw new InvalidOperationException("指定したオブジェクトは既に別のレイヤーに所属しています。"); } objects_.Add(object3D); coreLayer3D.AddObject(object3D.CoreObject); object3D.Layer = this; object3D.Start(); } /// <summary> /// このレイヤーから指定した3Dオブジェクトを削除する。 /// </summary> /// <param name="object3D">削除される3Dオブジェクト</param> public void RemoveObject(Object3D object3D) { objects_.Remove(object3D); coreLayer3D.RemoveObject(object3D.CoreObject); object3D.Layer = null; } internal override void BeginUpdating() { coreLayer3D.BeginUpdating(); } internal override void EndUpdating() { coreLayer3D.EndUpdating(); } internal override void Update() { if (!IsUpdated) { return; } OnUpdating(); foreach (var item in objects_) { item.Update(); } objects_.RemoveAll(_ => !_.IsAlive); OnUpdated(); } internal override void DrawAdditionally() { if (!IsDrawn) { return; } foreach (var item in objects_) { item.OnDrawAdditionally(); } OnDrawAdditionally(); } private List<Object3D> objects_ { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task1 { class Program { static void Main(string[] args) { string path = @"..\..\..\task1.dat"; using (var str = new BinaryWriter(File.Open(path, FileMode.OpenOrCreate))) { for (int i = 0; i < 10;i++) { str.Write(i); } } } } }
using System; namespace SocketLite.Net { /// <summary> /// 异常处理器 /// </summary> public static class ExceptionHandler { private static readonly object handlerLocker = new object(); /// <summary> /// 处理异常 /// </summary> /// <param name="exception">异常</param> public static void Handle(Exception exception) { lock (handlerLocker) { //Logger.Exception(exception); } } /// <summary> /// 处理异常 /// </summary> /// <param name="message">异常信息</param> /// <param name="exception">异常</param> public static void Handle(string message, Exception exception) { lock (handlerLocker) { //Logger.Exception(message, exception); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace SafeControls { public class SafeToolStripProgressBar : ToolStripProgressBar { delegate void SetValue(int value); delegate int GetValue(); delegate void SetMaximum(int value); delegate int GetMaximim(); public int Value { get { if ((base.Parent != null) && // Make sure that the container is already built (base.Parent.InvokeRequired)) // Is Invoke required? { GetValue getValueDel = delegate() { return base.Value; }; int value = 0; try { // Invoke the SetText operation from the Parent of the ToolStripProgressBar value = (int)base.Parent.Invoke(getValueDel, null); } catch { } return value; } else { return base.Value; } } set { // Get from the container if Invoke is required if ((base.Parent != null) && // Make sure that the container is already built (base.Parent.InvokeRequired)) // Is Invoke required? { SetValue setValueDel = delegate(int val) { base.Value = val; }; try { // Invoke the SetText operation from the Parent of the ToolStripProgressBar base.Parent.Invoke(setValueDel, new object[] { value }); } catch { } } else base.Value = value; } } public int Maximo { get { if ((base.Parent != null) && // Make sure that the container is already built (base.Parent.InvokeRequired)) // Is Invoke required? { GetMaximim getMax = delegate() { return base.Maximum; }; int value = 100; try { // Invoke the SetText operation from the Parent of the ToolStripProgressBar value = (int)base.Parent.Invoke(getMax, null); } catch { } return value; } else { return base.Maximum; } } set { // Get from the container if Invoke is required if ((base.Parent != null) && // Make sure that the container is already built (base.Parent.InvokeRequired)) // Is Invoke required? { SetMaximum _max = delegate(int val) { base.Maximum = val; }; try { // Invoke the Maximum operation from the Parent of the ToolStripProgressBar base.Parent.Invoke(_max, new object[] { value }); } catch { } } else base.Maximum = value; } } } }
using CarRental.API.Common.SettingsOptions; using CarRental.API.DAL.Entities; using CarRental.API.DAL.CustomEntities; using Dapper; using Dapper.FastCrud; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading.Tasks; namespace CarRental.API.DAL.DataServices.Reservations { public class ReservationDataService : BaseDataService , IReservationDataService { private const string SpCreate = "CreateReservation"; private const string SpCreateWithNewClient = "CreateReservationWithNewClient"; private const string SpReadAll = "GetReservations"; private const string SpUpdate = "UpdateReservation"; private const string ReadDetailedReservations = "GetDetailedReservations"; public ReservationDataService(IOptions<DatabaseOptions> databaseOptions) : base(databaseOptions) { } public async Task<IEnumerable<ReservationItem>> CreateAsync(ReservationItem reservation) { using (var conn = await GetOpenConnectionAsync()) { return await conn.QueryAsync<ReservationItem>( param: new { Id = reservation.Id, ClientId = reservation.ClientId, CarId = reservation.CarId, RentalStartDate = reservation.RentalStartDate, RentalEndDate = reservation.RentalEndDate, PickUpLocation = reservation.PickUpLocation, DropOffLocation = reservation.DropOffLocation, TotalPrice = reservation.TotalPrice }, sql: SpCreate, commandType: CommandType.StoredProcedure); } } public async Task<IEnumerable<ReservationItem>> CreateAsyncWithNewClient(ReservationItem reservation, ClientsItem client) { using (var conn = await GetOpenConnectionAsync()) { return await conn.QueryAsync<ReservationItem>( param: new { Id = reservation.Id, FullName = client.FullName, CarId = reservation.CarId, RentalStartDate = reservation.RentalStartDate, RentalEndDate = reservation.RentalEndDate, PickUpLocation = reservation.PickUpLocation, DropOffLocation = reservation.DropOffLocation, TotalPrice = reservation.TotalPrice }, sql: SpCreateWithNewClient, commandType: CommandType.StoredProcedure); } } public async Task<ReservationItem> DeleteAsync(Guid id) { using (var conn = await GetOpenConnectionAsync()) { conn.Delete<ReservationItem>(new ReservationItem { Id = id }); } return null; } public async Task<IEnumerable<ReservationItem>> GetAllAsync() { using (var conn = await GetOpenConnectionAsync()) { return await conn.QueryAsync<ReservationItem>( sql: SpReadAll, commandType: CommandType.StoredProcedure); } } public async Task<IEnumerable<DetailedReservations>> GetDetailedReservations() { using (var conn = await GetOpenConnectionAsync()) { return await conn.QueryAsync<DetailedReservations>( sql: ReadDetailedReservations, commandType: CommandType.StoredProcedure); } } public async Task<ReservationItem> GetAsync(Guid id) { using (var conn = await GetOpenConnectionAsync()) { return await conn.GetAsync(new ReservationItem() { Id = id }); } } public async Task<IEnumerable<ReservationItem>> UpsertAsync(ReservationItem reservation) { using (var conn = await GetOpenConnectionAsync()) { return await conn.QueryAsync<ReservationItem>( param: new { Id = reservation.Id, ClientId = reservation.ClientId, CarId = reservation.CarId, RentalStartDate = reservation.RentalStartDate, RentalEndDate = reservation.RentalEndDate, PickUpLocation = reservation.PickUpLocation, DropOffLocation = reservation.DropOffLocation, }, sql: SpUpdate, commandType: CommandType.StoredProcedure); } } } }
/**************************************************** 文件:Enemy_Eagle.cs 作者:Sam 邮箱: 403117224@qq.com 日期:2020/01/20 1:33 功能:鹰 *****************************************************/ using UnityEngine; public class Enemy_Eagle : Enemy { private Rigidbody2D rb; //private Animator Anim; public Transform Top, Bottom; public float Speed;//浮点型,可更改 private float TopX, TopY, BottomX, BottomY;//浮点型 private bool isLeft = true; private bool isTop = true; private bool isLeftTop = true; private bool isLeftBottom = true; protected override void Start() { base.Start();//调用父级的Start rb = GetComponent<Rigidbody2D>(); //Anim = GetComponent<Animator>();//获得动画 transform.DetachChildren();//断绝关系 TopX = Top.position.x; TopY = Top.position.y; BottomX = Bottom.position.x; BottomY = Bottom.position.y; Destroy(Top.gameObject); Destroy(Bottom.gameObject); } void Update() { SwitchAnim(); Movement(); } void Movement() { if (TopY == BottomY)//左右 { if (isLeft) { rb.velocity = new Vector2(-Speed, rb.velocity.y); if (transform.position.x < TopX) { transform.localScale = new Vector3(-1, 1, 1); isLeft = false; } } else { rb.velocity = new Vector2(Speed, rb.velocity.y); if (transform.position.x > BottomX) { transform.localScale = new Vector3(1, 1, 1); isLeft = true; } } } if (TopX == BottomX)//上下 { if (isTop) { rb.velocity = new Vector2(rb.velocity.x, Speed); if (transform.position.y > TopY) { isTop = false; } } else { rb.velocity = new Vector2(rb.velocity.x, -Speed); if (transform.position.y < BottomY) { isTop = true; } } } if (TopX < BottomX && TopY > BottomY)//左上、右下 { if (isLeftTop) { rb.velocity = new Vector2(-Speed, Speed); if (transform.position.x < TopX && transform.position.y > TopY) { transform.localScale = new Vector3(-1, 1, 1); isLeftTop = false; } } else { rb.velocity = new Vector2(Speed, -Speed); if (transform.position.x > BottomX && transform.position.y < BottomY) { transform.localScale = new Vector3(1, 1, 1); isLeftTop = true; } } } if (TopX < BottomX && TopY < BottomY)//左下、右上 { if (isLeftBottom) { rb.velocity = new Vector2(-Speed, -Speed); if (transform.position.x < TopX && transform.position.y < TopY) { transform.localScale = new Vector3(-1, 1, 1); isLeftBottom = false; } } else { rb.velocity = new Vector2(Speed, Speed); if (transform.position.x > BottomX && transform.position.y > BottomY) { transform.localScale = new Vector3(1, 1, 1); isLeftBottom = true; } } } } void SwitchAnim() { } }
using Microsoft.Xna.Framework.Input; namespace Entoarox.Framework.Interface { public interface IHotkeyComponent : IDynamicComponent { /********* ** Methods *********/ /// <summary>This event is triggered whenever a keyboard key is pressed. If <see cref="IDynamicComponent.Enabled" /> or <see cref="IComponent.Visible" /> is false, this event will not trigger. If a component is both <see cref="IHotkeyComponent" /> and <see cref="IInputComponent" /> then unless <see cref="IInputComponent.Selected" /> is false, input events happen instead of hotkey events.</summary> /// <param name="key">The key pressed.</param> bool ReceiveHotkey(Keys key); } }
using Prism.Commands; using Prism.Mvvm; using Prism.Navigation; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ObservableTune.ViewModels { public class MainPageViewModel : ViewModelBase { public MainPageViewModel(INavigationService navigationService) : base(navigationService) { Title = "Main Page"; } private List<string> _appearStrategy; public List<string> AppearStrategy { get { return _appearStrategy; } set { SetProperty(ref _appearStrategy, value); } } private string _selectedAppearStrategy; public string SelectedAppearStrategy { get { return _selectedAppearStrategy; } set { SetProperty(ref _selectedAppearStrategy, value); } } public override void Initialize(INavigationParameters parameters) { ChargerListStrategies(); base.Initialize(parameters); } private void ChargerListStrategies() { var targetType = typeof(IAppearStrategy); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => targetType.IsAssignableFrom(p) && p.IsClass).Select(x => x.FullName).ToList(); AppearStrategy = types; SelectedAppearStrategy = AppearStrategy.FirstOrDefault(); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CS_2_HomeWork.Object { class Kit : BaseObject { public bool IsMissing { get; set; } = false; public Kit(Bitmap img, Point pos, Point dir, Size size) : base(img, pos, dir, size) { } } }
using Revisao.LogConfing; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExceptionControl.LogConfing { public class ExceptionText { public ExceptionText(Exception ex) { string errorFormat = String.Format("Data do ERRO: {0} <br> Mensagem de ERRO: {1} <br> Valores da exceção: {2} <br> Códificação do ERRO: {3} <br> Link referente ao ERRO: {4}", DateTime.Now.ToString(), ex.Message, ex.Data, ex.HResult, ex.HelpLink); string dataLog = String.Format("log{0}", DateTime.Now.ToString()).Replace('/', '_').Replace('.', '_').Replace(':', '_').Replace(' ', '_'); string path = @"C:\Users\Public\WakoolErrors"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); File.AppendAllText((path + "\\" + dataLog), errorFormat); new SendEmail(errorFormat); } } }
using ContosoPortal.Models; using GistackWAPService.models; using System; using System.Collections.Generic; using System.Configuration; using System.IdentityModel.Protocols.WSTrust; using System.IdentityModel.Tokens; using System.Linq; using System.Net; using System.Net.Security; using System.Runtime.Serialization; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Security; using System.ServiceModel.Web; using System.Text; using System.Web.Security; namespace GistackWAPService { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。 // 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs,然后开始调试。 public class WapService : IWapService { private string authSiteEndPoint = "https://cloudd-zn.zncloud.com:30071"; private string userName = "247638969@qq.com"; private string password = "Esri@123"; private WAPTenantContext wapContext { get; set; } public string getToken() { ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(delegate { return true; }); return GetAspAuthToken(this.authSiteEndPoint,this.userName,this.password); } public IEnumerable<Plan> GetPlans() { if(this.CheckAuthorization()) return wapContext.GetWAPPlansForTenant(); else return null; } public IEnumerable<Subscription> GetWAPSubscriptions() { if (this.CheckAuthorization()) return wapContext.GetWAPSubscriptionForTenant(); else return null; } public IEnumerable<Quota> GetQuotasForSubscription(string subscriptionid) { if (this.CheckAuthorization()) return wapContext.GetWAPQuotaForSubscription(subscriptionid); else return null; } public IEnumerable<VMTemplate> GetWAPVMTemplates(string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); return wapContext.GetVMTemplate(); } else return null; } public IEnumerable<VirtualMachine> GetVirtualMachines(string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); return wapContext.GetVirtualMachine(); } else return null; } public VirtualMachine GetVirtualMachine(string subscriptionid, string vmname) { IEnumerable<VirtualMachine> vms = this.GetVirtualMachines(subscriptionid); if (vms != null && vms.Count() > 0) { IEnumerable<VirtualMachine> result = vms.Where(v => v.name.Contains(vmname)); if (result != null && result.Count() > 0) return result.ToList().First(); } return null; } public IEnumerable<Cloud> GetWAPClouds(string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); return wapContext.GetCloud(); } else return null; } public IEnumerable<VMNetwork> GetWAPNetworks(string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); return wapContext.GetVMNetworks(); } else return null; } public Result CreateVirtualMachine(VirtualMachine vm, string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); IEnumerable<Cloud> clouds = wapContext.GetCloud(); if (clouds != null) { List<Cloud>listClouds = clouds.ToList(); if (listClouds.Count > 0 && listClouds[0] != null) { try { wapContext.CreateVM(vm.name, listClouds[0].name, vm.vmTemplate); return new Result("true",null); } catch (Exception ex) { return new Result("false", ex.Message); } } } } return new Result("false", "login deny"); } public Result DeleteVirtualMachine(string guid, string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); try { Guid g = new Guid(guid); wapContext.DeleteVM(g); return new Result("true", null); } catch (Exception ex) { return new Result("false", ex.Message); } } else return new Result("false", "login deny"); } public Result StopVirtualMachine(string guid, string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); try { Guid g = new Guid(guid); wapContext.StopVM(g); return new Result("true", null); } catch (Exception ex) { return new Result("false", ex.Message); } } else return new Result("false", "login deny"); } public Result StartVirtualMachine(string guid, string subscriptionid) { if (this.CheckAuthorization()) { wapContext.GetVMMContextForSubscription(subscriptionid); try { Guid g = new Guid(guid); wapContext.StartVM(g); return new Result("true", null); } catch (Exception ex) { return new Result("false", ex.Message); } } else return new Result("false", "login deny"); } public Login login(Login model) { string msg = string.Empty; try { WAPTenantContext wapContext = new WAPTenantContext(); wapContext.SetWAPAuthContext(ConfigurationManager.AppSettings["WAPADAuthServer"], ConfigurationManager.AppSettings["WAPASPAuthServer"]); model.TenantAuthType = WAPWrapper.AuthType.ASPAuth; model = wapContext.CheckWAPUser(model); if (model.IsValidUser) { LoginList.Instance.InsertLoginRecord(model); } } catch (Exception ex) { msg = ex.Message; return null; } return model; } private Login CheckUser(Login model) { string msg = string.Empty; try { wapContext = new WAPTenantContext(); wapContext.SetWAPAuthContext(ConfigurationManager.AppSettings["WAPADAuthServer"], ConfigurationManager.AppSettings["WAPASPAuthServer"]); model.TenantAuthType = WAPWrapper.AuthType.ASPAuth; model = wapContext.CheckWAPUser(model); } catch (Exception ex) { msg = ex.Message; throw; } return model; } private bool CheckAuthorization() { var ctx = WebOperationContext.Current; var auth = ctx.IncomingRequest.Headers[HttpRequestHeader.Authorization]; if (!string.IsNullOrEmpty(auth)) { var username = auth.Substring(0, auth.IndexOf("/")); var password = auth.Remove(0, auth.IndexOf("/")+1); wapContext = new WAPTenantContext(); wapContext.SetWAPAuthContext(ConfigurationManager.AppSettings["WAPADAuthServer"], ConfigurationManager.AppSettings["WAPASPAuthServer"]); Login model = new Login(); model.UserName = username; model.Password = password; model.TenantAuthType = WAPWrapper.AuthType.ASPAuth; model = wapContext.CheckWAPUser(model); if (model.IsValidUser) return true; } ctx.OutgoingResponse.StatusCode = HttpStatusCode.MethodNotAllowed; return false; } private string GetAspAuthToken(string authSiteEndPoint, string userName, string password) { var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed")); var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential); identityProviderBinding.Security.Message.EstablishSecurityContext = false; identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint) { TrustVersion = TrustVersion.WSTrust13, }; //This line is only if we're using self-signed certs in the installation trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None }; trustChannelFactory.Credentials.SupportInteractive = false; trustChannelFactory.Credentials.UserName.UserName = userName; trustChannelFactory.Credentials.UserName.Password = password; var channel = trustChannelFactory.CreateChannel(); var rst = new RequestSecurityToken(RequestTypes.Issue) { AppliesTo = new EndpointReference("http://azureservices/TenantSite"), TokenType = "urn:ietf:params:oauth:token-type:jwt", KeyType = KeyTypes.Bearer, }; RequestSecurityTokenResponse rstr = null; SecurityToken token = null; token = channel.Issue(rst, out rstr); var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText; var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString)); return jwtString; } } }
using UnityEngine; using System.Collections; public class Loader : MonoBehaviour { public GameObject gameController; private GameController gc; // Use this for initialization void Awake () { gc = GameController.gc; if (gc == null) Instantiate (gameController); } } //good luck!
using System; using CarDealer.Data; using CarDealer.Models.EntityModels; namespace CarDealer.Services { public class Service { private CarDealerContext context; protected Service() { this.context = new CarDealerContext(); } protected CarDealerContext Context => this.context; protected void AddLog(int userId, OperationLog operation, string table) { User user = this.Context.Users.Find(userId); Log log = new Log() { User = user, ModifiedAt = DateTime.Now, ModifiedTableName = table, Operation = operation }; this.Context.Logs.Add(log); this.Context.SaveChanges(); } } }
using mec.Model.Entities; using mec.Model.Interfaces; using mec.Model.Orders; using mec.Database.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Activation; using Oracle.ManagedDataAccess.Client; using mec.Model.Plans; namespace MEC.Service.MESResource { // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼、svc 和組態檔中的類別名稱 "Order"。 // 注意: 若要啟動 WCF 測試用戶端以便測試此服務,請在 [方案總管] 中選取 Order.svc 或 Order.svc.cs,然後開始偵錯。 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Order : IOrder { private string connectName = "mes"; public string GetString() { try { //string value = "null"; //OracleConnection conn = new OracleConnection("Data Source=192.168.192.213/TESTDB.more.com.tw;User ID=MES;Password=MES123"); //conn.Open(); //Oracle.ManagedDataAccess.Client.OracleCommand comm = new Oracle.ManagedDataAccess.Client.OracleCommand(" select * from s_bins", conn); //Oracle.ManagedDataAccess.Client.OracleDataReader dr = comm.ExecuteReader(); ////conn.Open(); //while (dr.Read()) //{ // value = dr["ID"].ToString(); //} //dr.Close(); //conn.Close(); //return value; using (var db = new mec.Database.OracleDbContext(this.connectName)) { var q = from a in db.Bins select a; if (q.Any()) { return q.FirstOrDefault().C_ITEM; } } return this.connectName; } catch(Exception e) { return e.Message; } } public IEnumerable<FlowOrderViewModel> GetFlowOrders(FlowOrderParam param) { #region mark /* if (string.IsNullOrEmpty(param.OrgCode) == true) { return null; } if (string.IsNullOrEmpty(param.WorkNumber)) { return null; } using (var db = new mec.Database.OracleDbContext(this.connectName)) { var q = from a in db.FlowCards join b in db.Materials on a.C_INVCODE equals b.C_MATERIAL_NO where a.C_WORK_ORDER == param.WorkNumber.ToUpper() && b.ORG_CODE == param.OrgCode && a.I_CURR_QTY > 0 select new FlowOrderViewModel { WorkNumber = a.C_WORK_ORDER, LotNo = a.C_LOT_NO, MaterialCode = a.C_INVCODE, MaterialName = b.C_MATERIAL_NAME, InputQty = a.I_INPUT_QTY.HasValue == false ? 0 : a.I_INPUT_QTY.Value, CurrentQty = a.I_CURR_QTY.HasValue == false ? 0 : a.I_CURR_QTY.Value, PackingQty = a.PACKINGNUM.HasValue == false ? 0 : a.PACKINGNUM.Value, DownTime = a.D_DOWN.Value, Status = a.C_STATUS, CurrentProcess = a.C_CURR_PROC, PrevProcess = a.C_PREV_PROC }; if (q.Any()) { var o = q.ToList(); //取得 工單號 foreach (var b in o) { b.PartNumber = b.MaterialName.GetPartNumber(); b.ProductCode = b.DownTime.GetProductCode(b.WorkNumber); } return o; } } return null;*/ #endregion var orders = getFlowCards(param); if (orders != null && orders.Count() > 0) { foreach (var o in orders) { o.PartNumber = o.MaterialName.GetPartNumber(); o.ProductCode = o.DownTime.Value.GetProductCode(o.WorkNumber); } } return orders; } public IEnumerable<FlowOrderViewModel> GetFlowOrderForPrint(FlowOrderParam param) { var cards = getFlowCards(param); if (cards == null && cards.Count() <= 0) { return cards; } var w = getWork(param.WorkNumber); var routes = getRoutes(param.OrgCode, w.C_ROUTE_NO, w.I_ROUTE_VERSION); if (w != null) { foreach (var c in cards) { c.StartTime = w.D_EXPECT_START; c.EndTime = w.D_EXPECT_END; c.WorkNumber = w.C_WO_CODE; c.WorkQty = w.I_PLAN_NUM; c.Routes = routes; } } return cards.OrderBy(p=>p.LotNo); } private IEnumerable<FlowOrderViewModel> getFlowCards(FlowOrderParam param) { if (string.IsNullOrEmpty(param.OrgCode) == true) { return null; } if (string.IsNullOrEmpty(param.WorkNumber)) { return null; } using (var db = new mec.Database.OracleDbContext(this.connectName)) { var q = from a in db.FlowCards join b in db.Materials on a.C_INVCODE equals b.C_MATERIAL_NO where a.C_WORK_ORDER == param.WorkNumber.ToUpper() && b.ORG_CODE == param.OrgCode && a.I_CURR_QTY > 0 select new FlowOrderViewModel { WorkNumber = a.C_WORK_ORDER, LotNo = a.C_LOT_NO, MaterialCode = a.C_INVCODE, MaterialName = b.C_MATERIAL_NAME, InputQty = a.I_INPUT_QTY.HasValue == false ? 0 : a.I_INPUT_QTY.Value, CurrentQty = a.I_CURR_QTY.HasValue == false ? 0 : a.I_CURR_QTY.Value, PackingQty = a.PACKINGNUM.HasValue == false ? 0 : a.PACKINGNUM.Value, DownTime = a.D_DOWN.Value, Status = a.C_STATUS, CurrentProcess = a.C_CURR_PROC, PrevProcess = a.C_PREV_PROC }; if (q.Any()) { return q.ToList(); } } return null; } private SubComponent getWork(string workNo) { if (string.IsNullOrEmpty(workNo) == true) { return null; } using (var db = new mec.Database.OracleDbContext(this.connectName)) { var q = from a in db.SubComponents where a.C_WO_CODE == workNo.ToUpper() select a; if (q.Any()) { return q.FirstOrDefault(); } return null; } } private List<string> getRoutes(string orgCode, string routeNo, decimal? version) { List<string> routes = new List<string>(); if (string.IsNullOrEmpty(routeNo) == true) { return routes; } if (version.HasValue == false) { return routes; } using (var db = new mec.Database.OracleDbContext(this.connectName)) { var q = from a in db.RouteMains join b in db.RouteDetails on a.ID equals b.I_PID where a.C_ROUTE_NO == routeNo && a.I_ROUTE_VERSION == version && a.ORG_CODE == orgCode select b; if (q.Any()) { var o = q.ToList().OrderBy(p=>p.I_SEQ); foreach(var r in o) { routes.Add(string.Format("{0}.{1}", r.I_SEQ, r.C_PROCESS_NO)); } } } return routes; } } }
using System; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.Configuration; using Agencia_Datos_Repositorio; using Agencia_Datos_Entidades; namespace Agencia_Dominio.App_Start { /// <summary> /// Specifies the Unity configuration for the main container. /// </summary> public class UnityConfig { #region Unity Container private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// <summary> /// Gets the configured Unity container. /// </summary> public static IUnityContainer GetConfiguredContainer() { return container.Value; } #endregion /// <summary>Registers the type mappings with the Unity container.</summary> /// <param name="container">The unity container to configure.</param> /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks> public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. // container.LoadConfiguration(); // TODO: Register your types here // container.RegisterType<IProductRepository, ProductRepository>(); container.RegisterType<IRepositorio<Cliente>, Repositorio<Cliente>>(); container.RegisterType<IRepositorio<Contrato>, Repositorio<Contrato>>(); container.RegisterType<IRepositorio<Control_Electrodomestico_Empleado>, Repositorio<Control_Electrodomestico_Empleado>>(); container.RegisterType<IRepositorio<Control_Electrodomesticos>, Repositorio<Control_Electrodomesticos>>(); container.RegisterType<IRepositorio<Doc_Identidad>, Repositorio<Doc_Identidad>>(); container.RegisterType<IRepositorio<Documentos>, Repositorio<Documentos>>(); container.RegisterType<IRepositorio<D_DocumentoxEmpleado>, Repositorio<D_DocumentoxEmpleado>>(); container.RegisterType<IRepositorio<Empleado>, Repositorio<Empleado>>(); container.RegisterType<IRepositorio<Empleado_Detalle>, Repositorio<Empleado_Detalle>>(); container.RegisterType<IRepositorio<Estudios>, Repositorio<Estudios>>(); container.RegisterType<IRepositorio<HabilidadEmpleado>, Repositorio<HabilidadEmpleado>>(); container.RegisterType<IRepositorio<Habilidades>, Repositorio<Habilidades>>(); container.RegisterType<IRepositorio<Idiomas>, Repositorio<Idiomas>>(); container.RegisterType<IRepositorio<MenuEmpleado>, Repositorio<MenuEmpleado>>(); container.RegisterType<IRepositorio<Menus>, Repositorio<Menus>>(); container.RegisterType<IRepositorio<Religion>, Repositorio<Religion>>(); container.RegisterType<IRepositorio<ServicioEmpleado>, Repositorio<ServicioEmpleado>>(); container.RegisterType<IRepositorio<Servicios>, Repositorio<Servicios>>(); container.RegisterType<IRepositorio<TipoUsuario>, Repositorio<TipoUsuario>>(); container.RegisterType<IRepositorio<Ubigeo>, Repositorio<Ubigeo>>(); } } }
using System.Collections.Generic; using System.IO; using ManyConsole; namespace TsFromCsGenerator { class GenerateInterfacesCommand : ConsoleCommand { private readonly ICsToTsConverter _converter; private readonly List<string> _fileLocations = new List<string>(); private string _outLocation; private bool _exported; private bool _prefixInterfaces; public GenerateInterfacesCommand(ICsToTsConverter converter) { _converter = converter; IsCommand("Interfaces", "Generate TS interface from CS model"); HasRequiredOption("f|file=", "The {path} of the CS file to transform (Multiple possible)", p => _fileLocations.Add(p)); HasRequiredOption("o|out=", "The {path} of output TS file", p => _outLocation = p); HasOption("p|prefixinterface", "Output interface type names with a I-prefix", p => _prefixInterfaces = p != null); HasOption("e|export", "The generated TS type should be exported", p => _exported = p != null); } /// <inheritdoc /> public override int Run(string[] remainingArguments) { string tsCode = ""; foreach (string location in _fileLocations) { string code = File.ReadAllText(location); tsCode += _converter.Convert(code, false, _exported, _prefixInterfaces); } File.WriteAllText(_outLocation, tsCode); return 0; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; namespace RequestMonitor.Filters { public class GlobalExceptionHandler : IExceptionFilter { ILogger logger; public GlobalExceptionHandler(ILoggerFactory loggerFactor) { logger = loggerFactor.CreateLogger<GlobalExceptionHandler>(); } //Log exceptions public void OnException(ExceptionContext context) { HttpResponse response = context.HttpContext.Response; response.StatusCode = 500; response.ContentType = "application/json"; logger.LogCritical(context.Exception.ToString()); context.Result = new ObjectResult(new { Message = "Internal Server Error" }); } } }
namespace UnityAtoms.BaseAtoms { /// <summary> /// Action of type `int`. Inherits from `AtomAction&lt;int&gt;`. /// </summary> [EditorIcon("atom-icon-purple")] public abstract class IntAction : AtomAction<int> { } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; namespace _05.ChangeTownNamesCasing { class ChangeTownNamesCasing { static void Main() { string countryName = Console.ReadLine().Trim(); string connStr = @"Server=.\SQLEXPRESS;database=MinionsDB;Trusted_Connection=true;"; using (SqlConnection connection = new SqlConnection(connStr)) { connection.Open(); int countTowns = CheckTownsExistAndReturnCount(countryName, connection); if (countTowns == 0) { Console.WriteLine("No town names were affected."); return; } string sql = "Update Towns set Name = UPPER(Name) where country = @countryName"; SqlCommand sqlCommand = new SqlCommand(sql, connection); sqlCommand.Parameters.AddWithValue("@countryName", countryName); sqlCommand.ExecuteNonQuery(); Console.WriteLine($"{countTowns} town names were affected."); sql = "Select t.[Name] from Towns as t where t.country = @countryName"; sqlCommand.CommandText = sql; SqlDataReader reader = sqlCommand.ExecuteReader(); List<string> townNamesStr = new List<string>(); while (reader.Read()) { //Console.Write("["); for (int i = 0; i < reader.FieldCount; i++) { townNamesStr.Add(reader[i].ToString()); } } reader.Close(); Console.WriteLine($"[{string.Join<string>(", ", townNamesStr)}]"); } } private static int CheckTownsExistAndReturnCount(string countryName, SqlConnection connection) { string sql = "Select count(1) from Towns as t where t.Country = @name"; SqlCommand sqlCommand = new SqlCommand(sql, connection); sqlCommand.Parameters.AddWithValue("@name", countryName); return int.Parse(sqlCommand.ExecuteScalar().ToString()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Drawing; using System.Text; using System.Windows.Forms; namespace NetRuntimeChanger { public partial class Form1 : Form { public Form1() { InitializeComponent(); comboBoxVersion.SelectedIndex = 0; comboBoxLanguage.SelectedIndex = 0; } private void buttonStart_Click(object sender, EventArgs e) { string projectExtension = ""; if(comboBoxLanguage.SelectedIndex ==0) projectExtension = "*.csproj"; else projectExtension = "*.vbproj"; textBoxLog.Text = ""; string netVersion = GetSelectedNetVersion(); if (!Directory.Exists(textBoxFolder.Text)) { MessageBox.Show("Directory not exists", "Doooh", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //change projects string[] files = Directory.GetFiles(textBoxFolder.Text, projectExtension, SearchOption.AllDirectories); foreach (string file in files) { textBoxLog.AppendText("Change : " + System.IO.Path.GetFileName(file) + "\r\n"); string fileContent = File.ReadAllText(file); ChangeNetVersionEntry(ref fileContent, netVersion); ChangeToolsVersionEntry(ref fileContent, netVersion); ChangeKeyFile(ref fileContent, System.IO.Path.GetDirectoryName(file), System.IO.Path.GetFileNameWithoutExtension (file), netVersion); File.Delete(file); File.WriteAllText(file, fileContent, Encoding.UTF8); } //change solution string[] slnFiles = Directory.GetFiles(textBoxFolder.Text, "*.sln", SearchOption.AllDirectories); foreach (string slnFile in slnFiles) { textBoxLog.AppendText("Change : " + System.IO.Path.GetFileName(slnFile) + "\r\n"); string fileContent = File.ReadAllText(slnFile); ChangeFormatVersion(ref fileContent, netVersion); ChangeToolCode(ref fileContent, netVersion); File.Delete(slnFile); File.WriteAllText(slnFile, fileContent, Encoding.UTF8); } } private void ChangeKeyFile(ref string fileContent, string currentFolder, string name, string netVersion) { if (!checkBoxChangeKeyFiles.Checked) return; int position1 = fileContent.IndexOf("<AssemblyOriginatorKeyFile>"); if (position1 < 0) { textBoxLog.AppendText("\t\tKeyFile Entry not found:" + name + "\r\n"); return; } int position2 = fileContent.IndexOf("</AssemblyOriginatorKeyFile>", position1); string keyFile = fileContent.Substring(position1 + "<AssemblyOriginatorKeyFile>".Length, position2 - (position1 + "<AssemblyOriginatorKeyFile>".Length)); string[] arr = keyFile.Split(new string[] {"_"},StringSplitOptions.RemoveEmptyEntries); string newKeyFile = arr[0] + "_v" + netVersion + ".snk"; string newLine = "<AssemblyOriginatorKeyFile>" + newKeyFile + "</AssemblyOriginatorKeyFile>"; string net1 = "<AssemblyOriginatorKeyFile>" + keyFile + "</AssemblyOriginatorKeyFile>"; fileContent = fileContent.Replace(net1, newLine); string sourceFile = System.IO.Path.Combine(textBoxKeyFilesRootFolder.Text, netVersion); sourceFile = System.IO.Path.Combine(sourceFile, newKeyFile); string destFile = System.IO.Path.Combine(currentFolder, newKeyFile); if(!System.IO.File.Exists(destFile)) System.IO.File.Copy(sourceFile, destFile); } private void ChangeToolCode(ref string fileContent, string netVersion) { string replacedString = ""; if (netVersion == "4.0") { if (comboBoxLanguage.SelectedIndex == 0) replacedString = "# Visual C# Express 2010"; else replacedString = "# Visual Basic Express 2010"; } else replacedString = "# Visual Studio 2008"; string tools1 = "# Visual C# Express 2010"; int position = fileContent.IndexOf(tools1); if (position > -1) { fileContent = fileContent.Replace(tools1, replacedString); return; } string tools2 = "# Visual Studio 2008"; position = fileContent.IndexOf(tools2); if (position > -1) { fileContent = fileContent.Replace(tools2, replacedString); return; } } private void ChangeFormatVersion(ref string fileContent, string netVersion) { string replacedString = ""; if (netVersion.StartsWith("4")) replacedString = "Format Version 11.00"; else replacedString = "Format Version 10.00"; string tools1 = "Format Version 10.00"; int position = fileContent.IndexOf(tools1); if (position > -1) { fileContent = fileContent.Replace(tools1, replacedString); return; } string tools2 = "Format Version 11.00"; position = fileContent.IndexOf(tools2); if (position > -1) { fileContent = fileContent.Replace(tools2, replacedString); return; } } private void ChangeToolsVersionEntry(ref string fileContent, string netVersion) { string replacedString = ""; if (netVersion.StartsWith("4")) replacedString = "ToolsVersion=\"4.0\""; else replacedString = "ToolsVersion=\"3.5\""; string tools1 = "ToolsVersion=\"3.5\""; int position = fileContent.IndexOf(tools1); if (position > -1) { fileContent = fileContent.Replace(tools1, replacedString); return; } string tools2 = "ToolsVersion=\"4.0\""; position = fileContent.IndexOf(tools2); if (position > -1) { fileContent = fileContent.Replace(tools2, replacedString); return; } } private void ChangeNetVersionEntry(ref string fileContent, string netVersion) { string net1 = "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>"; int position = fileContent.IndexOf(net1); if (position > -1) { fileContent = fileContent.Replace(net1, "<TargetFrameworkVersion>v" + netVersion + "</TargetFrameworkVersion>"); return; } string net2 = "<TargetFrameworkVersion>v3.0</TargetFrameworkVersion>"; position = fileContent.IndexOf(net2); if (position > -1) { fileContent = fileContent.Replace(net2, "<TargetFrameworkVersion>v" + netVersion + "</TargetFrameworkVersion>"); return; } string net3 = "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>"; position = fileContent.IndexOf(net3); if (position > -1) { fileContent = fileContent.Replace(net3, "<TargetFrameworkVersion>v" + netVersion + "</TargetFrameworkVersion>"); return; } string net4 = "<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>"; position = fileContent.IndexOf(net4); if (position > -1) { fileContent = fileContent.Replace(net4, "<TargetFrameworkVersion>v" + netVersion + "</TargetFrameworkVersion>"); return; } string net5 = "<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>"; position = fileContent.IndexOf(net5); if (position > -1) { fileContent = fileContent.Replace(net4, "<TargetFrameworkVersion>v" + netVersion + "</TargetFrameworkVersion>"); return; } } private string GetSelectedNetVersion() { switch (comboBoxVersion.SelectedIndex) { case 0: return "2.0"; case 1: return "3.0"; case 2: return "3.5"; case 3: return "4.0"; case 4: return "4.5"; } throw(new Exception("Version not selected.")); } private void buttonChooseFolder_Click(object sender, EventArgs e) { FolderBrowserDialog fdg = new FolderBrowserDialog(); if (DialogResult.OK == fdg.ShowDialog(this)) textBoxFolder.Text = fdg.SelectedPath; } } }
using UnityEngine; public class ColumnMove : MonoBehaviour { private float speed = 0.1F; void Update() { transform.Translate(-speed,0,0); } }
using System; using System.Collections.Generic; using System.Linq; namespace Concept.Linq.Lesson1 { class Main { public void Run() { string[] files = { "fileA.txt", "fileB.txt", "fileC.txt" }; var exceptionDemoQuery = from file in files let n = SomeMethodThatMightThrow(file) select n; try { foreach (var item in exceptionDemoQuery) { Console.WriteLine($"Processing {item}"); } } catch (InvalidOperationException e) { Console.WriteLine(e.Message); } Console.WriteLine("Press any key to exit"); Console.ReadKey(); } string SomeMethodThatMightThrow(string s) { if (s[4] == 'C') { throw new InvalidOperationException(); } return @"C:\newFolder\" + s; } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace KeepTeamAutotests.Pages { public class CommentsTab : PopupPage { [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[2]/div[1]/div/div/input")] private IWebElement lastNameField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div/div/div/div/div[1]/div/div[2]/div/div/div/div/div/input")] private IWebElement commentsField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div/div/div/div/div[1]/div/div[2]/div/div[1]/div/div/textarea")] private IWebElement commentsField1; [FindsBy(How = How.XPath, Using = "/html/body/div[5]/div/div/div/div/section[3]/form/div/div/div/div/div[2]/div/div[2]/div/div/div[1]/span[2]")] private IWebElement commentsField2; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div/div/div/div/div[1]/div/div[2]/div/div[2]/div/div[1]")] private IWebElement saveButton; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[1]/div/div/div[1]/input")] private IWebElement dateField;///html/body/div[3]/div/div/div/div/section/form/div[3]/div[1]/div/div/div[1]/input [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[2]/div/div/input")] private IWebElement placeField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[4]/div[2]/div/div/input")] private IWebElement founderField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[5]/div/div/div/textarea")] private IWebElement descriptionField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[6]/div[1]/div/div/input")] private IWebElement phoneField; [FindsBy(How = How.XPath, Using = ".//*[@id='foundIndependently']")] private IWebElement foundCheckBox; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[4]/div[3]/div/div/div")] private IWebElement skillField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[3]/div/div/input")] private IWebElement minField; [FindsBy(How = How.XPath, Using = "//form[@name = 'applicantsForm']/div[3]/div[4]/div/div/input")] private IWebElement maxField; public CommentsTab(PageManager pageManager) : base(pageManager) { pagename = "commentscandidate"; } internal void addComment(string text) { commentsField.Click(); setTextField(commentsField1, text); saveButton.Click(); } internal string getMessage() { waitSecond(); return getTextField(commentsField2); } /* public void setComments(string name) { setTextField(commentsField, name); } public void setDescriptionField(string description) { setTextField(descriptionField, description); } public string getName() { return getTextField(nameField); } public string getDate() { return getTextField(dateField,""," . 45 лет"); } public string getDescription() { return getTextField(descriptionField); } internal void saveClick() { saveButton.Click(); waitSaveDone(); } internal void setLastNameField(string lastname) { setTextField(lastNameField, lastname); } internal string getLastName() { return getTextField(lastNameField); } internal void setPlaceField(string place) { setTextField(placeField, place); } internal void setDateField(string date) { setDateFieldWithDatePicker(dateField, date); } internal string getPlace() { return getTextField(placeField); } internal void setFounderField(string founder) { setTextField(founderField, founder); } internal string getFounder() { return getTextField(founderField,"Источник: "); } internal string getPhone() { return getTextField(phoneField); } internal void setPhoneField(string phone) { setTextField(phoneField, phone); } internal void setFounderCheckbox(bool found) { setCheckBox(foundCheckBox, found); } internal bool getFound() { return getCheckBox(foundCheckBox); } internal void setSkill(int skill) { setStarsField(skillField, skill); } internal int getSkill() { return getStarsField(skillField); } internal void clearName() { nameField.Clear(); } internal void clearLastname() { lastNameField.Clear(); } internal void clearDateBirthday() { ClearManual(dateField); } internal void clearPlace() { placeField.Clear(); } internal void clearFounder() { founderField.Clear(); } internal void clearDescription() { descriptionField.Clear(); } internal void clearPhone() { phoneField.Clear(); } internal void clearFound() { founderField.Clear(); } internal void clearSkill() { clearStarsField(skillField); } internal void setMinPay(string MinPay) { setTextField(minField, MinPay); } internal void setMaxPay(string MaxPay) { setTextField(maxField, MaxPay); } internal string getMaxPay() { return getTextField(maxField); } internal string getMinPay() { return getTextField(minField); } internal void clearMaxPay() { maxField.Clear(); } internal void clearMinPay() { minField.Clear(); } */ } }
using System; using Breeze.Screens; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Breeze.AssetTypes { //public class ScreenAsset //{ // public int ZIndex { get; set; } = 0; // public FloatRectangle? Clip { get; set; } = null; // public Rectangle? ScissorRect { get; set; } // //public FloatRectangle Position { get; set; } // public virtual void Draw(SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null) // { // throw new NotImplementedException(); // } //} //public class KeyedAsset : ScreenAsset //{ // public string Key { get; set; } // public bool IsDirty { get; set; } // public void Update(KeyedAsset asset, KeyedAsset source) // { // if (!string.IsNullOrWhiteSpace(asset.Key)) // { // (asset as LineListAsset)?.Update(source as LineListAsset); // // (asset as ButtonAsset)?.Update(source as ButtonAsset); // //(asset as RectangleAsset)?.Update(source as RectangleAsset); // //(asset as FontAsset)?.Update(source as FontAsset); // //(asset as PatternAsset)?.Update(source as PatternAsset); // (asset as SinglePixelLineAsset)?.Update(source as SinglePixelLineAsset); // //(asset as BezierLineAsset)?.Update(source as BezierLineAsset); // //(asset as ImageAsset)?.Update(source as ImageAsset); // // (asset as CentredImageAsset)?.Update(source as CentredImageAsset); // //(asset as ContainerAsset)?.Update(source as ContainerAsset); // (asset as BoxShadowAsset)?.Update(source as BoxShadowAsset); // // (asset as ViewportAsset)?.Update(source as ViewportAsset); // asset.Clip = source.Clip; // asset.ScissorRect = source.ScissorRect; // } // } //} //public class KeyedUpdatedAsset : KeyedAsset //{ // public virtual void Update(SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null) // { // throw new NotImplementedException(); // } //} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Threading; namespace chatSrv { class Program { static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; Server srv = new Server(); srv.Run(); } } // класс сервера class Server { int port = 12312; TcpListener listener; List<TcpClient> Clients = new List<TcpClient>(); public Server() { listener = new TcpListener( IPAddress.Any, port); } // запуск сервверра public void Run() { Console.WriteLine(">> waiting for clients"); listener.Start(); while (true) { TcpClient client = listener.AcceptTcpClient(); // записываем клиента в список клиентов Clients.Add(client); // тред (поток) на каждого клиента Thread clientThread = new Thread( new ParameterizedThreadStart( ClientThreadBody ) ); clientThread.Start(client); Console.WriteLine(">> client connected"); } } // тело треда клиента void ClientThreadBody(object Client) { TcpClient CurrentClient = (TcpClient)Client; NetworkStream stream = CurrentClient.GetStream(); // получаем стрим данных SendToAll("Кто-то приконнектился! " + CurrentClient.Client.RemoteEndPoint.ToString()); // пока клиент приконнекченный while(CurrentClient.Connected) { try { if (stream.DataAvailable) // если есть что ловить { byte[] buff = new byte[4096]; int read = stream.Read(buff, 0, 4096); //ловим до 4кб string input = UTF8Encoding.UTF8.GetString(buff,0, read); // всё что поймали пихаем в стринг Console.WriteLine( CurrentClient.Client.RemoteEndPoint.ToString() + ": " + input); SendToAll(CurrentClient.Client.RemoteEndPoint.ToString() + ": " + input); // транслируем на всех месседж } } catch { return; // если ошибки - вырубаем поток } /***/ Thread.Sleep(10); // чтоб поток не сжирал проц } } // трансляция всем public void SendToAll(string data) { byte[] buffer; buffer = UTF8Encoding.UTF8.GetBytes(data); // конвертим стринг в мсассив байтов foreach (TcpClient client in Clients) // перебором клиентов всем отсылаем { try { client.GetStream().Write(buffer, 0, buffer.Length); } catch { lock (Clients) { Clients.Remove(client); } } } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using TravelBuddySite.DAL; using TravelBuddySite.Handlers; using TravelBuddySite.Models; namespace TravelBuddySite.Controllers { public class UserLocationsController : Controller { private MainContext db = new MainContext(); // Finds all the location user have been at, with the location info from locations DB public ActionResult UserLocationsByUser(int id) { string username = GetUsernameByUserId(id); // Checking if user id exists if (username == string.Empty) { throw new HttpException(404,"User was not found."); } ViewData["Username"] = username; // Finds user's locations and adds the specific locations data var UserLocationsList = db.UserLocations.Where(x => x.UserId == id).Join(db.Locations, sc => sc.LocationId, soc => soc.Id, (sc, soc) => new UserLocationJoinResults { location = soc, userLocation = sc }); // Returns all the user location data to view return View(UserLocationsList.ToList()); } // Getting the username for id from database private string GetUsernameByUserId(int id) { try { return db.Users.Find(id).Username; } catch { return String.Empty; } } // Creats the userLocation creation page(for the user) full with his detailed locations public ActionResult CreateByUser(int id) { // Checking if the logged on user sent the request if(Session["logedUserId"].ToString() != id.ToString()) { throw new HttpException(401, "Not autorized request."); } // Creats a UserLocation Objects that holds all the locations in db and the user id UserLocationJoinResults ul = new UserLocationJoinResults(); ul.userLocation = new UserLocation(); ul.userLocation.UserId = id; // Finds all locations in locations table and parsed it for dropdown use ul.AllLocations = db.Locations.Select(r => new SelectListItem { Value = r.Id.ToString(), Text = r.Country + "," + r.City +"," + r.Name, }); return View(ul); } [HttpPost] [ValidateAntiForgeryToken] // adds a new user location to a specific user public ActionResult CreateByUser(UserLocationJoinResults ul) { if (ModelState.IsValid) { // adds the user's location location to DB db.UserLocations.Add(ul.userLocation); db.SaveChanges(); } return RedirectToAction("UserLocationsByUser","UserLocations",new { id = ul.userLocation.UserId }); } // GET: UserLocations/Edit/5 public ActionResult Edit(int? id) { if (id == null) { throw new HttpException(400, "Bad request."); } UserLocation userLocation = db.UserLocations.Find(id); if (userLocation == null) { throw new HttpException(404, "User location not found."); } // Checking if not manager if (!SessionsHandler.IsManager(Session)) { // if not manager, checking if not logged on user if (Session["LogedUserId"].ToString() != userLocation.UserId.ToString()) { throw new HttpException(401, "User not authorized."); } } var userLocationsDetails = db.UserLocations.Where(x => x.Id == id).Include("Location"); var userLocationAndUser = userLocationsDetails.Include("User"); return View(userLocationAndUser.First()); } // POST: UserLocations/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] // Edits user's location public ActionResult Edit([Bind(Include = "Id,UserId,LocationId,VisitCount,IsTarget")] UserLocation userLocation) { if (ModelState.IsValid) { db.Entry(userLocation).State = EntityState.Modified; db.SaveChanges(); if (SessionsHandler.IsManager(Session)) { return RedirectToAction("ManageUsersLocations", "UserLocations"); } else { return RedirectToAction("UserLocationsByUser", new { id = userLocation.UserId }); } } return View(userLocation); } // Delets user's location public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } UserLocation userLocation = db.UserLocations.Find(id); if (userLocation == null) { throw new HttpException(404, "User was not found."); } if (!SessionsHandler.IsManager(Session)) { if (Session["LogedUserId"].ToString() != userLocation.UserId.ToString()) { throw new HttpException(401, "User is not autorized for this action."); } } return View(userLocation); } // POST: UserLocations/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [AllowAnonymous] // Checks if the user wants to delete his location public ActionResult DeleteConfirmed(int id) { UserLocation userLocation = db.UserLocations.Find(id); db.UserLocations.Remove(userLocation); db.SaveChanges(); // if manager did the change, returning to manager page if (SessionsHandler.IsManager(Session)) { return RedirectToAction("ManageUsersLocations"); } return RedirectToAction("UserLocationsByUser",new { id= int.Parse(Session["LogedUserId"].ToString())}); } // The index page for managing the user locations public ActionResult ManageUsersLocations() { if (!SessionsHandler.IsManager(Session)) { throw new HttpException(404, "Page not found."); } var UserLocationsList = db.Users.Include("UserLocations.Location"); return View(UserLocationsList.ToList()); } // Manager create action to create new user location public ActionResult ManagerCreate() { if (!SessionsHandler.IsManager(Session)) { throw new HttpException(404, "Page not found."); } // if model is not valid returning to manager index if (!ModelState.IsValid) { return RedirectToAction("Index", "Manager"); } var Users = db.Users; var Locations = db.Locations; List<SelectListItem> users = new List<SelectListItem>(); List<SelectListItem> locations = new List<SelectListItem>(); // Creating users list for dropdown list in view foreach (var user in Users) { users.Add(new SelectListItem { Value = user.Id.ToString(), Text = user.Id + ". " + user.FirstName + " " + user.LastName }); } // Creating locations list for dropdown list in view foreach (var loc in Locations) { locations.Add(new SelectListItem { Value = loc.Id.ToString(), Text = loc.Id + ". " + loc.Country + " - " + loc.City }); } ViewBag.UsersList = users; ViewBag.LocsList = locations; return View(); } [HttpPost] public ActionResult ManagerCreateNewUserLocation() { var userLocs = db.UserLocations; int UserID = 0; int locID = 0; //if request is wrong try { UserID = int.Parse(Request["UsersList"].ToString()); locID = int.Parse(Request["LocsList"].ToString()); } catch { throw new HttpException(400, "Bad request sent to server"); } bool isTarget = false; int visitCount = int.Parse(Request["VisitCount"].ToString()); if (Request["IsTarget"].ToString().Contains("true")) { isTarget = true; } UserLocation ul = new UserLocation(); ul.UserId = UserID; ul.LocationId = locID; ul.IsTarget = isTarget; ul.VisitCount = visitCount; db.UserLocations.Add(ul); db.SaveChanges(); return RedirectToAction("ManageUsersLocations","UserLocations"); } // Displaying user location details for manager public ActionResult ManagerDetails(int? id) { if (!SessionsHandler.IsManager(Session)) { throw new HttpException(404, "Page not found"); } if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } UserLocation userLocation = db.UserLocations.Find(id); if (userLocation == null) { throw new HttpException(404, "User location not found."); } var userLocationsDetails = db.UserLocations.Where(x => x.Id == id).Include("Location"); var userLocationAndUser = userLocationsDetails.Include("User"); return View(userLocationAndUser); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using Hayaa.BaseModel; using Hayaa.BaseModel.Service; using System; using System.Collections.Generic; using System.Text; namespace Hayaa.Security.Service { public interface AppGrantService : IBaseService<AppGrant, AppGrantSearchPamater> { /// <summary> /// 对App进行授权 /// </summary> /// <param name="appId">被授权App的Id</param> /// <param name="authority">被授权权限</param> /// <returns></returns> FunctionOpenResult<bool> Grant(int appId, Dictionary<int, List<int>> authority); } }
using SecureNetRestApiSDK.Api.Models; using SNET.Core; namespace SecureNetRestApiSDK.Api.Requests { /// <summary> /// Request class used for allowing a previously authorized transaction to be captured for settlement. /// </summary> public class PriorAuthCaptureRequest : SecureNetRequest { #region Properties /// <summary> /// Identifier of the previously authorized transaction to be captured. /// </summary> public int? TransactionId { get; set; } /// <summary> /// Contains developer Id and version information related to the integration. /// </summary> public DeveloperApplication DeveloperApplication { get; set; } /// <summary> /// Final amount of the transaction. Used in cases where the transaction amount needs to be modified after the original authorization. /// </summary> public decimal Amount { get; set; } /// <summary> /// Additional data to assist in reporting, ecommerce or moto transactions, and level 2 or level 3 processing. Includes user-defined fields and invoice-related information. /// If a gratuity is to be added to the previously authorized amount, it can be sent in the serviceData object field. /// </summary> public ExtendedInformation ExtendedInformation { get; set; } #endregion #region Methods public override string GetUri() { return "api/Payments/Capture"; } public override HttpMethodEnum GetMethod() { return HttpMethodEnum.POST; } #endregion } }
using Exiled.API.Features; using Exiled.Events.EventArgs; using UnityEngine; namespace CustomEscape { class EventHandlers { CustomEscapePlugin Plugin; public EventHandlers(CustomEscapePlugin plugin) { Plugin = plugin; } public void OnWaitingForPlayers() { GameObject escape = new GameObject("CustomEscapeTrigger"); BoxCollider collider = escape.AddComponent<BoxCollider>(); escape.AddComponent<SEscapeAnyClass>(); collider.transform.localScale = new Vector3(4.5f, 6, 4.5f); collider.isTrigger = true; escape.layer = 8; escape.transform.position = new Vector3(169.8f, 986, 23.1f); Escape.radius = 0; } public void OnEscaping(EscapingEventArgs ev) { ev.IsAllowed = false; } } }
using System; using CouponMerchant.Data; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; [assembly: HostingStartup(typeof(CouponMerchant.Areas.Identity.IdentityHostingStartup))] namespace CouponMerchant.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { }); } } }
using UnityEditor; using UnityEngine; using System.Collections; // Custom Editor using SerializedProperties. // Automatic handling of multi-object editing, undo, and Prefab overrides. [CustomEditor(typeof(TilingSegmentBendingScript))] [CanEditMultipleObjects] public class TilingSegmentBendingScriptEditor : Editor { // SerializedProperty cellSize; SerializedProperty oppositeCorner; SerializedProperty startMagnitude; SerializedProperty targetMagnitude; SerializedProperty segmentPrefab; void OnEnable() { // Setup the SerializedProperties. // cellSize = serializedObject.FindProperty("CellSize"); oppositeCorner = serializedObject.FindProperty("Target"); startMagnitude = serializedObject.FindProperty("StartMagnitude"); targetMagnitude = serializedObject.FindProperty("TargetMagnitude"); segmentPrefab = serializedObject.FindProperty("Segment"); } private void OnSceneGUI() { TilingSegmentBendingScript segmentBendingScript = target as TilingSegmentBendingScript; Handles.color = Color.white; // TODO: handles for end of each segment // TODO: entries for each segment with options for if the curve is quadratic, cubic, uses only angle from previous segment, etc. foreach (var item in segmentBendingScript.segments) { Vector3 p0l = item.Item2.RearLeftBone.position; Vector3 p0r = item.Item2.RearRightBone.position; Vector3 lastBone = p0l; foreach (var bone in item.Item2.LeftBones) { // TODO: apply transform to line positions Handles.DrawLine(lastBone, bone.position); } lastBone = p0r; foreach (var bone in item.Item2.RightBones) { // TODO: apply transform to line positions Handles.DrawLine(lastBone, bone.position); } EditorGUI.BeginChangeCheck(); Transform handleTransform = item.Item2.RearLeftBone; Quaternion handleRotation = item.Item2.RearLeftBone.rotation; p0l = Handles.DoPositionHandle(p0l, handleRotation); if (EditorGUI.EndChangeCheck()) { // Undo.RecordObject(line, "Move Point"); // EditorUtility.SetDirty(line); item.Item2.RearLeftBone.position = handleTransform.InverseTransformPoint(p0l); } Vector3 p1l = item.Item2.FrontLeftBone.position; handleTransform = item.Item2.FrontLeftBone; handleRotation = item.Item2.FrontLeftBone.rotation; EditorGUI.BeginChangeCheck(); p1l = Handles.DoPositionHandle(p1l, handleRotation); if (EditorGUI.EndChangeCheck()) { // Undo.RecordObject(line, "Move Point"); // EditorUtility.SetDirty(line); // line.p1 = handleTransform.InverseTransformPoint(p1l); item.Item2.FrontLeftBone.position = handleTransform.InverseTransformPoint(p1l); } } } public override void OnInspectorGUI() { // Update the serializedProperty - always do this in the beginning of OnInspectorGUI. serializedObject.Update(); // oppositeCorner = serializedObject.FindProperty("OppositeCorner"); // cellPrefab = serializedObject.FindProperty("CellPrefab"); TilingSegmentBendingScript tilingBender = (TilingSegmentBendingScript)target; // Show the custom GUI controls. // EditorGUILayout.Slider(cellSize, 0, 100, new GUIContent("Cell Size")); // tilingBender.CellSize = EditorGUILayout.Slider(tilingBender.CellSize, 0.01f, 30); // Only show the damage progress bar if all the objects have the same damage value: // if (!cellSize.hasMultipleDifferentValues) // ProgressBar(cellSize.floatValue / 100.0f, "Cell Size"); EditorGUILayout.PropertyField(oppositeCorner, new GUIContent("Opposite Corner")); EditorGUILayout.PropertyField(startMagnitude, new GUIContent("Start Magnitude")); EditorGUILayout.PropertyField(targetMagnitude, new GUIContent("End Magnitude")); EditorGUILayout.PropertyField(segmentPrefab, new GUIContent("Cell")); // GUILayout.Label("Cells: " + tilingBender.CellCount); if (GUILayout.Button("Clear grid")) { // tilingBender.ClearCells(); } if (GUILayout.Button("Update grid")) { // tilingBender.UpdateCells(); } // TODO: toggle for checking collision on cell locations, with dynamically hidden settings // tilingBender.CheckCollision = EditorGUILayout.Toggle("Collision", tilingBender.CheckCollision); // if(gridUpdater.CheckCollision){ // gridUpdater.CollisionMask= EditorGUILayout.MaskField("",gridUpdater.CollisionMask.value); // } // tilingBender.PrintDebug = EditorGUILayout.Toggle("Print debug", tilingBender.PrintDebug); // Apply changes to the serializedProperty - always do this in the end of OnInspectorGUI. serializedObject.ApplyModifiedProperties(); } // Custom GUILayout progress bar. void ProgressBar(float value, string label) { // Get a rect for the progress bar using the same margins as a textfield: Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField"); EditorGUI.ProgressBar(rect, value, label); EditorGUILayout.Space(); } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Plotliner.Entities { class ColorChanger { Color[,] colors = { { Color.Blue, Color.Red, Color.Black }, { Color.Brown, Color.Green, Color.Yellow }, {Color.DarkBlue, Color.Maroon, Color.DarkGreen }}; int size = 150; int margin; int boxSize; Texture2D rect; TextBox box; bool enabled; Point colorPos; public ColorChanger(Game1 gameRef) { rect = new Texture2D(gameRef.GraphicsDevice, 1, 1); rect.SetData(new[] { Color.White }); margin = size / 15; boxSize = size / 4; } public void draw(SpriteBatch spriteBatch) { colorPos = new Point(box.Position.X + box.Size.X + 15, box.Position.Y + (box.Size.Y / 2) - (size / 2)); spriteBatch.Draw(rect, new Rectangle(colorPos.X, colorPos.Y, size, size), Color.Black); for(int x = 1; x <= 3; x++) { for(int y = 1; y <= 3; y++) { spriteBatch.Draw(rect, new Rectangle(colorPos.X + (margin * x) + (boxSize * (x - 1)), colorPos.Y + (margin * y) + (boxSize * (y - 1)), boxSize, boxSize), colors[x - 1, y - 1]); } } } public Color checkClicked(Point mousePos) { if(new Rectangle(colorPos, new Point(size, size)).Contains(mousePos)) { for(int x = 1; x <= 3; x++) { for(int y = 1; y <= 3; y++) { if(new Rectangle(colorPos.X + (margin * x) + (boxSize * (x - 1)), colorPos.Y + (margin * y) + (boxSize * (y - 1)), boxSize, boxSize).Contains(mousePos)) { return colors[x - 1, y - 1]; } } } } return Color.Transparent; } public void enable(TextBox box) { this.box = box; enabled = true; } public void disable() { box = null; enabled = false; } public bool Enabled { get { return enabled; } } public TextBox Box { get { return box; } } } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; [CreateAssetMenu ( menuName = "Third Person Synty Character/Weapons/New Weapon" )] public class WeaponData : ScriptableObject { public enum WeaponType { Pistol, Rifle } public enum FireType { Single, Burst, Auto } public string weaponName; [Space] public WeaponType weaponType = WeaponType.Pistol; public HumanBodyBones activeBodyPart = HumanBodyBones.RightHand; public TransformData ikData; public TransformData inVehicleIkData; [Space] public TransformData holsterData; public HumanBodyBones holsterBodyPart = HumanBodyBones.RightHand; [Space] public float fireRate = 60.0f; // Rounds per minute public float burstDelay = 60.0f; // Delay Between burst fires. Calculated in Rounds per Minute to keep uniformity in calculations public float reloadTime = 1.2f; public int clipSize = 30; [Space] public float maxDistance; public float maxDamage; public AnimationCurve damageByDistanceFalloff; [Space] public List<FireType> fireTypes = new List<FireType> (); [Space] public AudioClip audioClipFire; public AudioClip audioClipEmptyFire; public AudioClip audioClipReload; public RecoilData recoilData; [Space] public GameObject prefab; public GameObject muzzlePrefab; public Vector3 offsetPosition; public Vector3 offsetRotation; public Vector3 localScale; public Vector3 clipTextLocalPosition; public Vector3 clipTextHolsteredLocalPosition; } #if UNITY_EDITOR public static class CopyComponent { public static Vector3 pos; public static Vector3 rot; public static Vector3 scale; [MenuItem( "Tools/Third Person Synty Character/Copyer/Copy Transform" )] public static void CopyTransform () { pos = Selection.gameObjects[0].GetComponent<Transform> ().localPosition; rot = Selection.gameObjects[0].GetComponent<Transform> ().localEulerAngles; scale = Selection.gameObjects[0].GetComponent<Transform> ().localScale; } [MenuItem ( "Tools/Third Person Synty Character/Copyer/Paste Weapon Transform" )] public static void PasteWeaponTransform () { ((WeaponData)Selection.objects[0]).offsetPosition = pos; ((WeaponData)Selection.objects[0]).offsetRotation = rot; ((WeaponData)Selection.objects[0]).localScale = scale; EditorUtility.SetDirty ( Selection.objects[0] ); AssetDatabase.SaveAssets (); } [MenuItem ( "Tools/Third Person Synty Character/Copyer/Paste Transform Data" )] public static void PasteTransformData () { ((TransformData)Selection.objects[0]).position = pos; ((TransformData)Selection.objects[0]).eulerAngles = rot; ((TransformData)Selection.objects[0]).localScale = scale; EditorUtility.SetDirty ( Selection.objects[0] ); AssetDatabase.SaveAssets (); } } #endif
using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; public class Health : MonoBehaviour { [SerializeField]private int _health; public int HP { get { return _health; } set { _health = value; } } void Update () { Death(); } void Death() { //If player dies go back to main menu if (_health <= 0) { SceneManager.LoadScene("Menu"); } } }