text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FunctionalProgramming.Basics; using FunctionalProgramming.Monad.Outlaws; using FunctionalProgramming.Monad.Transformer; using FunctionalProgramming.Tests.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FunctionalProgramming.Tests.TransformerTests { [TestClass] class TryEnumerableTests { [TestMethod] public void TestTryEnumerable() { var expected = new[] {2, 3, 4, 5, 6}; var initital = new[] {1, 2, 3, 4, 5}; var @try = Try.Attempt(() => initital.AsEnumerable()).ToTryEnumerable(); var temp = (from num in @try select num + 1) .Out(); var result = temp.Match( success: BasicFunctions.Identity, failure: ex => Enumerable.Empty<int>()); Assert.IsTrue(TestUtils.AreEqual(result, expected)); } } }
namespace DeMo.Models.model { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("BinhLuan")] public partial class BinhLuan { [Key] public int MaBL { get; set; } [StringLength(8)] public string MaThongBao { get; set; } [Column(TypeName = "date")] public DateTime NgayBL { get; set; } [StringLength(8)] public string MaPH { get; set; } [StringLength(500)] public string NoiDungBL { get; set; } public virtual PhuHuynh PhuHuynh { get; set; } public virtual ThongBao ThongBao { get; set; } } }
public class Expense { public string Category { get; set; } public decimal Amount { get; set; } public bool HasDocument {get; set; } public System.DateTime day {get; set; } }
using System.Collections; using System.Collections.Generic; public interface Database_IDatabaseConnector { void TestDatabaseConnection(); IEnumerator LoginUser(string login, string password); IEnumerator UpdateScore(int playerId, int worldId, int score); IEnumerator RegisterUser(string login, string password, string repeatedPassword, string email); IEnumerator ChangePassword(string login, string password, string repeatedPassword); IEnumerator RetrievePlayerScores(int playerId); IEnumerator RetrieveTopScores(int top, string login, int worldId); }
using System; using System.Collections.Generic; namespace PizzaBox.Client.Models { public partial class Pizzas { public int? Topping { get; set; } public Guid? Orderid { get; set; } public int Id { get; set; } public virtual Orders Order { get; set; } public virtual Toppings ToppingNavigation { get; set; } } }
 using UnityEngine; public class PlayerMovement : MonoBehaviour { public float speed = 6f; Vector3 movement; Animator anim; Rigidbody playerRigidBody; int floorMask; float camRayLength = 100f; Vector2 direct; void Awake () { floorMask = LayerMask.GetMask ("Floor"); anim = GetComponent<Animator>(); playerRigidBody = GetComponent<Rigidbody>(); } void OnEnable () { EasyJoystick.On_JoystickMove += On_JoystickMove; EasyJoystick.On_JoystickTouchUp += On_JoystickTouchUp; } public void On_JoystickMove (MovingJoystick move) { direct = move.joystickAxis; } public void On_JoystickTouchUp (MovingJoystick move) { direct = Vector2.zero; } void FixedUpdate () { //float h = Input.GetAxisRaw ("Horizontal"); //float v = Input.GetAxisRaw ("Vertical"); Move (direct.x, direct.y); Turning (); Animating (direct.x, direct.y); } void Move (float h, float v) { movement.Set (h, 0f, v); movement = movement.normalized * speed * Time.deltaTime; playerRigidBody.MovePosition (transform.position + movement); } void Turning () { // Ray camRay = Camera.main.ScreenPointToRay (Input.mousePosition); // // RaycastHit floorHit; // // if(Physics.Raycast (camRay, out floorHit, camRayLength, floorMask)) // { // Vector3 playerToMouse = floorHit.point - transform.position; // playerToMouse.y = 0f; // // Quaternion newRotation = Quaternion.LookRotation (playerToMouse); // playerRigidBody.MoveRotation (newRotation); // } Vector3 playerToMouse = new Vector3(direct.x, 0f, direct.y); if(playerToMouse != Vector3.zero) { Quaternion newRotation = Quaternion.LookRotation (playerToMouse); playerRigidBody.MoveRotation (newRotation); } } void Animating (float h, float v) { bool walking = h != 0f || v != 0f; anim.SetBool ("isWalking", walking); } }
using System.Collections.Generic; using Umbraco.Core.Models.PublishedContent; namespace Uintra.Features.CentralFeed.Providers { public interface IFeedContentProvider { IPublishedContent GetOverviewPage(); IEnumerable<IPublishedContent> GetRelatedPages(); } }
//using System.Collections; //using System.Collections.Generic; using UnityEngine; public class TowerRight : MonoBehaviour { public GameManager gm; public TowerLeft left; public TowerMid mid; public Color originRightColor; private void OnMouseDown() { //아무것도 선택 안되어있을 때. if (!gm.isCurrentCheck) { if (gm.stackRight.Count >= 1) { gm.isRightCheck = true; gm.isCurrentCheck = true; originRightColor = gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color; gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color = Color.gray; } else if (gm.stackRight.Count < 1) { //탑이 비어있다는 메시지 gm.StartCoroutine("EmptyError"); } } //자기 자신을 다시 선택했을 때. else if (gm.isCurrentCheck && gm.isRightCheck) { gm.isRightCheck = false; gm.isCurrentCheck = false; gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color = originRightColor; } //다른 탑에서 오른쪽 탑으로 가져올 때. else if (gm.isCurrentCheck && !gm.isRightCheck) { //왼쪽 탑에서 가져올 때. if (gm.isLeftCheck) { //왼쪽 탑이 비어있지 않으면 실행. if (gm.stackLeft.Count >= 1) { //오른쪽 탑이 비어있으면 그냥 가져옴. if (gm.stackRight.Count == 0) { gm.boardCube[gm.stackLeft.Peek() - 1].transform.position = new Vector3(10f, 4.5f, 0); gm.stackRight.Push(gm.stackLeft.Pop()); gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color = left.originLeftColor; } //오른쪽 탑이 무언가 차 있으면 실행. else if (gm.stackRight.Count != 0) { //오른쪽 탑의 끝 원판보다 작은 원판이 들어오면 그냥 가져옴. if (gm.stackRight.Peek() > gm.stackLeft.Peek()) { gm.boardCube[gm.stackLeft.Peek() - 1].transform.position = new Vector3(10f, 4.5f, 0); gm.stackRight.Push(gm.stackLeft.Pop()); gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color = left.originLeftColor; } //더 큰 원판이 들어오면 예외처리. else if (gm.stackRight.Peek() < gm.stackLeft.Peek()) { gm.boardCube[gm.stackLeft.Peek() - 1].GetComponent<Renderer>().material.color = left.originLeftColor; gm.StartCoroutine("OverflowError"); } } } //왼쪽 탑이 비어 있으면 예외처리. else if (gm.stackLeft.Count < 1) { gm.StartCoroutine("EmptyError"); } } //중앙 탑에서 가져올 때. if (gm.isMidCheck) { //중앙 탑이 비어있지 않으면 실행. if (gm.stackMid.Count >= 1) { //오른쪽 탑이 비어있으면 그냥 가져옴. if (gm.stackRight.Count == 0) { gm.boardCube[gm.stackMid.Peek() - 1].transform.position = new Vector3(10f, 4.5f, 0); gm.stackRight.Push(gm.stackMid.Pop()); gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color = mid.originMidColor; } //오른쪽 탑이 무언가 차 있으면 실행. else if (gm.stackRight.Count != 0) { // 탑의 끝 원판보다 작은 원판이 들어오면 그냥 가져옴. if (gm.stackRight.Peek() > gm.stackMid.Peek()) { gm.boardCube[gm.stackMid.Peek() - 1].transform.position = new Vector3(10f, 4.5f, 0); gm.stackRight.Push(gm.stackMid.Pop()); gm.boardCube[gm.stackRight.Peek() - 1].GetComponent<Renderer>().material.color = mid.originMidColor; } //더 큰 원판이 들어오면 예외처리. else if (gm.stackRight.Peek() < gm.stackMid.Peek()) { gm.boardCube[gm.stackMid.Peek() - 1].GetComponent<Renderer>().material.color = mid.originMidColor; gm.StartCoroutine("OverflowError"); } } } //중앙 탑이 비어 있으면 예외처리. else if (gm.stackMid.Count < 1) { gm.StartCoroutine("EmptyError"); } } gm.isCurrentCheck = false; gm.isLeftCheck = false; gm.isMidCheck = false; gm.isRightCheck = false; } } }
using UnityEngine; using System.Collections; public class MovesLeftSystem : MonoBehaviour { public TextMesh textMovesLeft; public int movesLeft; void Start() { PlayerPrefs.SetInt("movesLeftAK", movesLeft); } void Update() { textMovesLeft.text = ""; StringPusher.addStringDependInt(textMovesLeft, PlayerPrefs.GetInt("movesLeftAK"), 2, "0"); textMovesLeft.text += (PlayerPrefs.GetInt("movesLeftAK") + " Left"); } public static void movesLeftMinusOne() { PlayerPrefs.SetInt("movesLeftAK", PlayerPrefs.GetInt("movesLeftAK") - 1); } public static bool movesLeftIsEmpty() { if (PlayerPrefs.GetInt("movesLeftAK") <= 0) return true; return false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Web; namespace CarManageSystem.helper { public class EmailHelper { static string address = System.Configuration.ConfigurationManager.ConnectionStrings["emailServer"].ConnectionString; static string[] strs = address.Split(':'); static string ip = strs[0]; static int port = Convert.ToInt32(strs[1]); /// Send email without attachments /// </summary> /// <param name="ToMail">收件人邮箱地址</param> /// <param name="FromMail">发件人邮箱地址</param> /// <param name="Cc">抄送</param> /// <param name="Bcc">密送</param> /// <param name="Body">邮件正文</param> /// <param name="Subject">邮件标题</param> /// <returns></returns> public static string SendMail(string ToMail, string FromMail, string Cc, string Bcc, string Body, string Subject) { SmtpClient client = new SmtpClient(); MailMessage message = new MailMessage { From = new MailAddress(FromMail) }; message.To.Add(ToMail); if (Cc != "") { message.CC.Add(Cc); } message.Body = Body; message.Subject = Subject; message.IsBodyHtml = true; client.UseDefaultCredentials = true; message.Priority = MailPriority.High; client.Host = ip;//此处应该改为上面设置的服务器IP地址 client.Port = port; try { client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(message); message.Dispose(); return "1"; } catch (Exception exception) { return ("0" + exception); } } } }
// Copyright (c) 2020, mParticle, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Text; using Xunit; namespace MP.Json.Validation.Test { public class ObjectTests { JsonProperty a1 = MPJson.Property("a", 1); JsonProperty b2 = MPJson.Property("b", 2); JsonProperty c3 = MPJson.Property("c", 3); JsonProperty d4 = MPJson.Property("d", 4); [Fact] public void MaxPropertiesTest() { var schema = SingletonSchema("maxProperties", 3); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object(a1, b2))); Assert.True(schema.Validate(MPJson.Object(a1, b2, c3))); Assert.False(schema.Validate(MPJson.Object(a1, b2, c3, d4))); // Any non-object should validate Assert.True(schema.Validate(0)); Assert.False(SingletonSchema("maxProperties", -1).IsValid); Assert.False(SingletonSchema("maxProperties", 1.5).IsValid); Assert.False(SingletonSchema("maxProperties", "1").IsValid); Assert.False(SingletonSchema("maxProperties", MPJson.Array()).IsValid); } [Fact] public void MinItemsTest() { var schema = SingletonSchema("minProperties", 3); Assert.True(schema.IsValid); Assert.False(schema.Validate(MPJson.Object())); Assert.False(schema.Validate(MPJson.Object(a1, b2))); Assert.True(schema.Validate(MPJson.Object(a1, b2, c3))); Assert.True(schema.Validate(MPJson.Object(a1, b2, c3, d4))); // Any non-object should validate Assert.True(schema.Validate(0)); Assert.False(SingletonSchema("minProperties", -1).IsValid); Assert.False(SingletonSchema("minProperties", 1.5).IsValid); Assert.False(SingletonSchema("minProperties", "1").IsValid); Assert.False(SingletonSchema("minProperties", MPJson.Array()).IsValid); } [Fact] public void RequiredTest() { var schema = SingletonSchema("required", MPJson.Array("a", "c")); Assert.True(schema.IsValid); Assert.False(schema.Validate(MPJson.Object())); Assert.False(schema.Validate(MPJson.Object(a1))); Assert.False(schema.Validate(MPJson.Object(b2, c3, d4))); Assert.True(schema.Validate(MPJson.Object(a1, c3))); Assert.True(schema.Validate(MPJson.Object(a1, b2, c3, d4))); Assert.False(SingletonSchema("required", "true").IsValid); Assert.False(SingletonSchema("required", MPJson.Object()).IsValid); } [Fact] public void PropertyNamesTest() { var schema = SingletonSchema("propertyNames", MPJson.Object( MPJson.Property("pattern", "a|c") )); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object(a1))); Assert.False(schema.Validate(MPJson.Object(b2, c3, d4))); Assert.True(schema.Validate(MPJson.Object(a1, c3))); Assert.False(schema.Validate(MPJson.Object(a1, b2, c3, d4))); Assert.False(SingletonSchema("propertyNames", "true").IsValid); Assert.False(SingletonSchema("propertyNames", MPJson.Array()).IsValid); } [Fact] public void PropertiesTest() { var m2 = MPJson.Object("multipleOf", 2); var m3 = MPJson.Object("multipleOf", 3); var m5 = MPJson.Object("multipleOf", 5); MPSchema schema = MPJson.Object("properties", MPJson.Object("m2", m2, "m3", m3, "m5", m5)); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object("m2", 2))); Assert.True(schema.Validate(MPJson.Object("m5", 5))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 4, "m3", 9, "m5", 25))); Assert.False(schema.Validate(MPJson.Object("m2", 3))); Assert.False(schema.Validate(MPJson.Object("m2", 2, "m3", 3, "m5", 7))); } [Fact] public void AdditionalPropertiesTest() { var m2 = MPJson.Object("multipleOf", 2); var m3 = MPJson.Object("multipleOf", 3); var m5 = MPJson.Object("multipleOf", 5); MPSchema schema = MPJson.Object( "properties", MPJson.Object("m2", m2, "m3", m3), "additionalProperties", m5); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object("m2", 2))); Assert.True(schema.Validate(MPJson.Object("m5", 5))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 4, "m3", 9, "m5", 25))); Assert.False(schema.Validate(MPJson.Object("m2", 3))); Assert.False(schema.Validate(MPJson.Object("m2", 2, "m3", 3, "m5", 7))); Assert.False(schema.Validate(MPJson.Object("m7", 7))); } [Fact] public void PatternPropertiesTest() { var m2 = MPJson.Object("multipleOf", 2); var m3 = MPJson.Object("multipleOf", 3); var m5 = MPJson.Object("multipleOf", 5); MPSchema schema = MPJson.Object( "patternProperties", MPJson.Object("2", m2, "3", m3), "additionalProperties", m5); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object("m2", 2))); Assert.True(schema.Validate(MPJson.Object("m5", 5))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 4, "m3", 9, "m5", 25))); Assert.True(schema.Validate(MPJson.Object("m23", 6))); Assert.True(schema.Validate(MPJson.Object("m23", 6, "m5", 5))); Assert.False(schema.Validate(MPJson.Object("m23", 5, "m5", 5))); Assert.False(schema.Validate(MPJson.Object("m2", 3))); Assert.False(schema.Validate(MPJson.Object("m2", 2, "m3", 3, "m5", 7))); Assert.False(schema.Validate(MPJson.Object("m7", 7))); } [Theory] [InlineData("dependencies")] [InlineData("dependentSchemas")] public void DependentSchemasTest(string keyword) { var m2 = MPJson.Object("multipleOf", 2); var m3 = MPJson.Object("multipleOf", 3); MPSchema schema = MPJson.Object( "properties", MPJson.Object("m2", m2, "m3", m3), keyword, MPJson.Object("m5", MPJson.Object("required", MPJson.Array("m3")))); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object("m2", 2))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 4, "m3", 9, "m5", 25))); Assert.True(schema.Validate(MPJson.Object("m5", 5, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3, "m5", 7))); Assert.True(schema.Validate(MPJson.Object("m7", 7))); Assert.False(schema.Validate(MPJson.Object("m2", 3))); Assert.False(schema.Validate(MPJson.Object("m5", 5, "m2", 2))); } [Theory] [InlineData("dependencies")] [InlineData("dependentRequired")] public void DependentRequiredTest(string keyword) { var m2 = MPJson.Object("multipleOf", 2); var m3 = MPJson.Object("multipleOf", 3); MPSchema schema = MPJson.Object( "properties", MPJson.Object("m2", m2, "m3", m3), keyword, MPJson.Object("m5", MPJson.Array("m3"))); Assert.True(schema.IsValid); Assert.True(schema.Validate(MPJson.Object())); Assert.True(schema.Validate(MPJson.Object("m2", 2))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 4, "m3", 9, "m5", 25))); Assert.True(schema.Validate(MPJson.Object("m5", 5, "m3", 3))); Assert.True(schema.Validate(MPJson.Object("m2", 2, "m3", 3, "m5", 7))); Assert.True(schema.Validate(MPJson.Object("m7", 7))); Assert.False(schema.Validate(MPJson.Object("m2", 3))); Assert.False(schema.Validate(MPJson.Object("m5", 5, "m2", 2))); } #region Helpers MPSchema SingletonSchema(string keyword, MPJson json) { return MPJson.Object(MPJson.Property(keyword, json)); } #endregion } }
using System; namespace Business.Services.Contracts { public interface IBusinessService : IDisposable { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Oracle.ManagedDataAccess.Client; namespace Oracle.Personel { public partial class FrmPersonelurunler : Form { OracleBaglantisi conn = new OracleBaglantisi(); public FrmPersonelurunler() { InitializeComponent(); } void UrunListele() { try { OracleCommand cmd = new OracleCommand("select * from TBL_URUNLER", conn.baglanti()); OracleDataReader reader = cmd.ExecuteReader(); DataTable dataTable = new DataTable(); dataTable.Load(reader); dataGridView1.DataSource = dataTable; } catch (Exception ex) { MessageBox.Show(ex.Message); } } void Reset() { txtUrunID.Text = null; txtAd.Text = null; txtMarka.Text = null; txtUrnModeli.Text = null; txtAdet.Text = null; txtAlisFiyati.Text = null; txtSatisFiyati.Text = null; rchtxtAcıklama.Text = null; rchtxtKampanya.Text = null; } private void FrmUrunler_Load(object sender, EventArgs e) { UrunListele(); } private void button1_Click(object sender, EventArgs e) { OracleCommand cmd = new OracleCommand("insert into TBL_URUNLER(URUNADI,URUNMARKA,URUNMODEL,URUNADET,ALISFIYATI,SATISFIYATI,DETAY,KAMPANYA) values(:P1, :P2, :P3, :P4, :P5, :P6,:P7,:P8)", conn.baglanti()); cmd.Parameters.Add(":P1",OracleDbType.Varchar2).Value=txtAd.Text; cmd.Parameters.Add(":P2",OracleDbType.Varchar2).Value=txtMarka.Text; cmd.Parameters.Add(":P3",OracleDbType.Varchar2).Value=txtUrnModeli.Text; cmd.Parameters.Add(":P4",OracleDbType.Int32).Value=txtAdet.Text; cmd.Parameters.Add(":P5",OracleDbType.Double).Value=txtAlisFiyati.Text; cmd.Parameters.Add(":P6",OracleDbType.Double).Value=txtSatisFiyati.Text; cmd.Parameters.Add(":P7",OracleDbType.Varchar2).Value=rchtxtAcıklama.Text; cmd.Parameters.Add(":P8",OracleDbType.Varchar2).Value=rchtxtKampanya.Text; cmd.ExecuteNonQuery(); conn.baglanti().Close(); UrunListele(); Reset(); MessageBox.Show("Ürün Eklendi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { int select = dataGridView1.SelectedCells[0].RowIndex; txtUrunID.Text = dataGridView1.Rows[select].Cells[0].Value.ToString(); txtAd.Text = dataGridView1.Rows[select].Cells[1].Value.ToString(); txtMarka.Text = dataGridView1.Rows[select].Cells[2].Value.ToString(); txtUrnModeli.Text = dataGridView1.Rows[select].Cells[3].Value.ToString(); txtAdet.Text = dataGridView1.Rows[select].Cells[4].Value.ToString(); txtAlisFiyati.Text = dataGridView1.Rows[select].Cells[5].Value.ToString(); txtSatisFiyati.Text = dataGridView1.Rows[select].Cells[6].Value.ToString(); rchtxtAcıklama.Text = dataGridView1.Rows[select].Cells[7].Value.ToString(); rchtxtKampanya.Text = dataGridView1.Rows[select].Cells[8].Value.ToString(); } private void btnGuncelle_Click(object sender, EventArgs e) { OracleCommand cmd = new OracleCommand("update TBL_URUNLER set URUNADI=:P1,URUNMARKA=:P2,URUNMODEL=:P3,URUNADET=:P4,ALISFIYATI=:P5,SATISFIYATI=:P6,DETAY=:P7,KAMPANYA=:P8 where URUNID=:P9", conn.baglanti()); cmd.Parameters.Add(":P1", OracleDbType.Varchar2).Value = txtAd.Text; cmd.Parameters.Add(":P2", OracleDbType.Varchar2).Value = txtMarka.Text; cmd.Parameters.Add(":P3", OracleDbType.Varchar2).Value = txtUrnModeli.Text; cmd.Parameters.Add(":P4", OracleDbType.Int32).Value = txtAdet.Text; cmd.Parameters.Add(":P5", OracleDbType.Double).Value = txtAlisFiyati.Text; cmd.Parameters.Add(":P6", OracleDbType.Double).Value = txtSatisFiyati.Text; cmd.Parameters.Add(":P7", OracleDbType.Varchar2).Value = rchtxtAcıklama.Text; cmd.Parameters.Add(":P8", OracleDbType.Varchar2).Value = rchtxtKampanya.Text; cmd.Parameters.Add(":P9", OracleDbType.Varchar2).Value = txtUrunID.Text; cmd.ExecuteNonQuery(); conn.baglanti().Close(); UrunListele(); Reset(); MessageBox.Show("Ürün Güncellendi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void btnSil_Click(object sender, EventArgs e) { OracleCommand cmd = new OracleCommand("Delete TBL_URUNLER WHERE URUNID=:P1",conn.baglanti()); cmd.Parameters.Add(":P1",OracleDbType.Int32).Value=txtUrunID.Text; cmd.ExecuteNonQuery(); conn.baglanti().Close(); UrunListele(); Reset(); MessageBox.Show("Ürün Silindi", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
namespace CarDealer.ViewModels.Parts { public class PartViewModel { public string Name { get; set; } public double? Price { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BlackjackViewPresenter; namespace BlackjackGUI { public partial class BlackjackTableView : UserControl, IBlackjackTableView { private readonly IBlackjackTableSlotView[] slots; private readonly BlackjackInsuranceDialog insuranceView = new(); private readonly BlackjackSurrenderDialog surrenderView = new(); public ILogView Log => logView; public IBlackjackConfigView Config => configView; public IBlackjackTableSlotView DealerSlot => dealerSlotView; public IBlackjackTableSlotView[] PlayerSlots => slots; public IBlackjackDecisionView Decision => decisionView; public IBlackjackBetView Bet => betView; public IBlackjackInsuranceView Insurance => insuranceView; public IBlackjackEarlySurrenderView Surrender => surrenderView; public IBankView Bank => bankView; public IShoeView Shoe => shoeView; public IBlackjackCountView Count => countView; public event EventHandler<EventArgs> RoundStarted; public BlackjackTableView() { InitializeComponent(); slots = new BlackjackTableSlotView[1] { playerSlotView }; } private void PlayButton_Click(object sender, EventArgs args) { RoundStarted?.Invoke(this, new EventArgs()); playButton.Enabled = false; } public void EndRound() { if (InvokeRequired) { Invoke(new MethodInvoker(() => EndRound())); return; } playButton.Enabled = true; } } }
using System; using System.Linq; using Fingo.Auth.DbAccess.Models; using Fingo.Auth.DbAccess.Models.CustomData; 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; using Fingo.Auth.Domain.Infrastructure.EventBus.Events.CustomData; using Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces; namespace Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation { public class AddProjectCustomDataToProject : IAddProjectCustomDataToProject { private readonly IEventBus _eventBus; private readonly ICustomDataJsonConvertService _jsonConvertService; private readonly IProjectRepository _projectRepository; public AddProjectCustomDataToProject(IProjectRepository projectRepository , ICustomDataJsonConvertService jsonConvertService , IEventBus eventBus) { _eventBus = eventBus; _jsonConvertService = jsonConvertService; _projectRepository = projectRepository; } public void Invoke(int projectId , string name , ConfigurationType type , ProjectConfiguration configuration) { 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 == name); if (customData == null) { project.ProjectCustomData.Add(new ProjectCustomData { ConfigurationName = name , ConfigurationType = type , SerializedConfiguration = _jsonConvertService.Serialize(configuration) }); AddConfigurationForUsers(name , type , configuration , project); } else throw new Exception($"Custom data of name: {name} already exists."); _projectRepository.Edit(project); _eventBus.Publish(new CustomDataAdded(projectId , name , type)); } private void AddConfigurationForUsers(string name , ConfigurationType type , ProjectConfiguration configuration , Project project) { switch (type) { case ConfigurationType.Boolean: { AddBooleanConfigurationToUsers((BooleanProjectConfiguration) configuration , project , name); break; } case ConfigurationType.Number: { AddNumberConfigurationToUsers((NumberProjectConfiguration) configuration , project , name); break; } case ConfigurationType.Text: { AddTextConfigurationToUsers((TextProjectConfiguration) configuration , project , name); break; } } } private void AddBooleanConfigurationToUsers(BooleanProjectConfiguration configuration , Project project , string configurationName) { foreach (var projectProjectUser in project.ProjectUsers) { var projectCustomData = project.ProjectCustomData.FirstOrDefault(m => m.ConfigurationName == configurationName); projectCustomData.UserCustomData.Add(new UserCustomData { UserId = projectProjectUser.UserId , SerializedConfiguration = _jsonConvertService.Serialize(new BooleanUserConfiguration {Value = configuration.Default}) }); } } private void AddNumberConfigurationToUsers(NumberProjectConfiguration configuration , Project project , string configurationName) { foreach (var projectProjectUser in project.ProjectUsers) { var projectCustomData = project.ProjectCustomData.FirstOrDefault(m => m.ConfigurationName == configurationName); projectCustomData.UserCustomData.Add(new UserCustomData { UserId = projectProjectUser.UserId , SerializedConfiguration = _jsonConvertService.Serialize(new NumberUserConfiguration {Value = configuration.Default}) }); } } private void AddTextConfigurationToUsers(TextProjectConfiguration configuration , Project project , string configurationName) { foreach (var projectProjectUser in project.ProjectUsers) { var projectCustomData = project.ProjectCustomData.FirstOrDefault(m => m.ConfigurationName == configurationName); projectCustomData.UserCustomData.Add(new UserCustomData { UserId = projectProjectUser.UserId , SerializedConfiguration = _jsonConvertService.Serialize(new TextUserConfiguration {Value = configuration.Default}) }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MiniShop { public class ShopBasket : Iitems { //public Merchandise merchandise { get; set; } public string Id { get; set; } public string Name { get; set; } public double Price { get; set; } public double Weight { get; set; } public int PurchaseAmount { get; set; } public ShopBasket(Iitems merch) { Id = merch.Id; Name = merch.Name; Price = merch.Price; Weight = merch.Weight; PurchaseAmount = 1; } public void ChangeAmount(int amount) { PurchaseAmount = amount; } } }
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 lab_015 { public partial class Form1 : Form { public Form1() { InitializeComponent(); base.Text = "Мониторинг движения мыши"; } private void listBox1_MouseEnter(object sender, EventArgs e) { listBox1.Items.Add("Курсор мыши вошел в область ListBox"); } private void listBox1_MouseLeave(object sender, EventArgs e) { listBox1.Items.Add("Курсор мыши вышел из области ListBox"); } private void listBox1_MouseMove(object sender, MouseEventArgs e) { textBox1.Text = string.Format("X = {0} или {1}", Form1.MousePosition.X, e.X); textBox2.Text = string.Format("Y = {0} или {1}", Form1.MousePosition.Y, e.Y); } } }
using System.ComponentModel; using System; namespace ControleEstacionamento.Web.ViewModels.Valores { public class ValoresViewModelList { public int ValorId { get; set; } [DisplayName("Inicio de Vigencia")] public DateTime InicioVigencia { get; set; } [DisplayName("Fim de Vigencia")] public DateTime FimVigencia { get; set; } [DisplayName("Valor da Hora")] public double ValorHora { get; set; } [DisplayName("Valor da Hora Adicional")] public double ValorAdicional { get; set; } } }
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Create a media for an already open file descriptor. /// The file descriptor shall be open for reading (or reading and writing). /// /// Regular file descriptors, pipe read descriptors and character device /// descriptors (including TTYs) are supported on all platforms. /// Block device descriptors are supported where available. /// Directory descriptors are supported on systems that provide <c>fdopendir()</c>. /// Sockets are supported on all platforms where they are file descriptors, /// i.e. all except Windows. /// </summary> /// <remarks> /// This library will <b>not</b> automatically close the file descriptor /// under any circumstance. Nevertheless, a file descriptor can usually only be /// rendered once in a media player. To render it a second time, the file /// descriptor should probably be rewound to the beginning with lseek(). /// </remarks> /// <param name="instance"> /// The instance /// </param> /// <param name="fd"> /// An open file descriptor /// </param> /// <returns> /// the newly created media or NULL on error /// </returns> [LibVlcFunction("libvlc_media_new_fd")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr CreateNewMediaFromFileDescriptor(IntPtr instance, int fd); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace BackToBasics { public class Shop { public string nom; public int money; public List<Pony> ponylist; public Shop(string name, int gold) { nom = name; money = gold; ponylist = new List<Pony>(); } public void display() { for (int i = 0; i < ponylist.Count; i++) { ponylist[i].display(); Console.Write(" | "); } } public void add_gold(int nb) { money += nb; } public void add_poney(Pony poney) { ponylist.Add(poney); } public Pony get_poney() { try { Pony my_pony = ponylist[ponylist.Count - 1]; ponylist.RemoveAt(ponylist.Count - 1); return my_pony; } catch { Console.WriteLine("error get_poney"); return (new Pony(ConsoleColor.Black)); } } } }
 using System; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Reflection; using ReactMusicStore.Core.Data.Context.Config; using ReactMusicStore.Core.Data.Context.Mapping; using ReactMusicStore.Core.Data.Context.Mapping.Identity; using ReactMusicStore.Core.Data.Context.Migrations; using ReactMusicStore.Core.Domain.Entities; using ReactMusicStore.Core.Domain.Entities.Identity; using ReactMusicStore.Core.Utilities.Extensions; namespace ReactMusicStore.Core.Data.Context { public class DbMusicStoreContext : BaseDbContext { static DbMusicStoreContext() { Database.SetInitializer(new ContextInitializer()); } public DbMusicStoreContext() : base() { } public DbMusicStoreContext(string nameOrConnectionString) : base(nameOrConnectionString) { if (!Database.Exists()) { Database.Initialize(true); } } public static DbMusicStoreContext Create() { return new DbMusicStoreContext(GetConnectionString()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); base.OnModelCreating(modelBuilder); //modelBuilder.Configurations.Add(new GenreMap()); //modelBuilder.Configurations.Add(new ArtistMap()); //modelBuilder.Configurations.Add(new AlbumMap()); //modelBuilder.Configurations.Add(new CartMap()); //modelBuilder.Configurations.Add(new OrderMap()); //modelBuilder.Configurations.Add(new OrderDetailMap()); //modelBuilder.Configurations.Add(new UserAccountMap()); //modelBuilder.Configurations.Add(new UserAccountLoginMap()); //modelBuilder.Configurations.Add(new UserAccountsUserRolesMap()); //modelBuilder.Configurations.Add(new UserRoleMap()); var typesToRegister = from t in Assembly.GetExecutingAssembly().GetTypes() where t.Namespace.HasValue() && t.BaseType != null && t.BaseType.IsGenericType let genericType = t.BaseType.GetGenericTypeDefinition() where genericType == typeof(EntityTypeConfiguration<>) || genericType == typeof(ComplexTypeConfiguration<>) select t; foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } } #region DbSet public virtual IDbSet<UserRole> UserRoles { get; set; } public virtual IDbSet<UserAccount> UserAccounts { get; set; } public IDbSet<Genre> Genres { get; set; } public IDbSet<Album> Albums { get; set; } public IDbSet<Artist> Artists { get; set; } public IDbSet<Cart> Carts { get; set; } public IDbSet<Order> Orders { get; set; } public IDbSet<OrderDetail> OrderDetails { get; set; } #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 ProgramaOperaciones { public partial class FormPrincipal : Form { public FormPrincipal() { InitializeComponent(); //FormPrincipal fp = new FormPrincipal(); //fp.StartPosition = FormStartPosition.CenterScreen; } private void pictureBoxCirculo_Click(object sender, EventArgs e) { FormCirculo fc = new FormCirculo(); fc.StartPosition = FormStartPosition.CenterScreen; fc.Show(); this.Hide(); } private void pictureBoxCuadrado_Click(object sender, EventArgs e) { FormCuadrado fcu = new FormCuadrado(); fcu.StartPosition = FormStartPosition.CenterScreen; fcu.Show(); this.Hide(); } private void pictureBoxRectangulo_Click(object sender, EventArgs e) { FormRectangulo fr = new FormRectangulo(); fr.StartPosition = FormStartPosition.CenterScreen; fr.Show(); this.Hide(); } private void pictureBoxTriangulo_Click(object sender, EventArgs e) { FormTriangulo ft = new FormTriangulo(); ft.StartPosition = FormStartPosition.CenterScreen; ft.Show(); this.Hide(); } } }
 using Spring.Messaging.Amqp.Rabbit.Connection; using Spring.Messaging.Amqp.Rabbit.Test; namespace Spring.Messaging.Amqp.Rabbit.Listener { /// <summary> /// Message listener recovery single connection integration tests. /// </summary> /// <remarks></remarks> public class MessageListenerRecoverySingleConnectionIntegrationTests { /// <summary> /// Creates the connection factory. /// </summary> /// <returns>The connection factory.</returns> /// <remarks></remarks> protected IConnectionFactory CreateConnectionFactory() { var connectionFactory = new SingleConnectionFactory(); connectionFactory.Port = BrokerTestUtils.GetPort(); return connectionFactory; } } }
using System; using System.Collections.Generic; using System.Text; namespace AimaTeam.WebFormLightAPI.httpUtility { /// <summary> /// 定义一个对字符串进行编码管理的工具类 /// </summary> internal sealed class EncodingUtility { /// <summary> /// 通过执行的Encoding获取字符串的bytes数组 /// </summary> /// <param name="str">字符串</param> /// <param name="encoding">编码</param> /// <returns></returns> public static byte[] get_bytes(string str, Encoding encoding) { return encoding.GetBytes(str); } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.MySqlEntity { public class MtRunning { public string RunningPrefix { get; set; } public int RunningNumber { get; set; } public string RunningMonth { get; set; } public int RunningYear { get; set; } } public class MtRunningConfig : EntityTypeConfiguration<MtRunning> { public MtRunningConfig() { ToTable("tbmtrunning"); Property(t => t.RunningMonth).HasColumnName("RunningMonth"); Property(t => t.RunningNumber).HasColumnName("RunningNumber"); Property(t => t.RunningPrefix).HasColumnName("RunningPrefix"); Property(t => t.RunningYear).HasColumnName("RunningYear"); HasKey(t => t.RunningPrefix); } } }
namespace BattleEngine.Output { public class BuildingChangeOwnerEvent : OutputEvent { public int objectId; public int ownerId; public int units; } }
using Xamarin.Forms; using Xamarin.Forms.Xaml; using XF40Demo.ViewModels; namespace XF40Demo.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class PowerBenefitsPage : ContentPage { private readonly PowerDetailViewModel vm = new PowerDetailViewModel(); public PowerBenefitsPage() { InitializeComponent(); BindingContext = vm; } protected override void OnAppearing() { vm.OnAppearing(); } protected override void OnDisappearing() { vm.OnDisappearing(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 旋切边 { public partial class Alarm : Form { string[] oldState = new string[16]; public Alarm() { InitializeComponent(); } public void almAdd(string almMsg) { listBox1.Items.Add(almMsg); } public void almRemove(string almMsg) { listBox1.Items.Remove(almMsg); } private void timer1_Tick(object sender, EventArgs e) { string[] newState = new string[16]; newState[0] = global.alarmString.Substring(2, 1); if (oldState[0] != newState[0]) { oldState[0] = newState[0]; if (newState[0] == "1") { this.almAdd("紧急停止"); } else { this.almRemove("紧急停止"); } } newState[1] = global.alarmString.Substring(1, 1); if (oldState[1] != newState[1]) { oldState[1] = newState[1]; if (newState[1] == "1") { this.almAdd("光幕报警"); } else { this.almRemove("光幕报警"); } } newState[2] = global.alarmString.Substring(3, 1); if (oldState[2] != newState[2]) { oldState[2] = newState[2]; if (newState[2] == "1") { this.almAdd("棱镜气缸报警"); } else { this.almRemove("棱镜气缸报警"); } } } private void Alarm_Load(object sender, EventArgs e) { //timer1.Enabled = true; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } } }
using UnityEngine; using TouchScript.Gestures; using System; namespace Project.Game { [RequireComponent(typeof(FlickGesture))] public class SwipeGesture : MonoBehaviour { FlickGesture baseGesture; public event Action SwipeUp; public event Action SwipeDown; public event Action SwipeLeft; public event Action SwipeRigth; private void Awake() { baseGesture = GetComponent<FlickGesture>(); } private void OnEnable() { baseGesture.Flicked += SwipeHandler; } private void OnDisable() { baseGesture.Flicked -= SwipeHandler; } private void SwipeHandler(object sender, EventArgs e) { Vector2 v = baseGesture.ScreenFlickVector; float x = v.x; float y = v.y; if (Mathf.Abs(x) > Mathf.Abs(y)) { if (x < 0) { if (SwipeRigth != null) SwipeRigth(); } else { if (SwipeLeft != null) SwipeLeft(); } } else { if (y < 0) { if (SwipeDown != null) SwipeDown(); } else { if (SwipeUp != null) SwipeUp(); } } } } }
using System; using System.Collections.Generic; using System.Text; namespace lsc.Model { /// <summary> /// 用户数量相关统计 /// </summary> public class UserEnterReport { public int UserID { get; set; } public int Total { get; set; } } public class EnterTotalReportForDay { public string Days { get; set; } public int UserID { get; set; } public int Total { get; set; } } }
using UnityEngine; using System.Collections; [System.Serializable] public class Product { public string pName; public string pDescription; public int pPrice; public int pDef; public int pHp; //usable item public Product (string _name, string _desc, int _price) { pName = _name; pDescription = _desc; pPrice = _price; } //equipment item public Product (string _name, string _desc, int _price, int _def, int _hpInc) { pName = _name; pDescription = _desc; pPrice = _price; pDef = _def; pHp = _hpInc; } }
using Computer_Wifi_Remote.Command; using Computer_Wifi_Remote_Library; using Computer_Wifi_Remote_Library.Command; using System; using WebSocketSharp; namespace Computer_Wifi_Remote_Client { class Program { static void Main(string[] args) { Console.WriteLine("Press any key to connect..."); Console.ReadKey(); using(var ws = new WebSocket("ws://localhost:34198/command")) { ws.Connect(); Console.WriteLine("Client is running..."); Console.WriteLine("Type a command. Type quit to exit"); var nextLine = Console.ReadLine(); while(nextLine.ToLowerInvariant() != "quit") { var commands = nextLine.Split(' '); Commands.ExecuteRemotely(ws, new Request(commands[0], commands.SubArray(1, commands.Length - 1))); nextLine = Console.ReadLine(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using NStack; using Terminal.Gui.Resources; namespace Terminal.Gui { /// <summary> /// Provides navigation and a user interface (UI) to collect related data across multiple steps. Each step (<see cref="WizardStep"/>) can host /// arbitrary <see cref="View"/>s, much like a <see cref="Dialog"/>. Each step also has a pane for help text. Along the /// bottom of the Wizard view are customizable buttons enabling the user to navigate forward and backward through the Wizard. /// </summary> /// <remarks> /// The Wizard can be displayed either as a modal (pop-up) <see cref="Window"/> (like <see cref="Dialog"/>) or as an embedded <see cref="View"/>. /// /// By default, <see cref="Wizard.Modal"/> is <c>true</c>. In this case launch the Wizard with <c>Application.Run(wizard)</c>. /// /// See <see cref="Wizard.Modal"/> for more details. /// </remarks> /// <example> /// <code> /// using Terminal.Gui; /// using NStack; /// /// Application.Init(); /// /// var wizard = new Wizard ($"Setup Wizard"); /// /// // Add 1st step /// var firstStep = new Wizard.WizardStep ("End User License Agreement"); /// wizard.AddStep(firstStep); /// firstStep.NextButtonText = "Accept!"; /// firstStep.HelpText = "This is the End User License Agreement."; /// /// // Add 2nd step /// var secondStep = new Wizard.WizardStep ("Second Step"); /// wizard.AddStep(secondStep); /// secondStep.HelpText = "This is the help text for the Second Step."; /// var lbl = new Label ("Name:") { AutoSize = true }; /// secondStep.Add(lbl); /// /// var name = new TextField () { X = Pos.Right (lbl) + 1, Width = Dim.Fill () - 1 }; /// secondStep.Add(name); /// /// wizard.Finished += (args) => /// { /// MessageBox.Query("Wizard", $"Finished. The Name entered is '{name.Text}'", "Ok"); /// Application.RequestStop(); /// }; /// /// Application.Top.Add (wizard); /// Application.Run (); /// Application.Shutdown (); /// </code> /// </example> public class Wizard : Dialog { /// <summary> /// Represents a basic step that is displayed in a <see cref="Wizard"/>. The <see cref="WizardStep"/> view is divided horizontally in two. On the left is the /// content view where <see cref="View"/>s can be added, On the right is the help for the step. /// Set <see cref="WizardStep.HelpText"/> to set the help text. If the help text is empty the help pane will not /// be shown. /// /// If there are no Views added to the WizardStep the <see cref="HelpText"/> (if not empty) will fill the wizard step. /// </summary> /// <remarks> /// If <see cref="Button"/>s are added, do not set <see cref="Button.IsDefault"/> to true as this will conflict /// with the Next button of the Wizard. /// /// Subscribe to the <see cref="View.VisibleChanged"/> event to be notified when the step is active; see also: <see cref="Wizard.StepChanged"/>. /// /// To enable or disable a step from being shown to the user, set <see cref="View.Enabled"/>. /// /// </remarks> public class WizardStep : FrameView { /// <summary> /// The title of the <see cref="WizardStep"/>. /// </summary> /// <remarks>The Title is only displayed when the <see cref="Wizard"/> is used as a modal pop-up (see <see cref="Wizard.Modal"/>.</remarks> public new ustring Title { get => title; set { if (!OnTitleChanging (title, value)) { var old = title; title = value; OnTitleChanged (old, title); } base.Title = value; SetNeedsDisplay (); } } private ustring title = ustring.Empty; /// <summary> /// An <see cref="EventArgs"/> which allows passing a cancelable new <see cref="Title"/> value event. /// </summary> public class TitleEventArgs : EventArgs { /// <summary> /// The new Window Title. /// </summary> public ustring NewTitle { get; set; } /// <summary> /// The old Window Title. /// </summary> public ustring OldTitle { get; set; } /// <summary> /// Flag which allows cancelling the Title change. /// </summary> public bool Cancel { get; set; } /// <summary> /// Initializes a new instance of <see cref="TitleEventArgs"/> /// </summary> /// <param name="oldTitle">The <see cref="Title"/> that is/has been replaced.</param> /// <param name="newTitle">The new <see cref="Title"/> to be replaced.</param> public TitleEventArgs (ustring oldTitle, ustring newTitle) { OldTitle = oldTitle; NewTitle = newTitle; } } /// <summary> /// Called before the <see cref="Title"/> changes. Invokes the <see cref="TitleChanging"/> event, which can be cancelled. /// </summary> /// <param name="oldTitle">The <see cref="Title"/> that is/has been replaced.</param> /// <param name="newTitle">The new <see cref="Title"/> to be replaced.</param> /// <returns><c>true</c> if an event handler cancelled the Title change.</returns> public virtual bool OnTitleChanging (ustring oldTitle, ustring newTitle) { var args = new TitleEventArgs (oldTitle, newTitle); TitleChanging?.Invoke (args); return args.Cancel; } /// <summary> /// Event fired when the <see cref="Title"/> is changing. Set <see cref="TitleEventArgs.Cancel"/> to /// <c>true</c> to cancel the Title change. /// </summary> public event Action<TitleEventArgs> TitleChanging; /// <summary> /// Called when the <see cref="Title"/> has been changed. Invokes the <see cref="TitleChanged"/> event. /// </summary> /// <param name="oldTitle">The <see cref="Title"/> that is/has been replaced.</param> /// <param name="newTitle">The new <see cref="Title"/> to be replaced.</param> public virtual void OnTitleChanged (ustring oldTitle, ustring newTitle) { var args = new TitleEventArgs (oldTitle, newTitle); TitleChanged?.Invoke (args); } /// <summary> /// Event fired after the <see cref="Title"/> has been changed. /// </summary> public event Action<TitleEventArgs> TitleChanged; /// <summary> /// WizardContentView is an internal implementation detail of Window. It is used to host Views added with <see cref="Add(View)"/>. /// Its ONLY reason for being is to provide a simple way for Window to expose to those SubViews that the Window's Bounds /// are actually deflated due to the border. /// </summary> class WizardContentView : View { } private WizardContentView contentView = new WizardContentView (); /// <summary> /// Sets or gets help text for the <see cref="WizardStep"/>.If <see cref="WizardStep.HelpText"/> is empty /// the help pane will not be visible and the content will fill the entire WizardStep. /// </summary> /// <remarks>The help text is displayed using a read-only <see cref="TextView"/>.</remarks> public ustring HelpText { get => helpTextView.Text; set { helpTextView.Text = value; ShowHide (); SetNeedsDisplay (); } } private TextView helpTextView = new TextView (); /// <summary> /// Sets or gets the text for the back button. The back button will only be visible on /// steps after the first step. /// </summary> /// <remarks>The default text is "Back"</remarks> public ustring BackButtonText { get; set; } = ustring.Empty; /// <summary> /// Sets or gets the text for the next/finish button. /// </summary> /// <remarks>The default text is "Next..." if the Pane is not the last pane. Otherwise it is "Finish"</remarks> public ustring NextButtonText { get; set; } = ustring.Empty; /// <summary> /// Initializes a new instance of the <see cref="Wizard"/> class using <see cref="LayoutStyle.Computed"/> positioning. /// </summary> /// <param name="title">Title for the Step. Will be appended to the containing Wizard's title as /// "Wizard Title - Wizard Step Title" when this step is active.</param> /// <remarks> /// </remarks> public WizardStep (ustring title) { this.Title = title; // this.Title holds just the "Wizard Title"; base.Title holds "Wizard Title - Step Title" this.Border.BorderStyle = BorderStyle.Rounded; base.Add (contentView); helpTextView.ReadOnly = true; helpTextView.WordWrap = true; base.Add (helpTextView); ShowHide (); var scrollBar = new ScrollBarView (helpTextView, true); scrollBar.ChangedPosition += () => { helpTextView.TopRow = scrollBar.Position; if (helpTextView.TopRow != scrollBar.Position) { scrollBar.Position = helpTextView.TopRow; } helpTextView.SetNeedsDisplay (); }; scrollBar.OtherScrollBarView.ChangedPosition += () => { helpTextView.LeftColumn = scrollBar.OtherScrollBarView.Position; if (helpTextView.LeftColumn != scrollBar.OtherScrollBarView.Position) { scrollBar.OtherScrollBarView.Position = helpTextView.LeftColumn; } helpTextView.SetNeedsDisplay (); }; scrollBar.VisibleChanged += () => { if (scrollBar.Visible && helpTextView.RightOffset == 0) { helpTextView.RightOffset = 1; } else if (!scrollBar.Visible && helpTextView.RightOffset == 1) { helpTextView.RightOffset = 0; } }; scrollBar.OtherScrollBarView.VisibleChanged += () => { if (scrollBar.OtherScrollBarView.Visible && helpTextView.BottomOffset == 0) { helpTextView.BottomOffset = 1; } else if (!scrollBar.OtherScrollBarView.Visible && helpTextView.BottomOffset == 1) { helpTextView.BottomOffset = 0; } }; helpTextView.DrawContent += (e) => { scrollBar.Size = helpTextView.Lines; scrollBar.Position = helpTextView.TopRow; if (scrollBar.OtherScrollBarView != null) { scrollBar.OtherScrollBarView.Size = helpTextView.Maxlength; scrollBar.OtherScrollBarView.Position = helpTextView.LeftColumn; } scrollBar.LayoutSubviews (); scrollBar.Refresh (); }; base.Add (scrollBar); } /// <summary> /// Does the work to show and hide the contentView and helpView as appropriate /// </summary> internal void ShowHide () { contentView.Height = Dim.Fill (); helpTextView.Height = Dim.Fill (); helpTextView.Width = Dim.Fill (); if (contentView.InternalSubviews?.Count > 0) { if (helpTextView.Text.Length > 0) { contentView.Width = Dim.Percent (70); helpTextView.X = Pos.Right (contentView); helpTextView.Width = Dim.Fill (); } else { contentView.Width = Dim.Percent (100); } } else { if (helpTextView.Text.Length > 0) { helpTextView.X = 0; } else { // Error - no pane shown } } contentView.Visible = contentView.InternalSubviews?.Count > 0; helpTextView.Visible = helpTextView.Text.Length > 0; } /// <summary> /// Add the specified <see cref="View"/> to the <see cref="WizardStep"/>. /// </summary> /// <param name="view"><see cref="View"/> to add to this container</param> public override void Add (View view) { contentView.Add (view); if (view.CanFocus) CanFocus = true; ShowHide (); } /// <summary> /// Removes a <see cref="View"/> from <see cref="WizardStep"/>. /// </summary> /// <remarks> /// </remarks> public override void Remove (View view) { if (view == null) return; SetNeedsDisplay (); var touched = view.Frame; contentView.Remove (view); if (contentView.InternalSubviews.Count < 1) this.CanFocus = false; ShowHide (); } /// <summary> /// Removes all <see cref="View"/>s from the <see cref="WizardStep"/>. /// </summary> /// <remarks> /// </remarks> public override void RemoveAll () { contentView.RemoveAll (); ShowHide (); } } // end of WizardStep class /// <summary> /// Initializes a new instance of the <see cref="Wizard"/> class using <see cref="LayoutStyle.Computed"/> positioning. /// </summary> /// <remarks> /// The Wizard will be vertically and horizontally centered in the container. /// After initialization use <c>X</c>, <c>Y</c>, <c>Width</c>, and <c>Height</c> change size and position. /// </remarks> public Wizard () : this (ustring.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="Wizard"/> class using <see cref="LayoutStyle.Computed"/> positioning. /// </summary> /// <param name="title">Sets the <see cref="Title"/> for the Wizard.</param> /// <remarks> /// The Wizard will be vertically and horizontally centered in the container. /// After initialization use <c>X</c>, <c>Y</c>, <c>Width</c>, and <c>Height</c> change size and position. /// </remarks> public Wizard (ustring title) : base (title) { wizardTitle = title; // Using Justify causes the Back and Next buttons to be hard justified against // the left and right edge ButtonAlignment = ButtonAlignments.Justify; this.Border.BorderStyle = BorderStyle.Double; this.Border.Padding = new Thickness (0); //// Add a horiz separator //var separator = new LineView (Graphs.Orientation.Horizontal) { // Y = Pos.AnchorEnd (2) //}; //Add (separator); // BUGBUG: Space is to work around https://github.com/gui-cs/Terminal.Gui/issues/1812 backBtn = new Button (Strings.wzBack) { AutoSize = true }; AddButton (backBtn); nextfinishBtn = new Button (Strings.wzFinish) { AutoSize = true }; nextfinishBtn.IsDefault = true; AddButton (nextfinishBtn); backBtn.Clicked += BackBtn_Clicked; nextfinishBtn.Clicked += NextfinishBtn_Clicked; Loaded += Wizard_Loaded; Closing += Wizard_Closing; if (Modal) { ClearKeybinding (Command.QuitToplevel); AddKeyBinding (Key.Esc, Command.QuitToplevel); } Initialized += (s, e) => Wizard_Loaded (); } private void Wizard_Loaded () { CurrentStep = GetFirstStep (); // gets the first step if CurrentStep == null } private bool finishedPressed = false; private void Wizard_Closing (ToplevelClosingEventArgs obj) { if (!finishedPressed) { var args = new WizardButtonEventArgs (); Cancelled?.Invoke (args); } } private void NextfinishBtn_Clicked () { if (CurrentStep == GetLastStep ()) { var args = new WizardButtonEventArgs (); Finished?.Invoke (args); if (!args.Cancel) { finishedPressed = true; if (IsCurrentTop) { Application.RequestStop (this); } else { // Wizard was created as a non-modal (just added to another View). // Do nothing } } } else { var args = new WizardButtonEventArgs (); MovingNext?.Invoke (args); if (!args.Cancel) { GoNext (); } } } /// <summary> /// <see cref="Wizard"/> is derived from <see cref="Dialog"/> and Dialog causes <c>Esc</c> to call /// <see cref="Application.RequestStop(Toplevel)"/>, closing the Dialog. Wizard overrides <see cref="Responder.ProcessKey(KeyEvent)"/> /// to instead fire the <see cref="Cancelled"/> event when Wizard is being used as a non-modal (see <see cref="Wizard.Modal"/>. /// See <see cref="Responder.ProcessKey(KeyEvent)"/> for more. /// </summary> /// <param name="kb"></param> /// <returns></returns> public override bool ProcessKey (KeyEvent kb) { if (!Modal) { switch (kb.Key) { case Key.Esc: var args = new WizardButtonEventArgs (); Cancelled?.Invoke (args); return false; } } return base.ProcessKey (kb); } /// <summary> /// Causes the wizad to move to the next enabled step (or last step if <see cref="CurrentStep"/> is not set). /// If there is no previous step, does nothing. /// </summary> public void GoNext () { var nextStep = GetNextStep (); if (nextStep != null) { GoToStep (nextStep); } } /// <summary> /// Returns the next enabled <see cref="WizardStep"/> after the current step. Takes into account steps which /// are disabled. If <see cref="CurrentStep"/> is <c>null</c> returns the first enabled step. /// </summary> /// <returns>The next step after the current step, if there is one; otherwise returns <c>null</c>, which /// indicates either there are no enabled steps or the current step is the last enabled step.</returns> public WizardStep GetNextStep () { LinkedListNode<WizardStep> step = null; if (CurrentStep == null) { // Get first step, assume it is next step = steps.First; } else { // Get the step after current step = steps.Find (CurrentStep); if (step != null) { step = step.Next; } } // step now points to the potential next step while (step != null) { if (step.Value.Enabled) { return step.Value; } step = step.Next; } return null; } private void BackBtn_Clicked () { var args = new WizardButtonEventArgs (); MovingBack?.Invoke (args); if (!args.Cancel) { GoBack (); } } /// <summary> /// Causes the wizad to move to the previous enabled step (or first step if <see cref="CurrentStep"/> is not set). /// If there is no previous step, does nothing. /// </summary> public void GoBack () { var previous = GetPreviousStep (); if (previous != null) { GoToStep (previous); } } /// <summary> /// Returns the first enabled <see cref="WizardStep"/> before the current step. Takes into account steps which /// are disabled. If <see cref="CurrentStep"/> is <c>null</c> returns the last enabled step. /// </summary> /// <returns>The first step ahead of the current step, if there is one; otherwise returns <c>null</c>, which /// indicates either there are no enabled steps or the current step is the first enabled step.</returns> public WizardStep GetPreviousStep () { LinkedListNode<WizardStep> step = null; if (CurrentStep == null) { // Get last step, assume it is previous step = steps.Last; } else { // Get the step before current step = steps.Find (CurrentStep); if (step != null) { step = step.Previous; } } // step now points to the potential previous step while (step != null) { if (step.Value.Enabled) { return step.Value; } step = step.Previous; } return null; } /// <summary> /// Returns the first enabled step in the Wizard /// </summary> /// <returns>The last enabled step</returns> public WizardStep GetFirstStep () { return steps.FirstOrDefault (s => s.Enabled); } /// <summary> /// Returns the last enabled step in the Wizard /// </summary> /// <returns>The last enabled step</returns> public WizardStep GetLastStep () { return steps.LastOrDefault (s => s.Enabled); } private LinkedList<WizardStep> steps = new LinkedList<WizardStep> (); private WizardStep currentStep = null; /// <summary> /// If the <see cref="CurrentStep"/> is not the first step in the wizard, this button causes /// the <see cref="MovingBack"/> event to be fired and the wizard moves to the previous step. /// </summary> /// <remarks> /// Use the <see cref="MovingBack"></see> event to be notified when the user attempts to go back. /// </remarks> public Button BackButton { get => backBtn; } private Button backBtn; /// <summary> /// If the <see cref="CurrentStep"/> is the last step in the wizard, this button causes /// the <see cref="Finished"/> event to be fired and the wizard to close. If the step is not the last step, /// the <see cref="MovingNext"/> event will be fired and the wizard will move next step. /// </summary> /// <remarks> /// Use the <see cref="MovingNext"></see> and <see cref="Finished"></see> events to be notified /// when the user attempts go to the next step or finish the wizard. /// </remarks> public Button NextFinishButton { get => nextfinishBtn; } private Button nextfinishBtn; /// <summary> /// Adds a step to the wizard. The Next and Back buttons navigate through the added steps in the /// order they were added. /// </summary> /// <param name="newStep"></param> /// <remarks>The "Next..." button of the last step added will read "Finish" (unless changed from default).</remarks> public void AddStep (WizardStep newStep) { SizeStep (newStep); newStep.EnabledChanged += UpdateButtonsAndTitle; newStep.TitleChanged += (args) => UpdateButtonsAndTitle (); steps.AddLast (newStep); this.Add (newStep); UpdateButtonsAndTitle (); } /// <summary> /// The title of the Wizard, shown at the top of the Wizard with " - currentStep.Title" appended. /// </summary> /// <remarks> /// The Title is only displayed when the <see cref="Wizard"/> <see cref="Wizard.Modal"/> is set to <c>false</c>. /// </remarks> public new ustring Title { get { // The base (Dialog) Title holds the full title ("Wizard Title - Step Title") return base.Title; } set { wizardTitle = value; base.Title = $"{wizardTitle}{(steps.Count > 0 && currentStep != null ? " - " + currentStep.Title : string.Empty)}"; } } private ustring wizardTitle = ustring.Empty; /// <summary> /// <see cref="EventArgs"/> for <see cref="WizardStep"/> transition events. /// </summary> public class WizardButtonEventArgs : EventArgs { /// <summary> /// Set to true to cancel the transition to the next step. /// </summary> public bool Cancel { get; set; } /// <summary> /// Initializes a new instance of <see cref="WizardButtonEventArgs"/> /// </summary> public WizardButtonEventArgs () { Cancel = false; } } /// <summary> /// Raised when the Back button in the <see cref="Wizard"/> is clicked. The Back button is always /// the first button in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any. /// </summary> public event Action<WizardButtonEventArgs> MovingBack; /// <summary> /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked (or the user presses Enter). /// The Next/Finish button is always the last button in the array of Buttons passed to the <see cref="Wizard"/> constructor, /// if any. This event is only raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow /// (otherwise the <see cref="Finished"/> event is raised). /// </summary> public event Action<WizardButtonEventArgs> MovingNext; /// <summary> /// Raised when the Next/Finish button in the <see cref="Wizard"/> is clicked. The Next/Finish button is always /// the last button in the array of Buttons passed to the <see cref="Wizard"/> constructor, if any. This event is only /// raised if the <see cref="CurrentStep"/> is the last Step in the Wizard flow /// (otherwise the <see cref="Finished"/> event is raised). /// </summary> public event Action<WizardButtonEventArgs> Finished; /// <summary> /// Raised when the user has cancelled the <see cref="Wizard"/> by pressin the Esc key. /// To prevent a modal (<see cref="Wizard.Modal"/> is <c>true</c>) Wizard from /// closing, cancel the event by setting <see cref="WizardButtonEventArgs.Cancel"/> to /// <c>true</c> before returning from the event handler. /// </summary> public event Action<WizardButtonEventArgs> Cancelled; /// <summary> /// <see cref="EventArgs"/> for <see cref="WizardStep"/> events. /// </summary> public class StepChangeEventArgs : EventArgs { /// <summary> /// The current (or previous) <see cref="WizardStep"/>. /// </summary> public WizardStep OldStep { get; } /// <summary> /// The <see cref="WizardStep"/> the <see cref="Wizard"/> is changing to or has changed to. /// </summary> public WizardStep NewStep { get; } /// <summary> /// Event handlers can set to true before returning to cancel the step transition. /// </summary> public bool Cancel { get; set; } /// <summary> /// Initializes a new instance of <see cref="StepChangeEventArgs"/> /// </summary> /// <param name="oldStep">The current <see cref="WizardStep"/>.</param> /// <param name="newStep">The new <see cref="WizardStep"/>.</param> public StepChangeEventArgs (WizardStep oldStep, WizardStep newStep) { OldStep = oldStep; NewStep = newStep; Cancel = false; } } /// <summary> /// This event is raised when the current <see cref="CurrentStep"/>) is about to change. Use <see cref="StepChangeEventArgs.Cancel"/> /// to abort the transition. /// </summary> public event Action<StepChangeEventArgs> StepChanging; /// <summary> /// This event is raised after the <see cref="Wizard"/> has changed the <see cref="CurrentStep"/>. /// </summary> public event Action<StepChangeEventArgs> StepChanged; /// <summary> /// Gets or sets the currently active <see cref="WizardStep"/>. /// </summary> public WizardStep CurrentStep { get => currentStep; set { GoToStep (value); } } /// <summary> /// Called when the <see cref="Wizard"/> is about to transition to another <see cref="WizardStep"/>. Fires the <see cref="StepChanging"/> event. /// </summary> /// <param name="oldStep">The step the Wizard is about to change from</param> /// <param name="newStep">The step the Wizard is about to change to</param> /// <returns>True if the change is to be cancelled.</returns> public virtual bool OnStepChanging (WizardStep oldStep, WizardStep newStep) { var args = new StepChangeEventArgs (oldStep, newStep); StepChanging?.Invoke (args); return args.Cancel; } /// <summary> /// Called when the <see cref="Wizard"/> has completed transition to a new <see cref="WizardStep"/>. Fires the <see cref="StepChanged"/> event. /// </summary> /// <param name="oldStep">The step the Wizard changed from</param> /// <param name="newStep">The step the Wizard has changed to</param> /// <returns>True if the change is to be cancelled.</returns> public virtual bool OnStepChanged (WizardStep oldStep, WizardStep newStep) { var args = new StepChangeEventArgs (oldStep, newStep); StepChanged?.Invoke (args); return args.Cancel; } /// <summary> /// Changes to the specified <see cref="WizardStep"/>. /// </summary> /// <param name="newStep">The step to go to.</param> /// <returns>True if the transition to the step succeeded. False if the step was not found or the operation was cancelled.</returns> public bool GoToStep (WizardStep newStep) { if (OnStepChanging (currentStep, newStep) || (newStep != null && !newStep.Enabled)) { return false; } // Hide all but the new step foreach (WizardStep step in steps) { step.Visible = (step == newStep); step.ShowHide (); } var oldStep = currentStep; currentStep = newStep; UpdateButtonsAndTitle (); // Set focus to the nav buttons if (backBtn.HasFocus) { backBtn.SetFocus (); } else { nextfinishBtn.SetFocus (); } if (OnStepChanged (oldStep, currentStep)) { // For correctness we do this, but it's meaningless because there's nothing to cancel return false; } return true; } private void UpdateButtonsAndTitle () { if (CurrentStep == null) return; base.Title = $"{wizardTitle}{(steps.Count > 0 ? " - " + CurrentStep.Title : string.Empty)}"; // Configure the Back button backBtn.Text = CurrentStep.BackButtonText != ustring.Empty ? CurrentStep.BackButtonText : Strings.wzBack; // "_Back"; backBtn.Visible = (CurrentStep != GetFirstStep ()); // Configure the Next/Finished button if (CurrentStep == GetLastStep ()) { nextfinishBtn.Text = CurrentStep.NextButtonText != ustring.Empty ? CurrentStep.NextButtonText : Strings.wzFinish; // "Fi_nish"; } else { nextfinishBtn.Text = CurrentStep.NextButtonText != ustring.Empty ? CurrentStep.NextButtonText : Strings.wzNext; // "_Next..."; } SizeStep (CurrentStep); SetNeedsLayout (); LayoutSubviews (); Redraw (Bounds); } private void SizeStep (WizardStep step) { if (Modal) { // If we're modal, then we expand the WizardStep so that the top and side // borders and not visible. The bottom border is the separator above the buttons. step.X = step.Y = -1; step.Height = Dim.Fill (1); // for button frame step.Width = Dim.Fill (-1); } else { // If we're not a modal, then we show the border around the WizardStep step.X = step.Y = 0; step.Height = Dim.Fill (1); // for button frame step.Width = Dim.Fill (0); } } /// <summary> /// Determines whether the <see cref="Wizard"/> is displayed as modal pop-up or not. /// /// The default is <c>true</c>. The Wizard will be shown with a frame with <see cref="Title"/> and will behave like /// any <see cref="Toplevel"/> window. /// /// If set to <c>false</c> the Wizard will have no frame and will behave like any embedded <see cref="View"/>. /// /// To use Wizard as an embedded View /// <list type="number"> /// <item><description>Set <see cref="Modal"/> to <c>false</c>.</description></item> /// <item><description>Add the Wizard to a containing view with <see cref="View.Add(View)"/>.</description></item> /// </list> /// /// If a non-Modal Wizard is added to the application after <see cref="Application.Run(Func{Exception, bool})"/> has been called /// the first step must be explicitly set by setting <see cref="CurrentStep"/> to <see cref="GetNextStep()"/>: /// <code> /// wizard.CurrentStep = wizard.GetNextStep(); /// </code> /// </summary> public new bool Modal { get => base.Modal; set { base.Modal = value; foreach (var step in steps) { SizeStep (step); } if (base.Modal) { ColorScheme = Colors.Dialog; Border.BorderStyle = BorderStyle.Rounded; Border.Effect3D = true; Border.DrawMarginFrame = true; } else { if (SuperView != null) { ColorScheme = SuperView.ColorScheme; } else { ColorScheme = Colors.Base; } CanFocus = true; Border.Effect3D = false; Border.BorderStyle = BorderStyle.None; Border.DrawMarginFrame = false; } } } } }
using Phenix.Business.Rules; namespace Phenix.Business.Core { #region Rules /// <summary> /// 申明业务规则注册中事件处理函数 /// </summary> /// <param name="businessRules">业务规则库</param> public delegate void BusinessRuleRegisteringEventHandler(Csla.Rules.BusinessRules businessRules); /// <summary> /// 申明授权规则注册中事件处理函数 /// </summary> /// <param name="authorizationRules">授权规则库</param> public delegate void AuthorizationRuleRegisteringEventHandler(AuthorizationRules authorizationRules); #endregion }
using System; using System.Collections.Generic; namespace EPI.HashTables { /// <summary> /// Test the Collatz conjecture for the first n positive integers. /// Collatz conjecture: Take any natural number. If it's odd, triple it and add one. /// If it's even, halve it. Repeat. No matter what number you choose, the sequence /// will converge to 1. /// NOTE: The conjecture has neither been proved or disproved. /// </summary> /// <example> /// 11 follows the sequence: {11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1} /// </example> public static class Collatz { // We test the conjecture on n by starting from 1 upto n. // The test fails if our sequence hits a loop. (circular reference) // The test throws (does not succeed) if we overflow. // To optimize: // When analyzing n for the Collatz conjecture, all <n numbers have already been evaluated. // We store any smaller that we know converges to 1 and if we hit those numbers, we stop. // Store only odd converged numbers < n. public static bool DoesNumberConvergeToOne(int n) { // store any previous numbers that we've processed HashSet<Int64> processedNumbers = new HashSet<Int64>(); processedNumbers.Add(1); // iterate from up to n and test the collatz conjecture on each number for (int i = 2; i <= n; i++) { HashSet<Int64> visited = new HashSet<Int64>(); Int64 current = Convert.ToInt64(i); while (current >= i) // stop if we reach a number below current (since those have already been processed and we haven't failed yet) { if (visited.Contains(current)) { // we entered a loop : hit a number that has already been visited in current sequence return false; //Collatz conjecture failed } visited.Add(current); // mark as visited if ((current & 1) == 1) // Odd number { if (processedNumbers.Contains(current)) { // current has already been processed (dont repeat work) break; } processedNumbers.Add(current); // mark as processed Int64 next = (3 * current) + 1; // next number if (next <= current) { // we expected a larger next number but didnt see it // this means we overflowed throw new OverflowException("Overflow"); } current = next; } else //even number { current /= 2; } } } // test hasn't failed and completed, return pass return true; } } }
// Forgot User Password public partial class DesktopModules_MemberForgotPassword_MemberForgotPassword : PortalModuleBase { protected void cmdSubmit_Click(object sender, EventArgs e) { try { DataTable dtUserDetails = DAL.getRow("", "Where = '" + DAL.safeSql(txtEmail.Text.Trim()) + "' AND = 1");//holds the users details //checks if the if the user is in the database and can login is in the database if (dtUserDetails.Rows.Count > 0) { //sends an email to the user with the link to reset their password General.sendHTMLMail(txtEmail.Text, "Your Request to Reset Your Password", string.Format(File.ReadAllText(Server.MapPath("~/EmailTemplate/ForgotPassword.html")), , dtUserDetails.Rows[0][""].ToString(), dtUserDetails.Rows[0][""].ToString())); //turn on the thank you message and removes the body panThankYou.Visible = true; panBody.Visible = false; }//end of if else throw new Exception("Email could not be found"); }//end of try catch (Exception ex) { lblError.Text = ex.Message; lblError.Visible = true; }//end of catch }//end of cmdLogin_Click() }//end of Module()
using Prism.Interactivity.InteractionRequest; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HabMap.ProjectConfigurations.Models { public class SelectCINotification : Confirmation, ISelectCINotification { public IClientInterfaceModel SelectedCI { get; set; } } }
using System.ComponentModel.DataAnnotations; using Alabo.Validations; namespace Alabo.Industry.Offline.Order.Domain.Dtos { /// <summary> /// MerchantCartInput /// </summary> public class MerchantCartInput { /// <summary> /// cart Id /// </summary> public string Id { get; set; } /// <summary> /// Merchant store id /// </summary> public string MerchantStoreId { get; set; } /// <summary> /// User id /// </summary> [Display(Name = "用户Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [Range(1, 99999999, ErrorMessage = ErrorMessage.NameNotCorrect)] public long UserId { get; set; } /// <summary> /// Merchant product id /// </summary> public string MerchantProductId { get; set; } /// <summary> /// SkuId /// </summary> [Display(Name = "SkuId")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public string SkuId { get; set; } /// <summary> /// Count /// </summary> [Display(Name = "数量")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public long Count { get; set; } } }
using UnityEngine; using System.Collections; enum CUT { NONE, CUT_DOWN, CUT_UP, CUT_RIGHT, CUT_LEFT } public enum MAP_GIMMIC { NONE, PLAYER, BLOCK, GOAL, MAGNET_S, MAGNET_N, APPEAR, DISAPPEAR } enum GIMMIC_CHECK { SandS, SandN } public class MapAction : MonoBehaviour { public static bool isStart; // オブジェクト情報 public GameObject player; public GameObject GimmicParticle; private GameObject PlayMainObj; // クローン用 private GameObject[] N_block = new GameObject[64]; private GameObject N_player; // テキストプレハブ public GameObject LabelPfb; // キー情報 private CUT cut_key; private CUT animation_key; private CUT before_key; // マップ情報 private MAP_GIMMIC[,] next_mapdata; public static int Map_X,Map_Y; private int next_Map_X,next_Map_Y; // マップ描画サイズ private float BUFF_L = (Screen.height-50)/8; private float BUFF_M = (Screen.height-20)/16; private float BUFF_S = (Screen.height-20)/32; private float buff; private float next_buff; private float buff_difference; // アニメーション前後のサイズの差 // 描画する際の中心座標 public static float CenterX,CenterY; // カメラオフじの初期化のため参照可能 private float CenterDiferenceX,CenterDiferenceY; // カメラ用座標 private Vector2 CameraMovePos; // アニメーションする歯車 public GameObject[] Gear = new GameObject[4]; // 各ギミックの数 public static int magnet_s_count; public static int magnet_n_count; public static int appear_count; public static int disappear_count; // ギミックの座標保存用 public static Vector2[] magnet_s_position; public static Vector2[] magnet_n_position; // アニメーション用メンバ変数 public static bool animation_flag; // プレイヤーから参照必要 private int animation_count; // 描画するかどうかのフラグ(外部から参照可能) public static bool draw_flag; public static bool player_draw_flag; private bool move_flag; // 切り取った回数 public static int Trouble; public UILabel trouble_number; // 二回呼び出さないために関数名変更 void MapStart (){ Destroy (PlayMainObj); // 親インスタンス生成 PlayMainObj = new GameObject(); PlayMainObj.transform.parent = transform; // サイズ調整 PlayMainObj.transform.localScale = new Vector3 (1,1,1); // 各種初期化 cut_key = CUT.NONE; buff = BUFF_L; move_flag = false; Trouble = 0; CenterX = CenterY = 0; Player.move_flag = false; Player.clear_flag = false; // マップ生成 for (int Y=0; Y<Map_Y; Y++) { for (int X=0; X<Map_X; X++) { N_block[Y*Map_Y+X] = Instantiate (player, transform.position, Quaternion.identity)as GameObject; N_block[Y*Map_Y+X].transform.parent = PlayMainObj.transform; } } // ギミック番号生成 for (int i=0; i<appear_count; i++) { Map_Input.appear[i].number = Instantiate (player, transform.position, Quaternion.identity)as GameObject; Map_Input.appear[i].number.transform.parent = PlayMainObj.transform; } for (int i=0; i<disappear_count; i++) { Map_Input.disappear[i].number = Instantiate (player, transform.position, Quaternion.identity)as GameObject; Map_Input.disappear[i].number.transform.parent = PlayMainObj.transform; } // プレイヤー生成 N_player = Instantiate (player, transform.position, Quaternion.identity)as GameObject; N_player.transform.parent = PlayMainObj.transform; // 初回描画 AppearGimmicAction (); Draw (); PlayerDraw (); // チュートリアルの確認 if (GameMemory.StagePage == 0 && GameMemory.StageGear == 0 && GameMemory.GuideFlag [1] == 0) { GameGuide.NowTutorial = TUTORIAL.STAGE1_1; GameMemory.GuideFlag [1] = 1; } if (GameMemory.StagePage == 0 && GameMemory.StageGear == 1 && GameMemory.GuideFlag [3] == 0) { GameGuide.NowTutorial = TUTORIAL.STAGE1_2; GameMemory.GuideFlag [3] = 1; } if (GameMemory.StagePage == 0 && GameMemory.StageGear == 2 && GameMemory.GuideFlag [5] == 0) { GameGuide.NowTutorial = TUTORIAL.STAGE1_3_1; GameMemory.GuideFlag [5] = 1; } // チュートリアルの表示 if (GameGuide.NowTutorial != TUTORIAL.NONE) GameMain.GuideFlag = true; } // Update is called once per frame void Update () { if (isStart) { MapStart (); isStart = false; } // リスタート時の処理 if (Setting.isRestart) { buff = BUFF_L; Trouble = 0; AppearGimmicAction (); Draw (); CameraAction.isStart = true; } // 更新制御 if (Setting.isSetting || GameGuide.isGuide || Fade.NowFade != FADE.FADE_NONE) return; if (Player.clear_flag && Fade.NowFade == FADE.FADE_OUT) return; // プレイヤーの動きを更新 move_flag = move_flag | Player.move_flag; // プレイヤーの移動などで画面が更新されたら描画しなおす if (player_draw_flag) PlayerDraw (); if (draw_flag) Draw (); // クリア判定 if(Player.clear_flag && Fade.NowFade == FADE.FADE_NONE) Fade.FadeRun(GAME_SCENE.RESULT); // カメラ操作 if (CameraAction.CameraOn) { GameCamera (); return; } // 入力取得 InputKey (); N_GimmickAction (); if(animation_flag) { // プレイヤーの位置調整を元に戻す Player.MoveDistance = 0; if(AnimationDraw(animation_key)) { Trouble++;//切った回数 animation_flag = false; Cut(); Create(next_Map_X, next_Map_Y, true); Copy(); AppearGimmicAction (); // 大きさを調整 if (Map_X == 8 || Map_Y == 8) buff = BUFF_L; if (Map_X == 16 || Map_Y == 16) buff = BUFF_M; if (Map_X == 32 || Map_Y == 32) buff = BUFF_S; Draw(); // ステージ1-3で上に切った時に追加でチュートリアル if(GameMemory.StagePage == 0 && GameMemory.StageGear == 2){ if (GameMemory.GuideFlag[6] == 0 && Trouble == 1) { GameGuide.NowTutorial = TUTORIAL.STAGE1_3_2; GameMemory.GuideFlag[6] = 1; GameMain.GuideFlag = true; } } } } else cut_key = CUT.NONE; before_key = animation_key; move_flag = false; } // 入力取得関数 void InputKey(){ cut_key = CUT.NONE; const int MapLimit = 2; // X軸Y軸の最小値 // スマホ用の入力取得 switch (TouchAction.swipe) { case SWIPE.NONE: cut_key = CUT.NONE; break; case SWIPE.SWIPE_DOWN: if (Map_X > MapLimit) cut_key = CUT.CUT_DOWN; break; case SWIPE.SWIPE_UP: if (Map_X > MapLimit) cut_key = CUT.CUT_UP; break; case SWIPE.SWIPE_RIGHT: if (Map_Y > MapLimit) cut_key = CUT.CUT_RIGHT; break; case SWIPE.SWIPE_LEFT: if (Map_Y > MapLimit) cut_key = CUT.CUT_LEFT; break; } // PC用の入力取得 if (Input.GetKey (KeyCode.W)) { if (Map_X > MapLimit) cut_key = CUT.CUT_UP; } if (Input.GetKey (KeyCode.A)) { if (Map_Y > MapLimit) cut_key = CUT.CUT_LEFT; } if (Input.GetKey (KeyCode.S)) { if (Map_X > MapLimit) cut_key = CUT.CUT_DOWN; } if (Input.GetKey (KeyCode.D)) { if (Map_Y > MapLimit) cut_key = CUT.CUT_RIGHT; } // 反発のギミックが稼働していたら元に戻す if (magnet_s_count > 0 && !animation_flag) { if (S_GimmickCheck ()) { // 隣り合っていた場合の元の状態に切りなおす処理 if (animation_key == CUT.CUT_DOWN) { cut_key = CUT.CUT_UP; } if (animation_key == CUT.CUT_UP) { cut_key = CUT.CUT_DOWN; } if (animation_key == CUT.CUT_LEFT) { cut_key = CUT.CUT_RIGHT; } if (animation_key == CUT.CUT_RIGHT) { cut_key = CUT.CUT_LEFT; } } } // チュートリアル中の操作制限 // ステージ1-1をクリアしていない時は切れない if (GameMemory.GuideFlag [2] == 0) cut_key = CUT.NONE; // ステージ1-2は左右にしか切れない if (GameMemory.StagePage == 0 && GameMemory.StageGear == 1 && GameMemory.GuideFlag [4] == 0){ if (cut_key == CUT.CUT_DOWN || cut_key == CUT.CUT_UP){ cut_key = CUT.NONE; } } // ステージ1-3は上にしか切れない if (GameMemory.StagePage == 0 && GameMemory.StageGear == 2 && GameMemory.GuideFlag [7] == 0){ if (cut_key == CUT.CUT_DOWN || cut_key == CUT.CUT_LEFT || cut_key == CUT.CUT_RIGHT){ cut_key = CUT.NONE; } // ランクを獲得してもらうために1回しか切れないようにする if(Trouble == 1) cut_key = CUT.NONE; } // 入力取得 if(cut_key != CUT.NONE && !animation_flag && !move_flag) { if(cut_key == CUT.CUT_DOWN || cut_key == CUT.CUT_UP) { // 次のマップの行列を計算 next_Map_Y = Map_X / 2; next_Map_X = Map_Y * 2; } else { if(cut_key == CUT.CUT_LEFT || cut_key == CUT.CUT_RIGHT) { // 次のマップの行列を計算 next_Map_Y = Map_X * 2; next_Map_X = Map_Y / 2; } } PlaySE.isPlayAnimation = true; animation_flag = true; animation_key = cut_key; // 切り取った後のブロックのサイズを次のマップのX軸Y軸の数で判定 if (next_Map_X == 8 || next_Map_Y == 8) next_buff = BUFF_L; if (next_Map_X == 16 || next_Map_Y == 16) next_buff = BUFF_M; if (next_Map_X == 32 || next_Map_Y == 32) next_buff = BUFF_S; // サイズの差を絶対値で保存 buff_difference = next_buff - buff; } } // mapdata描画 void Draw(){ int count = 0; int Scount = 0; int Ncount = 0; // 切り取った回数を更新 trouble_number.text = "" + Trouble; //配列の値を描画 for (int Y=Map_Y-1;Y>=0;Y--) { for(int X=0;X<Map_X;X++) { switch(Map_Input.mapdata[Y,X]) { case MAP_GIMMIC.NONE: N_block[count].GetComponent<UISprite> ().spriteName = "Space"; break; case MAP_GIMMIC.BLOCK: N_block[count].GetComponent<UISprite> ().spriteName = "Block"; break; case MAP_GIMMIC.GOAL: N_block[count].GetComponent<UISprite> ().spriteName = "Goal"; break; case MAP_GIMMIC.MAGNET_S: N_block[count].GetComponent<UISprite> ().spriteName = "Smagnet"; // 座標の保存 magnet_s_position[Scount].x = X; magnet_s_position[Scount].y = Y; Scount++; break; case MAP_GIMMIC.MAGNET_N: N_block[count].GetComponent<UISprite> ().spriteName = "Nmagnet"; // 座標の保存 magnet_n_position[Ncount].x = X; magnet_n_position[Ncount].y = Y; Ncount++; break; case MAP_GIMMIC.APPEAR: N_block[count].GetComponent<UISprite> ().spriteName = "appear"; break; case MAP_GIMMIC.DISAPPEAR: N_block[count].GetComponent<UISprite> ().spriteName = "disapper"; break; } // 大きさと位置調整 N_block[count].transform.localScale = new Vector3(buff,buff,1); N_block[count].transform.localPosition = new Vector3((X-Map_X/2)*buff+buff/2-CenterX, (Y-Map_Y/2)*buff+buff/2-CenterY, 0); count++; } } for (int i=0; i<appear_count; i++) { Map_Input.appear[i].number.transform.localScale = new Vector3(buff,buff,1); Map_Input.appear[i].number.transform.localPosition = new Vector3((Map_Input.appear[i].X-Map_X/2)*buff+buff/2-CenterX, (Map_Input.appear[i].Y-Map_Y/2)*buff+buff/2-CenterY, 0); Map_Input.appear[i].number.transform.eulerAngles = new Vector3(0,0,0); } for (int i=0; i<disappear_count; i++) { Map_Input.disappear[i].number.transform.localScale = new Vector3(buff,buff,1); Map_Input.disappear[i].number.transform.localPosition = new Vector3((Map_Input.disappear[i].X-Map_X/2)*buff+buff/2-CenterX, (Map_Input.disappear[i].Y-Map_Y/2)*buff+buff/2-CenterY, 0); Map_Input.disappear[i].number.transform.eulerAngles = new Vector3(0,0,0); } draw_flag = false; // マップ更新後にプレイヤーも描画 player_draw_flag = true; } void PlayerDraw(){ // 隣のブロックとのX軸の差を計算 float distance = Mathf.Abs(((0 - Map_X / 2) * buff + buff / 2 - CenterX) - ((1 - Map_X / 2) * buff + buff / 2 - CenterX)); N_player.transform.localScale = new Vector3(buff,buff,1); N_player.transform.localPosition = new Vector3((Player.X-Map_X/2)*buff+buff/2-CenterX + distance*Player.MoveDistance, (Player.Y-Map_Y/2)*buff+buff/2-CenterY, -1); N_player.transform.eulerAngles = new Vector3 (0, 0, Player.angle); player_draw_flag = false; } // マップ切り取り処理 void Cut(){ int next_countx = 0; int next_county = 0; // 各ギミックを一度だけ更新するためのフラグ bool player_update = false; bool[] appear_update = new bool[appear_count]; bool[] disappear_update = new bool[disappear_count]; switch (animation_key) { //------------------ // 下に向かって切った時 //------------------ case CUT.CUT_DOWN: // 次のマップの行列を計算 next_Map_Y = Map_X / 2; next_Map_X = Map_Y * 2; // 新マップの生成 Create(next_Map_X,next_Map_Y,false); for (int i = 0; i<Map_X/2; i++) { // 切った後の列読み込み下から上に読み込み for (int y = Map_Y - 1; y >= 0; y--) { next_mapdata[i,next_countx] = Map_Input.mapdata[y,i]; // プレイヤーの位置更新 if(i == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = i; player_update = true; } // ギミック確認 if(Map_Input.mapdata[y,i] == MAP_GIMMIC.APPEAR){ for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if((i == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = i; appear_update[j] = true; } } } } if(Map_Input.mapdata[y,i] == MAP_GIMMIC.DISAPPEAR){ for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if((i == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = i; disappear_update[j] = true; } } } } next_countx++; } // 切った後の列読み込み上から下に読み込み for (int y = 0; y<Map_Y; y++) { next_mapdata[i,next_countx] = Map_Input.mapdata[y,Map_X-1-i]; // プレイヤーの位置更新 if(Map_X-1-i == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = i; player_update = true; } // ギミック確認 if(Map_Input.mapdata[y,Map_X-1-i] == MAP_GIMMIC.APPEAR){ for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if((Map_X-1-i == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = i; appear_update[j] = true; } } } } if(Map_Input.mapdata[y,Map_X-1-i] == MAP_GIMMIC.DISAPPEAR){ for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if((Map_X-1-i == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = i; disappear_update[j] = true; } } } } next_countx++; } next_countx = 0; } break; //------------------ // 上に向かって切った時 //------------------ case CUT.CUT_UP: // 次のマップの行列を計算 next_Map_Y = Map_X / 2; next_Map_X = Map_Y * 2; // 新マップの生成 Create(next_Map_X,next_Map_Y,false); for (int i = 0; i<Map_X/2 ; i++) { // 切った後の列読み込み上から下に読み込み for (int y = 0; y<Map_Y; y++) { next_mapdata[i,next_countx] = Map_Input.mapdata[y,(Map_X / 2) - 1 - i]; // プレイヤーの位置更新 if((Map_X / 2) - 1 - i == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = i; player_update = true; } // ギミック確認 switch(Map_Input.mapdata[y,(Map_X / 2) - 1 - i]) { case MAP_GIMMIC.APPEAR: for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if(((Map_X / 2) - 1 - i == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = i; appear_update[j] = true; } } } break; case MAP_GIMMIC.DISAPPEAR: for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if(((Map_X / 2) - 1 - i == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = i; disappear_update[j] = true; } } } break; } next_countx++; } // 切った後の列読み込み下から上に読み込み for (int y = Map_Y - 1; y >= 0; y--) { next_mapdata[i,next_countx] = Map_Input.mapdata[y,(Map_X / 2) + i]; // プレイヤーの位置更新 if((Map_X / 2) + i == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = i; player_update = true; } // ギミック確認 switch(Map_Input.mapdata[y,(Map_X / 2) + i]) { case MAP_GIMMIC.APPEAR: for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if(((Map_X / 2) + i == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = i; appear_update[j] = true; } } } break; case MAP_GIMMIC.DISAPPEAR: for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if(((Map_X / 2) + i == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = i; disappear_update[j] = true; } } } break; } next_countx++; } next_countx = 0; } break; //------------------ // 右に向かって切った時 //------------------ case CUT.CUT_RIGHT: // 次のマップの行列を計算 next_Map_Y = Map_X * 2; next_Map_X = Map_Y / 2; // 新マップの生成 Create(next_Map_X,next_Map_Y,false); for (int x = 0; x<Map_X; x++) { // 切った後の列読み込み(中央上から右に読み込み) for (int y = (Map_Y / 2)-1; y >= 0; y--) { next_mapdata[next_county,next_countx] = Map_Input.mapdata[y,x]; // プレイヤーの位置更新 if(x == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = next_county; player_update = true; } // ギミック確認 switch(Map_Input.mapdata[y,x]) { case MAP_GIMMIC.APPEAR: for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if((x == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = next_county; appear_update[j] = true; } } } break; case MAP_GIMMIC.DISAPPEAR: for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if((x == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = next_county; disappear_update[j] = true; } } } break; } next_countx++; } next_county++; next_countx = 0; } for (int x = Map_X - 1; x >= 0; x--) { // 切った後の列読み込み(中央下から左に読み込み) for (int y = (Map_Y / 2); y<Map_Y; y++) { next_mapdata[next_county,next_countx] = Map_Input.mapdata[y,x]; // プレイヤーの位置更新 if(x == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = next_county; player_update = true; } // ギミック確認 switch(Map_Input.mapdata[y,x]) { case MAP_GIMMIC.APPEAR: for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if((x == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = next_county; appear_update[j] = true; } } } break; case MAP_GIMMIC.DISAPPEAR: for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if((x == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = next_county; disappear_update[j] = true; } } } break; } next_countx++; } next_county++; next_countx = 0; } break; //------------------ // 左に向かって切った時 //------------------ case CUT.CUT_LEFT: // 次のマップの行列を計算 next_Map_Y = Map_X * 2; next_Map_X = Map_Y / 2; // 新マップの生成 Create(next_Map_X,next_Map_Y,false); for (int x = Map_X - 1; x >= 0; x--) { // 切った後の列読み込み(中央上から左に読み込み) for (int y = 0; y<(Map_Y / 2); y++) { next_mapdata[next_county,next_countx] = Map_Input.mapdata[y,x]; // プレイヤーの位置更新 if(x == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = next_county; player_update = true; } // ギミック確認 switch(Map_Input.mapdata[y,x]) { case MAP_GIMMIC.APPEAR: for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if((x == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = next_county; appear_update[j] = true; } } } break; case MAP_GIMMIC.DISAPPEAR: for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if((x == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = next_county; disappear_update[j] = true; } } } break; } next_countx++; } next_county++; next_countx = 0; } for (int x = 0; x<Map_X; x++) { // 切った後の列読み込み(中央下から右に読み込み) for (int y = Map_Y-1; y>=(Map_Y / 2); y--) { next_mapdata[next_county,next_countx] = Map_Input.mapdata[y,x]; // プレイヤーの位置更新 if(x == Player.X && y == Player.Y && !player_update){ Player.X = next_countx; Player.Y = next_county; player_update = true; } // ギミック確認 switch(Map_Input.mapdata[y,x]) { case MAP_GIMMIC.APPEAR: for(int j=0;j<appear_count;j++){ if(!appear_update[j]){ if((x == Map_Input.appear[j].X) && (y == Map_Input.appear[j].Y)){ Map_Input.appear[j].X = next_countx; Map_Input.appear[j].Y = next_county; appear_update[j] = true; } } } break; case MAP_GIMMIC.DISAPPEAR: for(int j=0;j<disappear_count;j++){ if(!disappear_update[j]){ if((x == Map_Input.disappear[j].X) && (y == Map_Input.disappear[j].Y)){ Map_Input.disappear[j].X = next_countx; Map_Input.disappear[j].Y = next_county; disappear_update[j] = true; } } } break; } next_countx++; } next_county++; next_countx = 0; } break; } } // mapdata(next_mapdata)の生成 void Create(int x, int y, bool map_flag){ // TRUEの場合mapdataを作成 if (map_flag) { Map_Y = y; Map_X = x; Map_Input.mapdata = new MAP_GIMMIC [Map_Y,Map_X]; } else { next_Map_Y = y; next_Map_X = x; next_mapdata = new MAP_GIMMIC [next_Map_Y,next_Map_X]; } } // mapdataにnext_mapdataをコピー void Copy() { for (int y = 0; y<Map_Y; y++) { for (int x = 0; x<Map_X; x++) { Map_Input.mapdata[y,x] = next_mapdata[y,x]; } } } /*------------------------------------*/ // アニメーション /*------------------------------------*/ // 切り取った後のアニメーション描画関数 bool AnimationDraw(CUT key) { // 座標 float posX = 0; float posY = 0; // アニメーション中の位置調節用変数 float adjust_x = 0; float adjust_y = 0; // マップを切る時の支点 float pivot_x = 0; float pivot_y = 0; // 角度 float rot = 0; // アニメーションが終わる角度(演算に使う為 float ) const float MAX_ROT = 90; // 円周率 const double PI = 3.141592653589793; // アニメーションの速度(大きいほど遅い) const float ANIMATION_SPEED = 3; animation_count++; // 歯車のアニメーション Gear[0].transform.eulerAngles += new Vector3 (0, 0, 0.5f); Gear[1].transform.eulerAngles += new Vector3 (0, 0, -0.665f); Gear[2].transform.eulerAngles += new Vector3 (0, 0, 0.5f); Gear[3].transform.eulerAngles += new Vector3 (0, 0, -0.5f); // 徐々に大きさを変える処理 buff += buff_difference/(MAX_ROT/ANIMATION_SPEED); // 徐々に中心を元に戻す処理 if (CenterX != 0) { CenterX -= CenterDiferenceX /(MAX_ROT/ANIMATION_SPEED); if(Mathf.Abs(CenterX) < buff) CenterX = 0; } if (CenterY != 0) { CenterY -= CenterDiferenceY /(MAX_ROT/ANIMATION_SPEED); if(Mathf.Abs(CenterY) < buff) CenterY = 0; } // 支点と移動距離を確定 switch(key) { case CUT.CUT_DOWN: // 上から下 pivot_x = -buff/2; pivot_y = -(Map_Y*buff/2+buff/2); adjust_y = (next_Map_Y/2+Map_Y/2)/MAX_ROT*buff; break; case CUT.CUT_UP: // 下から上 pivot_x = -buff/2; pivot_y = Map_Y*buff/2-buff/2; adjust_y = -(next_Map_Y/2+Map_Y/2)/MAX_ROT*buff; break; case CUT.CUT_RIGHT: // 左から右 pivot_x = Map_X*buff/2-buff/2; pivot_y = -buff/2; adjust_x = -(next_Map_X/2+Map_X/2)/MAX_ROT*buff; break; case CUT.CUT_LEFT: // 右から左 pivot_x = -(Map_X*buff/2+buff/2); pivot_y = -buff/2; adjust_x = (next_Map_X/2+Map_X/2)/MAX_ROT*buff; break; } // クローン操作用変数 int count = 0; for (int Y = Map_Y-1; Y >= 0; Y--) { for (int X = 0; X < Map_X; X++) { // 傾く方向の確定 switch(key) { case CUT.CUT_DOWN: // 上から下 if(X < Map_X/2) rot = animation_count*ANIMATION_SPEED; else rot = -animation_count*ANIMATION_SPEED; break; case CUT.CUT_UP: // 下から上 if(X < Map_X/2) rot = -animation_count*ANIMATION_SPEED; else rot = animation_count*ANIMATION_SPEED; break; case CUT.CUT_RIGHT: // 左から右 if(Y < Map_Y/2) rot = animation_count*ANIMATION_SPEED; else rot = -animation_count*ANIMATION_SPEED; break; case CUT.CUT_LEFT: // 右から左 if(Y < Map_Y/2) rot = -animation_count*ANIMATION_SPEED; else rot = animation_count*ANIMATION_SPEED; break; } // 角度をラジアンに変換 float radian = (float)(rot * PI / 180.0); // アニメーション中の座標に変換 posX = ((X-Map_X/2)*buff - pivot_x) * Mathf.Cos(radian) - ((Y-Map_Y/2)*buff - pivot_y) * Mathf.Sin(radian) + pivot_x; posY = ((X-Map_X/2)*buff - pivot_x) * Mathf.Sin(radian) + ((Y-Map_Y/2)*buff - pivot_y) * Mathf.Cos(radian) + pivot_y; // ギミックのアニメーション if(Map_Input.mapdata[Y,X] == MAP_GIMMIC.APPEAR){ for (int i=0; i<MapAction.appear_count; i++) { if(Map_Input.appear[i].X == X && Map_Input.appear[i].Y == Y){ Map_Input.appear[i].number.transform.localPosition = new Vector3(posX+(adjust_x*animation_count*ANIMATION_SPEED)+buff/2, posY+(adjust_y*animation_count*ANIMATION_SPEED)+buff/2, -1); Map_Input.appear[i].number.transform.localScale = new Vector3(buff,buff,1); Map_Input.appear[i].number.transform.eulerAngles = new Vector3(0,0,rot); } } } if(Map_Input.mapdata[Y,X] == MAP_GIMMIC.DISAPPEAR){ for (int i=0; i<MapAction.disappear_count; i++) { if(Map_Input.disappear[i].X == X && Map_Input.disappear[i].Y == Y){ Map_Input.disappear[i].number.transform.localPosition = new Vector3(posX+(adjust_x*animation_count*ANIMATION_SPEED)+buff/2, posY+(adjust_y*animation_count*ANIMATION_SPEED)+buff/2, -1); Map_Input.disappear[i].number.transform.localScale = new Vector3(buff,buff,1); Map_Input.disappear[i].number.transform.eulerAngles = new Vector3(0,0,rot); } } } // プレイヤーのアニメーション if(X == Player.X && Y == Player.Y){ N_player.transform.localPosition = new Vector3(posX+(adjust_x*animation_count*ANIMATION_SPEED)+buff/2, posY+(adjust_y*animation_count*ANIMATION_SPEED)+buff/2, -1); N_player.transform.localScale = new Vector3(buff,buff,1); N_player.transform.eulerAngles = new Vector3(0,0,Player.angle+rot); } N_block[count].transform.localPosition = new Vector3(posX+(adjust_x*animation_count*ANIMATION_SPEED)+buff/2, posY+(adjust_y*animation_count*ANIMATION_SPEED)+buff/2, -1); N_block[count].transform.localScale = new Vector3(buff,buff,1); N_block[count].transform.eulerAngles = new Vector3(0,0,rot); count++; } } player_draw_flag = false; if(animation_count*ANIMATION_SPEED >= MAX_ROT) { // カウントリセット animation_count = 0; Player.angle -= rot; // アニメーションが終わると終了 return true; } // アニメーションが終わっていないので繰り返し return false; } // S磁石のギミックチェック public static bool S_GimmickCheck(){ // S極とS極の判定(隣り合っていればtrue) for(int i=0;i<magnet_s_count-1;i++){ for(int j=i+1;j<magnet_s_count;j++){ if((magnet_s_position[i].x == magnet_s_position[j].x && Mathf.Abs(magnet_s_position[i].y-magnet_s_position[j].y) == 1) || (magnet_s_position[i].y == magnet_s_position[j].y && Mathf.Abs(magnet_s_position[i].x-magnet_s_position[j].x) == 1)) return true; } } return false; } // N磁石のギミックチェック void N_GimmickAction(){ int isHit = 0; // S極とN極の判定 for (int i=0;i<magnet_n_count;i++) { for(int j=0; j<magnet_s_count; j++){ // S極と隣り合っていないか if((magnet_n_position[i].x == magnet_s_position[j].x && Mathf.Abs(magnet_n_position[i].y - magnet_s_position[j].y) == 1) || (magnet_n_position[i].y == magnet_s_position[j].y && Mathf.Abs(magnet_n_position[i].x - magnet_s_position[j].x) == 1)){ isHit++; } } // 下に何もないか if(magnet_n_position[i].y > 0 && isHit == 0){ if (Map_Input.mapdata [(int)magnet_n_position[i].y - 1, (int)magnet_n_position[i].x] == MAP_GIMMIC.NONE){ draw_flag = true; move_flag = true; Map_Input.mapdata [(int)magnet_n_position[i].y - 1, (int)magnet_n_position[i].x] = MAP_GIMMIC.MAGNET_N; Map_Input.mapdata [(int)magnet_n_position[i].y, (int)magnet_n_position[i].x] = MAP_GIMMIC.NONE; } } isHit = 0; } } // 現れる/消えるブロックのギミックチェック void AppearGimmicAction(){ int X, Y; // 時間経過で現れるブロックの処理 for (int i=0; i<MapAction.appear_count; i++) { if(Map_Input.appear[i].trouble <= Trouble){ Map_Input.appear[i].number.SetActive(false); if(Map_Input.appear[i].X >= 0 && Map_Input.appear[i].Y >= 0){ X = Map_Input.appear[i].X; Y = Map_Input.appear[i].Y; if(Map_Input.mapdata[Y,X] == MAP_GIMMIC.APPEAR){ Map_Input.mapdata[Y,X] = MAP_GIMMIC.BLOCK; // 使われないようにしておく Map_Input.appear[i].X = Map_Input.appear[i].Y = -1; if(GimmicParticle.particleSystem.isStopped) GimmicParticle.particleSystem.Play(); PlaySE.isPlayGimmic = true; } } } else{ Map_Input.appear[i].number.SetActive(true); Map_Input.appear[i].number.GetComponent<UISprite> ().spriteName = "Number" + (Map_Input.appear[i].trouble-Trouble); } } // 時間経過で消えるブロックの処理 for (int i=0; i<MapAction.disappear_count; i++) { if(Map_Input.disappear[i].trouble <= Trouble){ Map_Input.disappear[i].number.SetActive(false); if(Map_Input.disappear[i].X >= 0 && Map_Input.disappear[i].Y >= 0){ X = Map_Input.disappear[i].X; Y = Map_Input.disappear[i].Y; if(Map_Input.mapdata[Y,X] == MAP_GIMMIC.DISAPPEAR){ Map_Input.mapdata[Y,X] = MAP_GIMMIC.NONE; // 使われないようにしておく Map_Input.disappear[i].X = Map_Input.disappear[i].Y = -1; if(GimmicParticle.particleSystem.isStopped) GimmicParticle.particleSystem.Play(); PlaySE.isPlayGimmic = true; } } } else{ Map_Input.disappear[i].number.SetActive(true); Map_Input.disappear[i].number.GetComponent<UISprite> ().spriteName = "Number" + (Map_Input.disappear[i].trouble-Trouble); } } } // カメラ操作 void GameCamera(){ // カメラ移動処理 if (Input.touchCount == 1) { CenterX += CameraMovePos.x-TouchAction.direction[0].x; CenterY += CameraMovePos.y-TouchAction.direction[0].y; draw_flag = true; } CameraMovePos.x = (int)TouchAction.direction [0].x; CameraMovePos.y = (int)TouchAction.direction [0].y; // ズーム処理 if (Input.GetKey (KeyCode.Z)) { buff++; draw_flag = true; } if (TouchAction.zoom != ZOOM.NONE) { if(TouchAction.zoom == ZOOM.ZOOM_IN && buff < BUFF_L) buff++; if(TouchAction.zoom == ZOOM.ZOOM_OUT && buff > BUFF_S) buff--; draw_flag = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using System.Net; using System.ServiceModel.Channels; using System.ServiceModel; using Common.DataModel; using System.ComponentModel; using Common.Utils; using System.Windows; using System.Windows.Navigation; using System.Diagnostics; using Microsoft.Phone.Controls; using Client_WinPhone.FeedService; using Client_WinPhone.View; namespace Client_WinPhone.ViewModel { public class FeedsPageViewModel : BindableObject { private FeedManagerDataModel FeedsManager { get; set; } #region properties public ICommand RefreshFeed { get; private set; } public ICommand RefreshFeeds { get; private set; } public ICommand AddFeed { get; private set; } public ICommand RemoveFeed { get; private set; } public ICommand LoadFeedItems { get; private set; } public ICommand OpenFeedDetails { get; private set; } public ICommand LogOut { get; private set; } private List<Channel> channels = null; public List<Channel> Channels { get { return channels; } private set { channels = value; RaisePropertyChange("Channels"); } } private List<Channel> allChannels = null; public List<Channel> AllChannels { get { return allChannels; } private set { allChannels = value; RaisePropertyChange("AllChannels"); } } private List<Item> items = null; public List<Item> Items { get { return items; } private set { items = value; RaisePropertyChange("Items"); } } private string urlFeed = ""; public string UrlFeed { get { return urlFeed; } set { urlFeed = value; RaisePropertyChange("UrlFeed"); } } private Channel currentChannel = null; public Channel CurrentChannel { get { return currentChannel; } set { currentChannel = value; RaisePropertyChange("CurrentChannel"); } } #endregion #region CTor public FeedsPageViewModel() { FeedsManager = FeedManagerDataModel.Instance; FeedsManager.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(FeedsManager_PropertyChanged); RefreshFeeds = new RelayCommand((param) => FeedsManager.GetAllRootFeeds()); RefreshFeed = new RelayCommand((param) => FeedsManager.RefreshFeed(param as Channel)); AddFeed = new RelayCommand((param) => AddFeedBody(param as string)); RemoveFeed = new RelayCommand((param) => FeedsManager.RemoveFeed(param as Channel)); LoadFeedItems = new RelayCommand((param) => FeedsManager.LoadFeedItems(param as Channel)); /*OpenFeedDetails = new RelayCommand((param) => (new ChannelFeedsPage() { DataContext = new FeedDetailsViewModel(param as Channel) }));*/ OpenFeedDetails = new RelayCommand((param) => OpenDetails(param as Channel)); //LogOut = new RelayCommand((param) => Logout(param as string[])); PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual; bool success = frame.Navigate(new Uri("/View/DetailedFeedsPage.xaml", UriKind.Relative)); Channels = new List<Channel>(); FeedsManager.GetAllRootFeeds(); SearchDataModel.Instance.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Instance_PropertyChanged); } void Instance_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case "Search": SearchDataModel searchInstance = (sender as SearchDataModel); string searchValue = searchInstance.Search; if (searchInstance.IsSearchValue(searchValue)) { AllChannels = (from chan in FeedManagerDataModel.Instance.AllChannels where chan.Title.Contains(searchValue, StringComparison.OrdinalIgnoreCase) select chan).ToList(); Channels = (from chan in FeedManagerDataModel.Instance.Channels where chan.Title.Contains(searchValue) select chan).ToList(); } else { AllChannels = FeedManagerDataModel.Instance.AllChannels; Channels = FeedManagerDataModel.Instance.Channels; } break; } } #endregion private void OpenDetails(Channel param) { Debug.WriteLine("Opening : "); new ChannelFeedsPage() { DataContext = new FeedDetailsViewModel(param) }; PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual; bool success = frame.Navigate(new Uri("/View/DetailedFeedsPage.xaml", UriKind.Relative)); } void FeedsManager_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "Channels") { Channels = (sender as FeedManagerDataModel).Channels; } else if (e.PropertyName == "Items") Items = (sender as FeedManagerDataModel).Items; else if (e.PropertyName == "AllChannels") AllChannels = (sender as FeedManagerDataModel).AllChannels; } private void AddFeedBody(string url) { FeedsManager.AddNewFeed(url); } private void Logout(object sender, EventArgs e) { UserDataModel.Instance.Logout(); PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual; //bool success = frame.Navigate(new Uri("/View/LogInPage.xaml", UriKind.Relative)); frame.GoBack(); } } }
using System.Collections; using System.Collections.Generic; using System.Threading; using Framework.Core.Common; using Framework.Core.Config; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Oberon.Tenant { public class TenantCreate : TenantBasePage { #region Page Objects public static string Url = AppConfig.OberonBaseUrl + "/Tenant/Create/"; public IWebElement LoginId { get { return _driver.FindElement(By.CssSelector("#Name")); } } public IWebElement DisplayName { get { return _driver.FindElement(By.CssSelector("#DisplayName")); } } public IWebElement VanVoterFileApiKey { get { return _driver.FindElement(By.CssSelector("#VANVoterFileAPIKey")); } } public IWebElement VanMyCampaignApiKey { get { return _driver.FindElement(By.CssSelector("#VANMyCampaignAPIKey")); } } public IWebElement AddDesignationLink { get { return _driver.FindElement(By.CssSelector("#AddDesignation")); } } public IWebElement DesignationsList { get { return _driver.FindElement(By.CssSelector("#DesignationList")); } } public IWebElement DesignationsName { get { return _driver.FindElement(By.CssSelector("#Designations___Name")); } } public IWebElement DesignationsReportName { get { return _driver.FindElement(By.CssSelector("#Designations___ShortName")); } } public IWebElement DesignationsDisclosureReportId { get { return _driver.FindElement(By.CssSelector("#Designations___DisclosureReportId")); } } public IWebElement DesignationsCommitteeId { get { return _driver.FindElement(By.CssSelector("#Designations___CommitteeId")); } } public IWebElement PaymentGatewayName { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.PaymentGatewayName']/following::input")); } } public IWebElement PaymentMethod { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.PaymentMethod']/following::select")); } } public IWebElement PaymentGateway { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.GatewayTypeId']/following::select")); } } public IWebElement PaymentApiPartner { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.ApiPartner']/following::input")); } } public IWebElement PaymentApiUser { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.ApiUser']/following::input")); } } public IWebElement PaymentApiMerchant { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.ApiMerchant']/following::input")); } } public IWebElement PaymentApiPassword { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.ApiPassword']/following::input")); } } public IWebElement PaymentGatewayActive { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.IsActive']/following::input")); } } public IWebElement ApiTestButton { get { return _driver.FindElement(By.XPath("//label[@for='Designations.PaymentGateway.Action']/following::button")); } } public IWebElement ValidationHeader { get { return _driver.FindElement(By.CssSelector(".validationHeader")); } } public IWebElement InfoMessageContainerError { get { return _driver.FindElement(By.CssSelector(".alert.infoMessageContainer.error")); } } public IWebElement InfoMessageContainerSuccess { get { return _driver.FindElement(By.CssSelector(".alert.infoMessageContainer.success")); } } public IWebElement PaymentGatewayValidationMessage { get { return _driver.FindElement(By.XPath("//p[@class='validationHeader' and text()=('Payment Gateway Test Successful.')]")); } } public IWebElement AccountCreationValidationMessage { get { return _driver.FindElement(By.XPath("//p[@class='validationHeader' and text()=('Account creation was successful.')]")); } } //public IWebElement PlaceholderElement { get { return _driver.FindElement(By.XPath("//input[@value='Save']")); } } //public IWebElement SaveButton; public IWebElement ApiKey { get { return _driver.FindElement(By.XPath("//code[@class='apiKey']")); } } #endregion public TenantCreate(Driver driver) : base(driver) { } #region Methods /// <summary> /// navigates direclty to tenant create page via url /// </summary> public void GoToThisPageDirectly() { _driver.GoToPage(Url); } /// <summary> /// sets tenant id /// </summary> public void SetTenantId(string id) { LoginId.SendKeys(id); } /// <summary> /// sets display name /// </summary> public void SetDisplayName(string displayName) { DisplayName.SendKeys(displayName); } /// <summary> /// sets van voter file api key /// </summary> public void SetVanVoterFileApiKey(string apiKey) { VanVoterFileApiKey.SendKeys(apiKey); } /// <summary> /// sets van my campgaign file api key /// </summary> public void SetVanMyCampaignApiKey(string apiKey) { VanMyCampaignApiKey.SendKeys(apiKey); } /// <summary> /// adds Oberon report designation /// </summary> public void AddDesignationDetail() { _driver.SendKeys(DesignationsName, "Oberon"); _driver.SendKeys(DesignationsReportName, "Lefty4NY"); _driver.SendKeys(DesignationsDisclosureReportId, "Oberon Report"); _driver.SendKeys(DesignationsCommitteeId, "CP09234A"); _driver.Click(AddDesignationLink); //SelectDesignation(1); _driver.SendKeys(DesignationsName, "NY"); _driver.SendKeys(DesignationsReportName, "Lefty4NY"); _driver.SendKeys(DesignationsDisclosureReportId, "NY State Candidate Disclosure Report"); _driver.SendKeys(DesignationsCommitteeId, "CPA09234"); } /// <summary> /// adds Verisign payment gateway /// </summary> public void AddPaymentGateway() { _driver.SendKeys(PaymentGatewayName, "GatewayName"); _driver.SelectOptionByText(PaymentGateway, "PayPalPayFlowPro"); _driver.ClearAndTab(PaymentApiPartner); _driver.SendKeys(PaymentApiPartner, "Verisign"); _driver.SendKeys(PaymentApiUser, "jaimanalwar1"); _driver.SendKeys(PaymentApiMerchant, "jaimanalwar1"); _driver.SendKeys(PaymentApiPassword, "Password321!"); _driver.Click(PaymentGatewayActive); _driver.Click(ApiTestButton); } /// <summary> /// gets tenant id by parsing the url /// </summary> public string GetTenantId() { string url = _driver.GetUrl(); string[] urlSplit = url.Split('/'); return urlSplit[urlSplit.Length-1]; } /// <summary> /// creates tenant from arguments, returns api key /// </summary> public string CreateTenant(string id, string displayName, string[] features, string vanVoterFileApiKey, string vanMyCampaignApiKey) { _driver.SendKeys(LoginId, id); _driver.SendKeys(DisplayName, displayName); SetFeatures(features); _driver.SendKeys(VanVoterFileApiKey, vanVoterFileApiKey); _driver.SendKeys(VanMyCampaignApiKey, vanMyCampaignApiKey); AddDesignationDetail(); AddPaymentGateway(); ClickSaveButton(); _driver.IsElementPresent(InfoMessageContainerSuccess); if (_driver.IsElementPresent(InfoMessageContainerSuccess)) { _driver.IsElementPresent(AccountCreationValidationMessage); } //string tenantID = GetTenantId(); return ApiKey.Text; } #endregion } }
using UnityEngine; using System.Collections; public class ZhuJiaoNv : MonoBehaviour { float CenterPerPx = 0.3f; int PosX_1; int PosX_2; public static bool FireRight; public static bool FireLeft; public static bool IsFire; bool Fail; bool Win_1; bool Win_2; Animator AnimatorCom; bool IsFireOtherPort; static ZhuJiaoNv _Instance; public static ZhuJiaoNv GetInstance() { return _Instance; } // Use this for initialization void Start() { _Instance = this; CenterPerPx = GameCtrlXK.GetInstance().ZhuJiaoNvCenterPerPx; AnimatorCom = GetComponent<Animator>(); } // Update is called once per frame void Update() { if (Fail || Win_1 || Win_2) { return; } if (IsFire) { PosX_1 = (int)(608f * (1f - CenterPerPx)); PosX_2 = (int)(608f * (1f + CenterPerPx)); if (pcvr.CrossPosition.x < PosX_1) { if (!FireLeft) { FireLeft = true; FireRight = false; AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", true); } } else if (pcvr.CrossPosition.x > PosX_2) { if (!FireRight) { FireLeft = false; FireRight = true; AnimatorCom.SetBool("FireRight", true); AnimatorCom.SetBool("FireLeft", false); } } else { if (FireRight || FireLeft) { FireLeft = false; FireRight = false; AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", false); } } } } public void OpenFireOtherPort() { if (IsFireOtherPort) { return; } IsFireOtherPort = true; AnimatorCom.SetBool("IsFire", true); AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", false); } public void CloseFireOtherPort() { if (!IsFireOtherPort) { return; } IsFireOtherPort = false; AnimatorCom.SetBool("IsFire", false); AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", false); } public void UpdateZhuJiaoNvFireAction(float crossPx) { if (Fail || Win_1 || Win_2) { return; } if (!IsFireOtherPort) { return; } PosX_1 = (int)(608f * (1f - CenterPerPx)); PosX_2 = (int)(608f * (1f + CenterPerPx)); if (crossPx < PosX_1) { if (!FireLeft) { FireLeft = true; FireRight = false; AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", true); } } else if (crossPx > PosX_2) { if (!FireRight) { FireLeft = false; FireRight = true; AnimatorCom.SetBool("FireRight", true); AnimatorCom.SetBool("FireLeft", false); } } else { if (FireRight || FireLeft) { FireLeft = false; FireRight = false; AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", false); } } } public void OpenFire() { if (IsFire) { return; } IsFire = true; AnimatorCom.SetBool("IsFire", true); AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", false); } public void CloseFire() { if (!IsFire) { return; } IsFire = false; AnimatorCom.SetBool("IsFire", false); AnimatorCom.SetBool("FireRight", false); AnimatorCom.SetBool("FireLeft", false); } public void PlayFailAction() { Fail = true; AnimatorCom.SetBool("Fail", true); CloseFire(); } public void PlayWinAction(int key) { if (key == 1) { Win_1 = true; AnimatorCom.SetBool("Win_1", true); } else { Win_2 = true; AnimatorCom.SetBool("Win_2", true); } CloseFire(); } }
using Backend.Model.Pharmacies; using System.Collections.Generic; namespace IntegrationAdaptersActionBenefitService.Repository { public interface IPharmacyRepo { PharmacySystem GetPharmacyByExchangeName(string exchangeName); IEnumerable<PharmacySystem> GetPharmaciesBySubscribed(bool subscribed); } }
namespace Egret3DExportTools { using System.Collections.Generic; using GLTF.Schema; using UnityEngine; using Newtonsoft.Json.Linq; public enum MaterialType { Diffuse, Lambert, Phong, Standard, StandardSpecular, StandardRoughness, Particle, Skybox, Skybox_Cubed, Custom } public struct Define { public string name; public string content; } public class MaterialData { public Techniques technique; public JObject values; public MaterialAssetExtension asset; } public class GLTFMaterialSerializer : AssetSerializer { private bool _isParticle = false; private UnityEngine.Material _material; private readonly Dictionary<MaterialType, BaseMaterialParser> parsers = new Dictionary<MaterialType, BaseMaterialParser>(); public GLTFMaterialSerializer() { this.parsers.Clear(); // this.register(MaterialType.Diffuse, new DiffuseParser(), "builtin/meshbasic.shader.json"); this.register(MaterialType.Lambert, new LambertParser(), "builtin/meshlambert.shader.json"); this.register(MaterialType.Phong, new PhongParser(), "builtin/meshphong.shader.json"); this.register(MaterialType.Standard, new StandardParser(), "builtin/meshphysical.shader.json"); this.register(MaterialType.StandardRoughness, new StandardRoughnessParser(), "builtin/meshphysical.shader.json"); this.register(MaterialType.StandardSpecular, new StandardSpecularParser(), "builtin/meshphysical.shader.json"); this.register(MaterialType.Particle, new ParticleParser(), "builtin/particle.shader.json"); this.register(MaterialType.Skybox, new SkyboxParser(), "builtin/cube.shader.json"); this.register(MaterialType.Skybox_Cubed, new SkyboxCubedParser(), "builtin/cube.shader.json"); this.register(MaterialType.Custom, new CustomParser(), ""); } private void register(MaterialType type, BaseMaterialParser parse, string shaderAsset) { parse.Init(shaderAsset); this.parsers.Add(type, parse); } private BaseMaterialParser getParser(MaterialType type) { return this.parsers[type]; } protected override void InitGLTFRoot() { base.InitGLTFRoot(); this._root.ExtensionsRequired.Add(KhrTechniquesWebglMaterialExtension.EXTENSION_NAME); this._root.ExtensionsRequired.Add(AssetVersionExtension.EXTENSION_NAME); this._root.ExtensionsUsed.Add(KhrTechniquesWebglMaterialExtension.EXTENSION_NAME); this._root.ExtensionsUsed.Add(AssetVersionExtension.EXTENSION_NAME); this._root.Materials = new List<GLTF.Schema.Material>(); } protected override void Serialize(UnityEngine.Object sourceAsset) { this._material = sourceAsset as UnityEngine.Material; this._isParticle = this._target.GetComponent<ParticleSystem>() != null; var source = this._material; var data = new MaterialData(); var technique = new Techniques(); var materialExtension = new KhrTechniquesWebglMaterialExtension(); var assetExtension = new MaterialAssetExtension() { version = "5.0", minVersion = "5.0", renderQueue = source.renderQueue }; // data.values = materialExtension.values; data.technique = technique; data.asset = assetExtension; var parser = this.getParser(this.GetMaterialType()); parser.Parse(source, data); var materialGLTF = new GLTF.Schema.Material(); materialGLTF.Name = source.name; materialGLTF.Extensions = new Dictionary<string, IExtension>() { { KhrTechniquesWebglMaterialExtension.EXTENSION_NAME, materialExtension } }; var techniqueExt = new KhrTechniqueWebglGlTfExtension(); techniqueExt.techniques.Add(technique); if (this._root.Extensions.ContainsKey(AssetVersionExtension.EXTENSION_NAME)) { this._root.Extensions.Remove(AssetVersionExtension.EXTENSION_NAME); } this._root.Extensions.Add(AssetVersionExtension.EXTENSION_NAME, assetExtension); this._root.Extensions.Add(KhrTechniquesWebglMaterialExtension.EXTENSION_NAME, techniqueExt); this._root.Materials.Add(materialGLTF); } private MaterialType GetMaterialType() { var shaderName = this._material.shader.name; var customShaderConfig = ExportSetting.instance.GetCustomShader(shaderName); if (shaderName == "Skybox/6 Sided") { return MaterialType.Skybox; } if (shaderName == "Skybox/Cubemap") { return MaterialType.Skybox_Cubed; } if (this._isParticle) { return MaterialType.Particle; } if (customShaderConfig != null) { return MaterialType.Custom; } { var lightType = ExportSetting.instance.light.type; switch (lightType) { case ExportLightType.Lambert: { return MaterialType.Lambert; } case ExportLightType.Phong: { return MaterialType.Phong; } case ExportLightType.Standard: { switch (shaderName) { case "Standard (Specular setup)": { return MaterialType.StandardSpecular; } case "Standard (Roughness setup)": { return MaterialType.StandardRoughness; } default: { return MaterialType.Standard; } } } } } return MaterialType.Diffuse; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ghostpunch.OnlyDown.Common.Commands { public class RelayCommand<T> : ICommand { private readonly Action<T> _execute; private readonly Func<T, bool> _canExecute; public RelayCommand(Action<T> execute) : this(execute, null) { } public RelayCommand(Action<T> execute, Func<T, bool> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); _execute = execute; _canExecute = canExecute; } public bool CanExecute(object param) { if (_canExecute == null) return true; if (param == null && #if NETFX_CORE typeof(T).GetTypeInfo().IsValueType) #else typeof(T).IsValueType) #endif { return _canExecute(default(T)); } if (param == null || param is T) return _canExecute((T)param); return false; } public void Execute(object param) { var val = param; #if !NETFX_CORE if (param != null && param.GetType() != typeof(T)) { if (param is IConvertible) val = Convert.ChangeType(param, typeof(T), null); } #endif if (CanExecute(val) && _execute != null) { if (val == null) { #if NETFX_CORE if (typeof(T).GetTypeInfo().IsValueType) #else if (typeof(T).IsValueType) #endif { _execute(default(T)); return; } } _execute((T)val); } } } }
using System; namespace Interface_Ipayable { public interface Ipayable { decimal DapatkanJumlahPembayaran(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Business.OnlinePay.Company.ChinaPay.Charge { public class Response:ResponseBase { public override string ResponseName { get { return "C101RechargeCbRq"; } } /// <summary> /// 商户私有域 /// </summary> public string MerPriv { get; set; } /// <summary> /// 扩展域 /// </summary> public string Reserved { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CheckAvability.Common; namespace CheckAvability.Model { public class IphoneAvalibilityInStore { public string storeName { get; set; } // public string 大細機 { get; set; } public string 一二八亮黑 { get; set; } // MN8Q2ZP public string 二五六亮黑 { get; set; } //MN8W2ZP public string 三十二金 { get; set; } //MN8J2ZP public string 一二八金 { get; set; } //MN8N2ZP public string 二五六金 { get; set; } //MN8U2ZP public string 三十二玫金 { get; set; } //MN8K2ZP public string 一二八玫金 { get; set; } //MN8P2ZP public string 二五六玫金 { get; set; } //MN8V2ZP public string 三十二黑 { get; set; } //MN8G2ZP public string 一二八黑 { get; set; } //MN8L2ZP public string 二五六黑 { get; set; } //MN8R2ZP public string 三十二銀 { get; set; } //MN8H2ZP public string 一二八銀 { get; set; } //MN8M2ZP public string 二五六銀 { get; set; } //MN8T2ZP public IphoneAvalibilityInStore(string _storename) { this.storeName = Shop.GetShopName(_storename); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Anywhere2Go.Library { public class HashHelper { public string Hash { get; private set; } public string Salt { get; private set; } public string ConcatString { get; private set; } public HashHelper() { } public HashHelper(HashHelper hash) { } public string HashMigsTransactionReference(decimal amount, string merchantId, string orderId, string merchantAccessCode) { string hashInput = string.Concat(amount.ToString("0.00"), merchantId, orderId, merchantAccessCode); string hashedValue = MD5Hash(hashInput); return hashedValue; } public string PerformHash(string password) { Guid guid = Guid.NewGuid(); Salt = guid.ToString(); var passwordAndSaltBytes = Concat(password); return ComputeHash(passwordAndSaltBytes); } public bool Verify(string salt, string hash, string password) { Salt = salt; var passwordAndSaltBytes = Concat(password); var hashAttempt = ComputeHash(passwordAndSaltBytes); return hash == hashAttempt.ToLower(); } private string ComputeHash(byte[] bytes) { using (var sha256 = SHA256.Create()) { return HexHelper.ToHex(sha256.ComputeHash(bytes)); } } private byte[] Concat(string password) { ConcatString = string.Concat(password, Salt); var passwordBytes = Encoding.UTF8.GetBytes(ConcatString); return passwordBytes; } public string GetMd5Hash(MD5 md5Hash, string input) { string salt = "s+(_a*"; string ConcatString = string.Concat(input, salt); // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(ConcatString)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } public string GetMd5HashWitoutSalt(MD5 md5Hash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } /// <summary> /// Encrypt the Given string with the Key provided and return the value /// </summary> /// <param name="md5Has">md5 Hash</param> /// <param name="toEncrypt">Token from Reddist to be encrypted and stored in to Cookie</param> /// <param name="securityKey">Key to encrypt</param> /// <returns>return encrypted value in string</returns> public string EncryptTokenUsingMd5(string toEncrypt, string securityKey) { byte[] data; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); MD5 md5Has = new MD5CryptoServiceProvider(); data = md5Has.ComputeHash(UTF8Encoding.UTF8.GetBytes(securityKey)); md5Has.Dispose(); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = data; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// /// </summary> /// <param name="md5Has"></param> /// <param name="toDecrypt"></param> /// <param name="securityKey"></param> /// <returns></returns> public string DecryptTokenUsingMd5(string toDecrypt, string securityKey) { byte[] data; byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); MD5 md5Has = new MD5CryptoServiceProvider(); data = md5Has.ComputeHash(UTF8Encoding.UTF8.GetBytes(securityKey)); md5Has.Dispose(); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = data; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock( toEncryptArray, 0, toEncryptArray.Length); tdes.Clear(); return UTF8Encoding.UTF8.GetString(resultArray); } // Verify a hash against a string. public bool VerifyMd5Hash(MD5 md5Hash, string input, string hash) { // Hash the input. string hashOfInput = GetMd5Hash(md5Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) { return true; } else { return false; } } /// <summary> /// Created for performinig MD5 hash to MOLPay /// </summary> /// <param name="text">Input text</param> /// <returns>Hashed input</returns> public string MD5Hash(string text) { MD5 md5 = new MD5CryptoServiceProvider(); //compute hash from the bytes of text md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text)); //get hash result after compute it byte[] result = md5.Hash; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < result.Length; i++) { //change it into 2 hexadecimal digits //for each byte strBuilder.Append(result[i].ToString("x2")); } return strBuilder.ToString(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; namespace PowerPad.RouteHandlers { internal class StaticFileHandler : IRouteHandler { private readonly Func<byte[]> getSource; private readonly byte[] cachedSource; private readonly string contentType; private readonly Dictionary<string, string> knownContentTypes = new Dictionary<string, string> { { ".js", "application/javascript" }, { ".htm", "text/html" }, { ".jpg", "image/jpeg" }, { ".png", "image/png" }, { ".css", "text/css" }, { ".less", "text/css" } }; internal StaticFileHandler(string path) { if (path == null) throw new ArgumentException("Path can't be null"); // If we're in debug mode, we'll always read the file from disk rather than caching it if (Settings.IsDebug) getSource = () => File.ReadAllBytes(path); else { cachedSource = File.ReadAllBytes(path); getSource = () => cachedSource; } // Set the content type depending on the file extension string extension = Path.GetExtension(path); if (extension == null) throw new ArgumentException("Unknown filetype: " + Path.GetFileName(path)); if (knownContentTypes.ContainsKey(extension)) contentType = knownContentTypes[extension]; } public void HandleRequest(HttpListenerContext context, StreamWriter sw) { if (contentType != null) context.Response.ContentType = contentType; byte[] source = getSource(); context.Response.ContentLength64 = source.Length; context.Response.OutputStream.Write(source, 0, source.Length); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Robot : MonoBehaviour { public GameObject bodyPart; public GameObject bodyPivot; public float time; public float spawnDelay; public float animDelay; [SerializeField] private Texture [] textures; [SerializeField] private Robot previousRobot; public int textureNumber; private bool armSpawned = false; void Start () { InvokeRepeating ("StaticLoop", spawnDelay, 3); Invoke ("Delay", animDelay); } void StaticLoop () { if (name == "Robot005" && !armSpawned || name == "Robot005_Arm" && !armSpawned) { textureNumber = 1; armSpawned = true; } else if (name == "Robot001") textureNumber = Random.Range (0, textures.Length); else textureNumber = previousRobot.textureNumber; GameObject part = Instantiate (bodyPart, bodyPivot.transform.position, Quaternion.Euler (new Vector3 (bodyPart.transform.rotation.x, 270, bodyPart.transform.rotation.z)), bodyPivot.transform); foreach (Renderer rend in part.GetComponentsInChildren <Renderer> ()) rend.material.mainTexture = textures [textureNumber]; } void Delay () { if (gameObject.name != "Robot005_Arm") { GetComponent<Animator> ().SetBool ("Play", true); } } }
using JIDBFramework; using JIDBFramework.Windows; using OgrenciTakip.Ekran.Tema; using OgrenciTakip.Models.Kullanicilar; using OgrenciTakip.Models.Personeller; using OgrenciTakip.Utilities; using OgrenciTakip.Utilities.Liste; using OgrenciTakip.Yonetici; 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 OgrenciTakip.Ekran.Personeller { public partial class EmployeeInfoForm : TemplateForm { public EmployeeInfoForm() { InitializeComponent(); } public int PersonelId { get; set; } private void KapatToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void EmployeeInfoForm_Load(object sender, EventArgs e) { LoadDataIntoComboBoxes(); if (this.IsUpdate) { LoadDataAndBindIntoControls(); EnableButtons(); } else { GenerateEmployeeId(); } } private void LoadDataAndBindIntoControls() { DbSQLServer db = new DbSQLServer(AppSetting.ConnectionString()); DataTable dtEmployee = db.GetDataList("usp_EmployeesGetEmployeeDetailsById", new DbParameter { Parameter = "@PersonelId", Value = this.PersonelId }); DataRow row = dtEmployee.Rows[0]; EmbloyeeIDTextBox.Text = row["PersonelId"].ToString(); textBox2.Text = row["AdiveSoyadi"].ToString(); DateOfBirthDateTimePicker.Value = Convert.ToDateTime(row["DogumTarihi"]); NICTextBox.Text = row["NICNumber"].ToString(); EmailAddressTextBox.Text = row["EmailAddress"].ToString(); MobileTextBox.Text = row["Cep"].ToString(); TelephoneTextBox.Text = row["Telefon"].ToString(); comboBox1.SelectedValue = row["CinsiyetId"]; DateTimePicker2.Value = Convert.ToDateTime(row["IsTarihi"]); BolumComboBox.SelectedValue = row["BolumId"]; PhotoPictureBox.Image = (row["Photo"] is DBNull) ? null : ImageManipulations.PutPhoto((byte[])row["Photo"]); AddressLineTextBox.Text = row["AddressLine"].ToString(); CityComboBox.SelectedValue = row["CityId"]; DistrictComboBox.SelectedValue = row["DistrictId"]; PostCodeTextBox.Text = row["PostCode"].ToString(); JobTitleComboBox.SelectedValue = row["JobTitleId"]; MevcutMaasTextBox.Text = row["CurrentSalary"].ToString(); IlkMaasTextBox.Text = row["StartingSalary"].ToString(); HasLeftComboBox.Text = (Convert.ToBoolean(row["HasLeft"]) == true) ? "Evet" : "Hayır"; DateLeftDateTimePicker.Value = Convert.ToDateTime(row["DateLeft"]); EmployeeLevingReasonComboBox.SelectedValue = row["ReasonLeftId"]; EmployeeLeavingCommentsTextBox.Text = row["Comments"].ToString(); } private void GenerateEmployeeId() { DbSQLServer db = new DbSQLServer(AppSetting.ConnectionString()); EmbloyeeIDTextBox.Text = db.GetScalarValue("usp_EmployeesGenerateNewEmployeeId").ToString(); } private void LoadDataIntoComboBoxes() { ListData.LoadDataIntoComboBox(BolumComboBox, "usp_BranchesGetAllBranchNames"); ListData.LoadDataIntoComboBox(comboBox1, new DbParameter { Parameter = "@ListTypeId", Value = ListTypes.Gender }); ListData.LoadDataIntoComboBox(CityComboBox, new DbParameter { Parameter = "@ListTypeId", Value = ListTypes.City }); ListData.LoadDataIntoComboBox(DistrictComboBox, new DbParameter { Parameter = "@ListTypeId", Value = ListTypes.District }); ListData.LoadDataIntoComboBox(JobTitleComboBox, new DbParameter { Parameter = "@ListTypeId", Value = ListTypes.EmployeeJobTitle }); ListData.LoadDataIntoComboBox(HasLeftComboBox, new DbParameter { Parameter = "@ListTypeId", Value = ListTypes.YesNo }); ListData.LoadDataIntoComboBox(EmployeeLevingReasonComboBox, new DbParameter { Parameter = "@ListTypeId", Value = ListTypes.EmployeeReasonLeft }); } private void PhotoPictureBox_DoubleClick(object sender, EventArgs e) { GetPhoto(); } private void GetPhoto() { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Fotoğraf Seçiniz"; ofd.Filter = "Photo File (*.png; *.jpg; *.bmf;*.gif) | *.png; *.jpg; *.bmf;*.gif"; if (ofd.ShowDialog() == DialogResult.OK) { PhotoPictureBox.Image = new Bitmap(ofd.FileName); } } private void GetPhotoPictureBox_Click(object sender, EventArgs e) { GetPhoto(); } private void ClearPictureBox_Click(object sender, EventArgs e) { PhotoPictureBox.Image = null; } private void KaydetToolStripMenuItem_Click(object sender, EventArgs e) { if (IsFormValid()) { if(this.IsUpdate) { SaveOrUpdate("usp_EmployeesUpdateEmployeeDetails"); JIMessageBox.ShowSuccessMessage("Kayıt güncellemesi başarılı."); } else { SaveOrUpdate("usp_EmployeesAddNewEmployee"); JIMessageBox.ShowSuccessMessage("Kayıt başarılı."); this.IsUpdate = true; EnableButtons(); } } } private void SaveOrUpdate(string storedProcName) { DbSQLServer db = new DbSQLServer(AppSetting.ConnectionString()); db.SaveOrUpdateRecord(storedProcName, GetObject()); } private void EnableButtons() { EkleToolStripMenuItem.Enabled = true; YollaToolStripMenuItem.Enabled = true; YazdirToolStripMenuItem.Enabled = true; } private Employee GetObject() { Employee employee = new Employee(); employee.PersonelId = Convert.ToInt32(EmbloyeeIDTextBox.Text); employee.AdiveSoyadi = textBox2.Text.Trim(); employee.DogumTarihi = DateOfBirthDateTimePicker.Value.Date; employee.NICNumber = NICTextBox.Text.Trim(); employee.EmailAddress = EmailAddressTextBox.Text.Trim(); employee.Cep = MobileTextBox.Text.Trim(); employee.Telefon = TelephoneTextBox.Text.Trim(); employee.IsTarihi = DateTimePicker2.Value.Date; employee.CinsiyetId = (comboBox1.SelectedIndex == -1) ? 0 : Convert.ToInt32(comboBox1.SelectedValue); employee.BolumId = (BolumComboBox.SelectedIndex == -1) ? 0 : Convert.ToInt32(BolumComboBox.SelectedValue); employee.Photo = (PhotoPictureBox.Image == null) ? null : ImageManipulations.GetPhoto(PhotoPictureBox); employee.AddressLine = AddressLineTextBox.Text.Trim(); employee.CityId = (CityComboBox.SelectedIndex == -1) ? 0 : Convert.ToInt32(CityComboBox.SelectedValue); employee.DistrictId = (DistrictComboBox.SelectedIndex == -1) ? 0 : Convert.ToInt32(DistrictComboBox.SelectedValue); employee.PostCode = PostCodeTextBox.Text.Trim(); employee.JobTitleId = (JobTitleComboBox.SelectedIndex == -1) ? 0 : Convert.ToInt32(JobTitleComboBox.SelectedValue); employee.CurrentSalary = Convert.ToDecimal(MevcutMaasTextBox.Text); employee.StartingSalary = Convert.ToDecimal(IlkMaasTextBox.Text); employee.HasLeft = (HasLeftComboBox.Text == "Evet") ? true : false; employee.DateLeft = DateLeftDateTimePicker.Value.Date; employee.ReasonLeftId = (EmployeeLevingReasonComboBox.SelectedIndex == -1) ? 0 : Convert.ToInt32(EmployeeLevingReasonComboBox.SelectedValue); employee.Comments = EmployeeLeavingCommentsTextBox.Text.Trim(); employee.CreatedBy = LoggedInUser.KullaniciAdi; return employee; } private bool IsFormValid() { if (textBox2.Text.Trim() == string.Empty) { JIMessageBox.ShowErrorMessage("Lütfen adınızı ve soyadınızı giriniz."); textBox2.Focus(); return false; } if (NICTextBox.Text.Trim() == string.Empty) { JIMessageBox.ShowErrorMessage("Lütfen TC Kimlik numaranızı giriniz."); NICTextBox.Focus(); return false; } if ((MobileTextBox.Text.Trim() == string.Empty) && (TelephoneTextBox.Text.Trim() == string.Empty)) { JIMessageBox.ShowErrorMessage("Lütfen telefon numaranızı ya da cep telefonunuzu giriniz."); MobileTextBox.Focus(); return false; } if(comboBox1.SelectedIndex == -1) { JIMessageBox.ShowErrorMessage("Lütfen cinsiyetinizi seçiniz."); return false; } if (AddressLineTextBox.Text.Trim() == string.Empty) { JIMessageBox.ShowErrorMessage("Lütfen adresinizi giriniz."); AddressLineTextBox.Focus(); return false; } if (CityComboBox.SelectedIndex == -1) { JIMessageBox.ShowErrorMessage("Lütfen şehrinizi seçiniz."); return false; } if (DistrictComboBox.SelectedIndex == -1) { JIMessageBox.ShowErrorMessage("Lütfen ilçenizi seçiniz."); return false; } if (PostCodeTextBox.Text.Trim() == string.Empty) { JIMessageBox.ShowErrorMessage("Lütfen posta kodunuzu giriniz."); PostCodeTextBox.Focus(); return false; } if (JobTitleComboBox.SelectedIndex == -1) { JIMessageBox.ShowErrorMessage("Lütfen işinizi seçiniz."); return false; } if (MevcutMaasTextBox.Text.Trim() == string.Empty) { JIMessageBox.ShowErrorMessage("Lütfen mevcut maaşınızı giriniz."); MevcutMaasTextBox.Focus(); return false; } else { if(Convert.ToDecimal(MevcutMaasTextBox.Text.Trim()) < 1) { JIMessageBox.ShowErrorMessage("Mecvut maaşınız 0 ya da 0'dan küçük olamaz."); MevcutMaasTextBox.Focus(); return false; } } if (IlkMaasTextBox.Text.Trim() == string.Empty) { JIMessageBox.ShowErrorMessage("Lütfen başlangıç maaşınızı giriniz."); IlkMaasTextBox.Focus(); return false; } else { if (Convert.ToDecimal(IlkMaasTextBox.Text.Trim()) < 1) { JIMessageBox.ShowErrorMessage("İlk maaşınız 0 ya da 0'dan küçük olamaz."); IlkMaasTextBox.Focus(); return false; } } return true; } private void textBox2_TextChanged(object sender, EventArgs e) { label8.Text = textBox2.Text; } } }
using Cradiator.Model; namespace Cradiator.Config.ChangeHandlers { public class PollIntervalChangeHandler : IConfigChangeHandler { readonly IPollTimer _pollTimer; readonly ICountdownTimer _countdownTimer; public PollIntervalChangeHandler(IPollTimer pollTimer, ICountdownTimer countTimer) { _pollTimer = pollTimer; _countdownTimer = countTimer; } void IConfigChangeHandler.ConfigUpdated(ConfigSettings newSettings) { lock (_pollTimer) { if (_pollTimer.Interval != newSettings.PollFrequencyTimeSpan) { _pollTimer.Stop(); _pollTimer.Interval = newSettings.PollFrequencyTimeSpan; lock (_countdownTimer) { _countdownTimer.PollFrequency = newSettings.PollFrequencyTimeSpan; _countdownTimer.Reset(); } _pollTimer.Start(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.IO; using IBLLService; using MODEL.ViewModel; using Common; using MODEL; using ShengUI.Helper; using System.Threading; using System.Globalization; using Common.EfSearchModel.Model; using MODEL.ViewPage; namespace ShengUI.Logic { public class ResumeController : BaseController { IMST_RESUME_MANAGER resumeManager = OperateContext.Current.BLLSession.IMST_RESUME_MANAGER; IMST_RESUME_DTL_MANAGER resume_dtlManager = OperateContext.Current.BLLSession.IMST_RESUME_DTL_MANAGER; public ActionResult ResumeIndex() { ViewBag.PageFlag = "JianLi"; var member_cd = SessionHelper.Get("MEMBER_CD"); VIEW_MST_RESUME model = VIEW_MST_RESUME.ToViewModel(resumeManager.Get(r => r.MEMBER_CD == member_cd)); List<VIEW_MST_RESUME_DTL> modellist = VIEW_MST_RESUME_DTL.ToListViewModel(resume_dtlManager.GetListBy(r => r.MEMBER_CD == member_cd && r.RESUME_CD == model.RESUME_CD)).ToList(); ViewBag.ResumeDtlList = modellist; return View(model); } public ActionResult ReNameResume(ReNameResume model) { bool status = false; if (!ModelState.IsValid) return this.JsonFormat(ModelState, !status, "ERROR"); MST_RESUME resume = new MST_RESUME(); resume.RESUME_CD = model.RESUME_CD; resume.RESUME_NAME = model.RESUME_NAME; resume.VERSION = model.VERSION + 1; resume.SYNCVERSION =DateTime.Now; resume.SYNCOPERATION = "U"; resumeManager.Modify(resume, "RESUME_NAME", "VERSION", "SYNCVERSION", "SYNCOPERATION"); status = true; return this.JsonFormat(resume, !status, "保存成功"); } public ActionResult SaveBaseInfo(ResumeBaseInfo model) { bool status = false; if (!ModelState.IsValid) return this.JsonFormat(ModelState, !status, "ERROR"); MST_RESUME resume = new MST_RESUME(); resume.RESUME_CD = model.RESUME_CD; resume.NAME = model.NAME; resume.EMAIL = model.EMAIL; resume.EDUCATION = model.EDUCATION; resume.EXPERIENCE = model.EXPERIENCE; resume.SEX = model.SEX; resume.PHONE = model.PHONE; resume.CURRENT_STATE = model.CURRENT_STATE; resume.PORTRAIT = model.PORTRAIT; resumeManager.Modify(resume, "NAME", "EMAIL", "EDUCATION", "EXPERIENCE", "SEX", "PHONE", "CURRENT_STATE", "PORTRAIT"); status = true; return this.JsonFormat(resume, !status, "保存成功"); } public ActionResult SaveZWPJ(ResumeZWPJ model) { bool status = false; if (!ModelState.IsValid) return this.JsonFormat(ModelState, !status, "ERROR"); var member_cd = SessionHelper.Get("MEMBER_CD"); MST_RESUME_DTL dtl = new MST_RESUME_DTL(); dtl.ID = model.ResumeZWPJID; dtl.RESUME_CD = model.RESUME_CD; dtl.MEMBER_CD = member_cd; dtl.RESUME_DTL1 = model.selfDesc; resume_dtlManager.Modify(dtl, "RESUME_DTL1"); status = true; return this.JsonFormat(dtl, !status, "保存成功"); } public ActionResult SaveWorkForm(ResumeWork model) { bool status = false; if (!ModelState.IsValid) return this.JsonFormat(ModelState, !status, "ERROR"); var member_cd = SessionHelper.Get("MEMBER_CD"); MST_RESUME_DTL dtl = new MST_RESUME_DTL(); dtl.RESUME_CD = model.RESUME_CD; dtl.MEMBER_CD = member_cd; dtl.RESUME_DTL1 = model.workLink; dtl.RESUME_DTL2 = model.workDesc; resume_dtlManager.Add(dtl); status = true; return this.JsonFormat(dtl, !status, "保存成功"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HomeWork8_1 { //Факториал числа через рекурсию class Program { static int Factr(int a) { if (a <= 1) return 1; else { return a * Factr(a - 1); } } static void Main(string[] args) { Console.WriteLine(Factr(4)); Console.ReadKey(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UPArea : MonoBehaviour { public Image weapon; public Image other; public Image decorate; public Image defense; public GameObject charaRawImage; public GameObject charaRawImageObj; public static UPArea instance; // Start is called before the first frame update void Start() { EventCenter.GetInstance().AddEventListener(EventDic.PlayerModelUpdate,UpdateNowEqp); EventCenter.GetInstance().AddEventListener(EventDic.PlayerModelUpdate,CharaChangeUpdate); } private void OnDestroy() { EventCenter.GetInstance().RemoveEventListener(EventDic.PlayerModelUpdate,UpdateNowEqp); EventCenter.GetInstance().RemoveEventListener(EventDic.PlayerModelUpdate, CharaChangeUpdate); } // Update is called once per frame void Update() { } private void Awake() { instance = this; } public void Init() { //TODO°´Å¥¹¦ÄÜ //Debug.Log("aaaaaaa"); // CharaChangeUpdate(); UpdateNowEqp(); InitPlayerModel(); SetEqpBroder(); } public Sprite EqpBroder; private void SetEqpBroder() { //throw new NotImplementedException(); } public Text Text_Level; public Text Text_ATK; public Text Text_DEF; public Text Text_HP; private void InitPlayerModel() { string nowCharaName = GameRoot.instance.playerModel.nowCharaName; var model = GameRoot.instance.playerModel.CharaInfoDic[nowCharaName]; Text_Level.text = model.level.ToString(); Text_ATK.text = PlayerModelController.GetInstance().GetPlayerInfo().atk.ToString(); Text_DEF.text = PlayerModelController.GetInstance().GetPlayerInfo().def.ToString(); Text_HP.text = PlayerModelController.GetInstance().GetPlayerInfo().hp.ToString(); //throw new NotImplementedException(); } private void CharaChangeUpdate() { Destroy(charaRawImageObj); charaRawImageObj = ResMgr.GetInstance().Load<GameObject>(GameRoot.instance.playerModel.nowCharaPath); charaRawImageObj.transform.parent = instance.charaRawImage.transform; charaRawImageObj.transform.localPosition = new Vector3(0, 0, 888); charaRawImageObj.transform.localScale = new Vector3(111, 111, 1); charaRawImageObj.layer = 7; } private void UpdateNowEqp() { //Debug.Log(GameRoot.instance.playerModel.eqp_weapon.imagePath); try { if (ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_weapon.imagePath) != null) { weapon.sprite = ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_weapon.imagePath); } else { } } catch{} try { if (ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_other.imagePath) != null) { other.sprite = ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_other.imagePath); } } catch {} try { if (ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_decorate.imagePath)!=null) { decorate.sprite = ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_decorate.imagePath); } } catch{} try { if (ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_defense.imagePath) != null) { defense.sprite = ResMgr.GetInstance().Load<Sprite>(GameRoot.instance.playerModel.eqp_defense.imagePath); } } catch { Debug.Log("¿Õ"); } //throw new NotImplementedException(); InitPlayerModel(); } }
using DevanshAssociate_API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DevanshAssociate_API.Services { interface ICommonService { List<LoanData> getAllLoanData(); List<BankData> getAllBankData(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SpacecraftWar { class GameManager { private Timer _timer; private BoardManager _board; public const int INTERVAL = 1300; public GameManager(int width, int height) { _board = new BoardManager(width, height); } public void StartGame() { _timer = new Timer(TimerCallback, null, 0, INTERVAL); } public void MovePlayer(Direction direction) { _board.MovePlayer(direction); } public GameSituation GetGameSituation() { return _board.GetGameSituation(); } private void TimerCallback(object state) { _board.MoveEnemies(); } } }
using Backend.Model.Users; using Backend.Repository.SpecialtyRepository; using System.Collections.Generic; namespace Backend.Service.UsersAndWorkingTime { public class SpecialtyService : ISpecialtyService { private readonly ISpecialtyRepository _specialtyRepository; public SpecialtyService(ISpecialtyRepository specialtyRepository) { _specialtyRepository = specialtyRepository; } public List<Specialty> GetSpecialties() { return _specialtyRepository.GetSpecialties(); } } }
using CarRental.API.BL.Services.RentalLocations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CarRental.API.BL.Models.RentalLocations; using CarRental.API.DAL.Entities; namespace CarRental.API.Controllers { [ApiController] [Route("[controller]")] public class RentalLocationsController : ControllerBase { private readonly IRentalLocationService _rentalLocationService; public RentalLocationsController(IRentalLocationService rentalLocationService) { _rentalLocationService = rentalLocationService; } [HttpGet] [Route("GetAllRentalLocations")] /// <summary> /// Get a list of items /// </summary> /// <returns>List with TodoModels</returns> public virtual async Task<IEnumerable<RentalLocationModel>> GetAllRentalLocations() { return await _rentalLocationService.GetAllAsync(); } /// <summary> /// Get an item by its id. /// </summary> /// <param name="id">id of the item you want to get</param> /// <returns>Item or StatusCode 404</returns> [HttpGet("GetRentalLocation/{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesDefaultResponseType] public virtual async Task<ActionResult<RentalLocationModel>> GetOneRentalLocation(Guid id) { var item = await _rentalLocationService.GetAsync(id); if (item is null) { return NotFound(); } return item; } /// <summary> /// Add an item /// </summary> /// <param name="item">Model to add, id will be ignored</param> /// <returns>Id of created item</returns> [Route("CreateRentalLocation")] [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesDefaultResponseType] public virtual async Task<RentalLocationItem> CreateOneRentalLocation(CreateRentalLocationModel item) { return await _rentalLocationService.CreateAsync(item); } /// <summary> /// Update or create an item /// </summary> /// <param name="item"></param> /// <returns></returns> [Route("UpdateRentalLocation")] [HttpPut] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesDefaultResponseType] public virtual async Task<ActionResult<int>> UpdateRentalLocation(RentalLocationModel item) { var updateItemId = await _rentalLocationService.UpsertAsync(item); return Ok(updateItemId); } /// <summary> /// Delete an item /// </summary> /// <param name="id">Id of the item to delete</param> /// <returns>StatusCode 200 or 404</returns> [HttpDelete("DeleteRentalLocation/{id}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesDefaultResponseType] public virtual async Task<ActionResult<bool>> DeleteRentalLocation(Guid id) { var deletedItem = await _rentalLocationService.DeleteAsync(id); return Ok(deletedItem); } } }
using System; using System.Linq; using System.Windows.Forms; namespace Tic_Tac_Toe_WF { public partial class Playernames : Form { public static string player1Name = ""; public static string player2Name = ""; private Game loadGame = new Game(); public Playernames() { InitializeComponent(); } private void Start_Click(object sender, EventArgs e) { //First we need to get the names player1Name = Player1.Text; player2Name = Player2.Text; //Use Uppercase only! ~ Deleted, because it looks ugly player1Name = player1Name.ToUpper(); player2Name = player2Name.ToUpper(); //Check if the Boxes contain any letters, if they contain anything else than letters or nothing - Error //true if it doesn't contain letters //Bugfix for https://github.com/DanielKng/Tic-Tac-Toe/issues/6 and https://github.com/DanielKng/Tic-Tac-Toe/issues/5 bool result = player1Name.Any(x => !char.IsLetter(x)) && player2Name.Any(x => !char.IsLetter(x)) || player1Name.Any(x => !char.IsLetter(x)) || player2Name.Any(x => !char.IsLetter(x)); //IF the result is true, one or both of the Textboxes does contain special characters or a space without letters //even if you put in a name in "Player 2 Textbox" it will get deleted here if you enabled the AI if (player1Name == "") { result = true; } if (result) { Player1.Text = "Error! Please use a valid name!"; if (!ai_activate.Checked) { Player2.Text = "Error! Please use a valid name!"; } } //Bugfix for https://github.com/DanielKng/Tic-Tac-Toe/issues/6 and https://github.com/DanielKng/Tic-Tac-Toe/issues/5 //If the String is empty else if (string.IsNullOrEmpty(player1Name) || string.IsNullOrEmpty(player2Name) || string.IsNullOrEmpty(player1Name) && string.IsNullOrEmpty(player2Name)) { if (ai_activate.Checked) //if you enabled the AI "Player 2 Name" will changed to "Computer" { loadGame.ai_enable = true; Playernames.player2Name = "Computer"; Hide(); loadGame.StartPosition = FormStartPosition.CenterScreen; loadGame.Show(); } else //... otherwise you'll get a Error Message, because you didn't filled all "Name Textboxes" { Player1.Text = "Error! The name cant be empty!"; Player2.Text = "Error! The name cant be empty!"; } } else { //Load the Game //This is important. With this piece of code the Window gets centered and is at the same place as all other Windows! loadGame.StartPosition = FormStartPosition.CenterScreen; loadGame.Show(); this.Hide(); } } private void ai_activate_CheckedChanged(object sender, EventArgs e) //if you click the Checkbox "ai_enable" you'll jump in here { if (ai_activate.Checked) //if you actiate the Checkbox, you diable the "Player 2 Textbox" { Player2.Enabled = false; Player2.Text = ""; } else //if you deactivate the Checkbox, you enable the "Player 2 Textbox" { Player2.Enabled = true; } } } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace ScriptableObjectFramework.Conditions.Editor { [CustomPropertyDrawer(typeof(Condition), true)] public class ConditionDrawer : PropertyDrawer { const float buffer = 5; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); float sectionSize = (position.width) / 4 - buffer; Rect executionModePosition = new Rect(position.x, position.y, sectionSize, position.height); Rect conditionPosition = new Rect(position.x + (buffer + sectionSize), position.y, sectionSize, position.height); Rect argumentPosition = new Rect(position.x + (buffer + sectionSize) * 2, position.y, sectionSize, position.height); Rect eventPosition = new Rect(position.x + (buffer + sectionSize) * 3, position.y, sectionSize, position.height); EditorGUI.PropertyField(executionModePosition, property.FindPropertyRelative("ExecutionMode"), GUIContent.none); EditorGUI.PropertyField(conditionPosition, property.FindPropertyRelative("Condition"), GUIContent.none); EditorGUI.PropertyField(argumentPosition, property.FindPropertyRelative("Argument"), GUIContent.none); EditorGUI.PropertyField(eventPosition, property.FindPropertyRelative("Event"), GUIContent.none); EditorGUI.EndProperty(); } } }
//#define DO_ANIMATE #define DO_LIGHT_SAMPLING #define DO_THREADED using Unity.Mathematics; using static Unity.Mathematics.math; using Unity.Collections; using Unity.Jobs; using Unity.Burst; using UnityEngine; namespace Aras { public static class MathUtil { public const float Pi = (float)System.Math.PI; public const float Tau = (float)(System.Math.PI * 2.0); public static bool Refract(float3 v, float3 n, float nint, out float3 outRefracted) { float dt = dot(v, n); float discr = 1.0f - nint * nint * (1 - dt * dt); if (discr > 0) { outRefracted = nint * (v - n * dt) - n * sqrt(discr); return true; } outRefracted = new float3(0, 0, 0); return false; } public static float Schlick(float cosine, float ri) { float r0 = (1 - ri) / (1 + ri); r0 = r0 * r0; return r0 + (1 - r0) * pow(1 - cosine, 5); } static uint XorShift32(ref uint state) { uint x = state; x ^= x << 13; x ^= x >> 17; x ^= x << 15; state = x; return x; } public static float RandomFloat01(ref uint state) { return (XorShift32(ref state) & 0xFFFFFF) / 16777216.0f; } public static float3 RandomInUnitDisk(ref uint state) { float3 p; do { p = 2.0f * new float3(RandomFloat01(ref state), RandomFloat01(ref state), 0) - new float3(1, 1, 0); } while (math.lengthsq(p) >= 1.0); return p; } public static float3 RandomInUnitSphere(ref uint state) { float3 p; do { p = 2.0f * new float3(RandomFloat01(ref state), RandomFloat01(ref state), RandomFloat01(ref state)) - new float3(1, 1, 1); } while (math.lengthsq(p) >= 1.0); return p; } } public struct Ray { public float3 orig; public float3 dir; public Ray(float3 orig_, float3 dir_) { orig = orig_; dir = dir_; } public float3 PointAt(float t) { return orig + dir * t; } } public struct Hit { public float3 pos; public float3 normal; public float t; } public struct Sphere { public float3 center; public float radius; public float invRadius; public Sphere(float3 center_, float radius_) { center = center_; radius = radius_; invRadius = 1.0f / radius_; } public void UpdateDerivedData() { invRadius = 1.0f / radius; } public bool HitSphere(Ray r, float tMin, float tMax, ref Hit outHit) { float3 oc = r.orig - center; float b = dot(oc, r.dir); float c = dot(oc, oc) - radius * radius; float discr = b * b - c; if (discr > 0) { float discrSq = sqrt(discr); float t = (-b - discrSq); if (t < tMax && t > tMin) { outHit.pos = r.PointAt(t); outHit.normal = (outHit.pos - center) * invRadius; outHit.t = t; return true; } t = (-b + discrSq); if (t < tMax && t > tMin) { outHit.pos = r.PointAt(t); outHit.normal = (outHit.pos - center) * invRadius; outHit.t = t; return true; } } return false; } } struct Camera { // vfov is top to bottom in degrees public Camera(float3 lookFrom, float3 lookAt, float3 vup, float vfov, float aspect, float aperture, float focusDist) { lensRadius = aperture / 2; float theta = vfov * MathUtil.Pi / 180f; float halfHeight = tan(theta / 2); float halfWidth = aspect * halfHeight; origin = lookFrom; w = normalize(lookFrom - lookAt); u = normalize(cross(vup, w)); v = cross(w, u); lowerLeftCorner = origin - halfWidth * focusDist * u - halfHeight * focusDist * v - focusDist * w; horizontal = 2 * halfWidth * focusDist * u; vertical = 2 * halfHeight * focusDist * v; } public Ray GetRay(float s, float t, ref uint state) { float3 rd = lensRadius * MathUtil.RandomInUnitDisk(ref state); float3 offset = u * rd.x + v * rd.y; return new Ray(origin + offset, normalize(lowerLeftCorner + s * horizontal + t * vertical - origin - offset)); } float3 origin; float3 lowerLeftCorner; float3 horizontal; float3 vertical; float3 u, v, w; float lensRadius; } struct Material { public enum Type { Lambert, Metal, Dielectric }; public Type type; public float3 albedo; public float3 emissive; public float roughness; public float ri; public Material(Type t, float3 a, float3 e, float r, float i) { type = t; albedo = a; emissive = e; roughness = r; ri = i; } public bool HasEmission => emissive.x > 0 || emissive.y > 0 || emissive.z > 0; }; class Test { const int DO_SAMPLES_PER_PIXEL = 8; const float DO_ANIMATE_SMOOTHING = 0.5f; static Sphere[] s_SpheresData = { new Sphere(new float3(0,-100.5f,-1), 100), new Sphere(new float3(2,0,-1), 0.5f), new Sphere(new float3(0,0,-1), 0.5f), new Sphere(new float3(-2,0,-1), 0.5f), new Sphere(new float3(2,0,1), 0.5f), new Sphere(new float3(0,0,1), 0.5f), new Sphere(new float3(-2,0,1), 0.5f), new Sphere(new float3(0.5f,1,0.5f), 0.5f), new Sphere(new float3(-1.5f,1.5f,0f), 0.3f), }; static Material[] s_SphereMatsData = { new Material(Material.Type.Lambert, new float3(0.8f, 0.8f, 0.8f), new float3(0,0,0), 0, 0), new Material(Material.Type.Lambert, new float3(0.8f, 0.4f, 0.4f), new float3(0,0,0), 0, 0), new Material(Material.Type.Lambert, new float3(0.4f, 0.8f, 0.4f), new float3(0,0,0), 0, 0), new Material(Material.Type.Metal, new float3(0.4f, 0.4f, 0.8f), new float3(0,0,0), 0, 0), new Material(Material.Type.Metal, new float3(0.4f, 0.8f, 0.4f), new float3(0,0,0), 0, 0), new Material(Material.Type.Metal, new float3(0.4f, 0.8f, 0.4f), new float3(0,0,0), 0.2f, 0), new Material(Material.Type.Metal, new float3(0.4f, 0.8f, 0.4f), new float3(0,0,0), 0.6f, 0), new Material(Material.Type.Dielectric, new float3(0.4f, 0.4f, 0.4f), new float3(0,0,0), 0, 1.5f), new Material(Material.Type.Lambert, new float3(0.8f, 0.6f, 0.2f), new float3(30,25,15), 0, 0), }; const float kMinT = 0.001f; const float kMaxT = 1.0e7f; const int kMaxDepth = 10; static bool HitWorld(Ray r, float tMin, float tMax, ref Hit outHit, ref int outID, NativeArray<Sphere> spheres) { Hit tmpHit = default(Hit); bool anything = false; float closest = tMax; for (int i = 0; i < spheres.Length; ++i) { if (spheres[i].HitSphere(r, tMin, closest, ref tmpHit)) { anything = true; closest = tmpHit.t; outHit = tmpHit; outID = i; } } return anything; } static bool Scatter(Material mat, Ray r_in, Hit rec, out float3 attenuation, out Ray scattered, out float3 outLightE, ref int inoutRayCount, NativeArray<Sphere> spheres, NativeArray<Material> materials, ref uint randState) { outLightE = new float3(0, 0, 0); if (mat.type == Material.Type.Lambert) { // random point inside unit sphere that is tangent to the hit point float3 target = rec.pos + rec.normal + MathUtil.RandomInUnitSphere(ref randState); scattered = new Ray(rec.pos, normalize(target - rec.pos)); attenuation = mat.albedo; // sample lights #if DO_LIGHT_SAMPLING for (int i = 0; i < spheres.Length; ++i) { if (!materials[i].HasEmission) continue; // skip non-emissive //@TODO if (&mat == &smat) // continue; // skip self var s = spheres[i]; // create a random direction towards sphere // coord system for sampling: sw, su, sv float3 sw = normalize(s.center - rec.pos); float3 su = normalize(cross(abs(sw.x) > 0.01f ? new float3(0, 1, 0) : new float3(1, 0, 0), sw)); float3 sv = cross(sw, su); // sample sphere by solid angle float cosAMax = sqrt(max(0.0f, 1.0f - s.radius * s.radius / math.lengthsq(rec.pos - s.center))); float eps1 = MathUtil.RandomFloat01(ref randState), eps2 = MathUtil.RandomFloat01(ref randState); float cosA = 1.0f - eps1 + eps1 * cosAMax; float sinA = sqrt(1.0f - cosA * cosA); float phi = MathUtil.Tau * eps2; float3 l = su * cos(phi) * sinA + sv * sin(phi) * sinA + sw * cosA; l = normalize(l); // shoot shadow ray Hit lightHit = default(Hit); int hitID = 0; ++inoutRayCount; if (HitWorld(new Ray(rec.pos, l), kMinT, kMaxT, ref lightHit, ref hitID, spheres) && hitID == i) { float omega = MathUtil.Tau * (1 - cosAMax); float3 rdir = r_in.dir; float3 nl = dot(rec.normal, rdir) < 0 ? rec.normal : -rec.normal; outLightE += (mat.albedo * materials[i].emissive) * (math.max(0.0f, math.dot(l, nl)) * omega / MathUtil.Pi); } } #endif return true; } else if (mat.type == Material.Type.Metal) { float3 refl = reflect(r_in.dir, rec.normal); // reflected ray, and random inside of sphere based on roughness scattered = new Ray(rec.pos, normalize(refl + mat.roughness * MathUtil.RandomInUnitSphere(ref randState))); attenuation = mat.albedo; return dot(scattered.dir, rec.normal) > 0; } else if (mat.type == Material.Type.Dielectric) { float3 outwardN; float3 rdir = r_in.dir; float3 refl = reflect(rdir, rec.normal); float nint; attenuation = new float3(1, 1, 1); float3 refr; float reflProb; float cosine; if (dot(rdir, rec.normal) > 0) { outwardN = -rec.normal; nint = mat.ri; cosine = mat.ri * dot(rdir, rec.normal); } else { outwardN = rec.normal; nint = 1.0f / mat.ri; cosine = -dot(rdir, rec.normal); } if (MathUtil.Refract(rdir, outwardN, nint, out refr)) { reflProb = MathUtil.Schlick(cosine, mat.ri); } else { reflProb = 1; } if (MathUtil.RandomFloat01(ref randState) < reflProb) scattered = new Ray(rec.pos, normalize(refl)); else scattered = new Ray(rec.pos, normalize(refr)); } else { attenuation = new float3(1, 0, 1); scattered = default(Ray); return false; } return true; } static float3 Trace(Ray r, int depth, ref int inoutRayCount, NativeArray<Sphere> spheres, NativeArray<Material> materials, ref uint randState) { Hit rec = default(Hit); int id = 0; ++inoutRayCount; if (HitWorld(r, kMinT, kMaxT, ref rec, ref id, spheres)) { Ray scattered; float3 attenuation; float3 lightE; var mat = materials[id]; if (depth < kMaxDepth && Scatter(mat, r, rec, out attenuation, out scattered, out lightE, ref inoutRayCount, spheres, materials, ref randState)) { return mat.emissive + lightE + attenuation * Trace(scattered, depth + 1, ref inoutRayCount, spheres, materials, ref randState); } else { return mat.emissive; } } else { // sky float3 unitDir = r.dir; float t = 0.5f * (unitDir.y + 1.0f); return ((1.0f - t) * new float3(1.0f, 1.0f, 1.0f) + t * new float3(0.5f, 0.7f, 1.0f)) * 0.3f; } } [BurstCompile] struct TraceRowJob : IJobParallelFor { public int screenWidth, screenHeight, frameCount; [NativeDisableParallelForRestriction] public NativeArray<UnityEngine.Color> backbuffer; public Camera cam; [NativeDisableParallelForRestriction] public NativeArray<int> rayCounter; [NativeDisableParallelForRestriction] public NativeArray<Sphere> spheres; [NativeDisableParallelForRestriction] public NativeArray<Material> materials; public void Execute(int y) { int backbufferIdx = y * screenWidth; float invWidth = 1.0f / screenWidth; float invHeight = 1.0f / screenHeight; float lerpFac = (float)frameCount / (float)(frameCount + 1); #if DO_ANIMATE lerpFac *= DO_ANIMATE_SMOOTHING; #endif uint state = (uint)(y * 9781 + frameCount * 6271) | 1; int rayCount = 0; for (int x = 0; x < screenWidth; ++x) { float3 col = new float3(0, 0, 0); for (int s = 0; s < DO_SAMPLES_PER_PIXEL; s++) { float u = (x + MathUtil.RandomFloat01(ref state)) * invWidth; float v = (y + MathUtil.RandomFloat01(ref state)) * invHeight; Ray r = cam.GetRay(u, v, ref state); col += Trace(r, 0, ref rayCount, spheres, materials, ref state); } col *= 1.0f / (float)DO_SAMPLES_PER_PIXEL; col = sqrt(col); UnityEngine.Color prev = backbuffer[backbufferIdx]; col = new float3(prev.r, prev.g, prev.b) * lerpFac + col * (1 - lerpFac); backbuffer[backbufferIdx] = new UnityEngine.Color(col.x, col.y, col.z, 1); backbufferIdx++; } rayCounter[0] += rayCount; //@TODO: how to do atomics add? } } public void DrawTest(float time, int frameCount, int screenWidth, int screenHeight, NativeArray<UnityEngine.Color> backbuffer) { int rayCount = 0; #if DO_ANIMATE s_SpheresData[1].center.y = cos(time)+1.0f; s_SpheresData[8].center.z = sin(time)*0.3f; #endif float3 lookfrom = new float3(0, 2, 3); float3 lookat = new float3(0, 0, 0); float distToFocus = 3; float aperture = 0.1f; for (int i = 0; i < s_SpheresData.Length; ++i) s_SpheresData[i].UpdateDerivedData(); Camera cam = new Camera(lookfrom, lookat, new float3(0, 1, 0), 60, (float)screenWidth / (float)screenHeight, aperture, distToFocus); TraceRowJob job; job.screenWidth = screenWidth; job.screenHeight = screenHeight; job.frameCount = frameCount; job.backbuffer = backbuffer; job.cam = cam; job.rayCounter = new NativeArray<int>(1, Allocator.Temp); job.spheres = new NativeArray<Sphere>(s_SpheresData, Allocator.Temp); job.materials = new NativeArray<Material>(s_SphereMatsData, Allocator.Temp); var watch = System.Diagnostics.Stopwatch.StartNew(); var fence = job.Schedule(screenHeight, 4); fence.Complete(); rayCount = job.rayCounter[0]; watch.Stop(); Debug.Log("Done! Time taken: " + watch.ElapsedMilliseconds + "ms, Num Rays: " + rayCount); Debug.Log("That's about " + (rayCount / (watch.ElapsedMilliseconds/1000.0d)) / 1000000.0d + " MRay/sec"); job.rayCounter.Dispose(); job.spheres.Dispose(); job.materials.Dispose(); } } } public class ArasBurstTracer : MonoBehaviour { private Color[] _colors; private Texture2D _tex; public void Awake() { Test(1,1); // I broke it :( } private void Test(int resX, int resY) { var buf = new NativeArray<Color>(resX * resY, Allocator.Temp, NativeArrayOptions.UninitializedMemory); var test = new Aras.Test(); test.DrawTest(0f, 1, resX, resY, buf); _colors = new Color[resX * resY]; _tex = new Texture2D(resX, resY, TextureFormat.ARGB32, false, true); _tex.filterMode = FilterMode.Point; ToTexture2D(buf, _colors, _tex); buf.Dispose(); } private void OnGUI() { GUI.DrawTexture(new Rect(0f, 0f, _tex.width, _tex.height), _tex); } private static void ToTexture2D(NativeArray<Color> screen, Color[] colors, Texture2D tex) { for (int i = 0; i < screen.Length; i++) { var c = screen[i]; colors[i] = c; } tex.SetPixels(0, 0, tex.width, tex.height, colors, 0); tex.Apply(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercise9 { class Program { static void Main(string[] args) { Front front = new Front(); front.PutSomeEmployeeInList(); front.fronten(); } } }
public abstract class AbstractDepositPoint : AbstractBehaviorContainer { /// <summary> /// Check if the deposit point is "open" and accepting items. If /// the Deposit point is full or disabled, this should return /// false. public abstract bool isOpen(); }
using Autofac; using Autofac.Extensions.DependencyInjection; using Hangfire.Dashboard.Management.Extension.Support; using Hangfire.Dashboard.Management.Infrastructure; using Hangfire.JobSDK; using MediatR; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace Hangfire.Dashboard.Management.Extension { public static class IServiceCollectionExtensions { public static void AddManagementPages(this IServiceCollection services, IConfiguration config, IHostingEnvironment hostingEnvironment, string jobsRootFolder) { GlobalLoaderConfiguration.WebRootPath = hostingEnvironment.WebRootPath; GlobalLoaderConfiguration.ContentRootPath = hostingEnvironment.ContentRootPath; services.LoadInstalledModules(jobsRootFolder, hostingEnvironment); foreach (var module in GlobalLoaderConfiguration.Modules) { JobsHelper.GetAllJobs(module.Assembly); } services.Build(config, hostingEnvironment); } public static void AddManagementPages(this IServiceCollection services, IConfiguration config, IHostingEnvironment hostingEnvironment, params Assembly[] assemblies) { GlobalLoaderConfiguration.WebRootPath = hostingEnvironment.WebRootPath; GlobalLoaderConfiguration.ContentRootPath = hostingEnvironment.ContentRootPath; services.LoadInstalledModules(hostingEnvironment, assemblies); foreach (var module in GlobalLoaderConfiguration.Modules) { JobsHelper.GetAllJobs(module.Assembly); } services.Build(config, hostingEnvironment); } private static IServiceCollection LoadInstalledModules(this IServiceCollection services, IHostingEnvironment hostingEnvironment, Assembly[] assemblies) { var modules = new List<ModuleInfo>(); foreach (var assembly in assemblies) { var fileInfo = new FileInfo(typeof(string).Assembly.Location); var module = new ModuleInfo { Name = fileInfo.GetNameWithoutExtension(), Assembly = assembly, Path = fileInfo.FullName }; // Register dependency in modules var moduleInitializerType = module.Assembly.GetTypes().FirstOrDefault(x => typeof(IModuleInitializer).IsAssignableFrom(x)); if ((moduleInitializerType != null) && (moduleInitializerType != typeof(IModuleInitializer))) { var moduleInitializer = (IModuleInitializer)Activator.CreateInstance(moduleInitializerType); moduleInitializer.Init(services, hostingEnvironment.EnvironmentName); } modules.Add(module); } GlobalLoaderConfiguration.Modules = modules; return services; } private static IServiceCollection LoadInstalledModules(this IServiceCollection services, string modulesRootPath, IHostingEnvironment hostingEnvironment) { var modules = new List<ModuleInfo>(); var moduleRootFolder = new DirectoryInfo(modulesRootPath); var moduleFolders = moduleRootFolder.GetDirectories(); foreach (var moduleFolder in moduleFolders) { var binFolder = new DirectoryInfo(Path.Combine(moduleFolder.FullName, "bin")); if (!binFolder.Exists) { continue; } var assemblies = Directory .GetFiles(binFolder.FullName, "*.dll", SearchOption.AllDirectories) .Select(AssemblyLoadContext.Default.LoadFromAssemblyPath) .ToList(); foreach (var assembly in assemblies) { if (assembly.FullName.Contains(moduleFolder.Name)) { var module = new ModuleInfo { Name = moduleFolder.Name, Assembly = assembly, Path = moduleFolder.FullName }; // Register dependency in modules var moduleInitializerType = module.Assembly.GetTypes().FirstOrDefault(x => typeof(IModuleInitializer).IsAssignableFrom(x)); if ((moduleInitializerType != null) && (moduleInitializerType != typeof(IModuleInitializer))) { var moduleInitializer = (IModuleInitializer)Activator.CreateInstance(moduleInitializerType); moduleInitializer.Init(services, hostingEnvironment.EnvironmentName); } modules.Add(module); } } } GlobalLoaderConfiguration.Modules = modules; return services; } private static IServiceProvider Build(this IServiceCollection services, IConfiguration configuration, IHostingEnvironment hostingEnvironment) { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces(); builder.RegisterType<SequentialMediator>().As<IMediator>(); builder.Register<SingleInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => c.Resolve(t); }); builder.Register<MultiInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t)); }); foreach (var module in GlobalLoaderConfiguration.Modules) { builder.RegisterAssemblyTypes(module.Assembly).AsImplementedInterfaces(); } builder.RegisterInstance(configuration); builder.RegisterInstance(hostingEnvironment); builder.Populate(services); var container = builder.Build(); return container.Resolve<IServiceProvider>(); } } }
using log4net; using System; using System.Collections.Generic; //using System.Data.Entity.Validation; using System.Globalization; using System.Linq; using Anywhere2Go.Library; using System.IO; using Anywhere2Go.Library.Image; using Anywhere2Go.Library.Datatables; using ClaimDi.DataAccess; using ClaimDi.DataAccess.Object; using ClaimDi.DataAccess.Entity; using ClaimDi.DataAccess.Object.API; using System.Data.Entity.Validation; using System.Web.Script.Serialization; using System.Net.Http; using System.Net; using ClaimDi.Business.Utility; using System.Web; using System.Text; using Anywhere2Go.Business.Master; namespace ClaimDi.Business.Master { public class TaskConsumerLogic { public const string NEWID = "New ID"; private static readonly ILog logger = LogManager.GetLogger(typeof(TaskConsumerLogic)); MyContext _context = null; //public const int StatusOpenTask = 1001; //public const int StatusAcceptTask = 1002; //public const int StatusStartTask = 1003; //public const int StatusArrive = 1004; public const int StatusWaitApprove = 1005; public const int StatusEdit = 1006; public const int StatusPreApprove = 1014; public const int StatusApprovePicture = 1015; public const int StatusPolicyApprove = 1009; public const int StatusPolicyNotApprove = 1010; public const int StatusCancel = 1011; public const int StatusSurveyCallBack = 1020; //public const int StatusInvoice = 2001; //public const int StatusPay = 2002; public const string CalendarSectionNoAssign = "100"; public const string CalendarSectionBike = "200"; public const string PictureTypeAccessory = "PT01"; public const string PictureTypeDocument = "PT02"; public const string PictureTypeDamage = "PT03"; public const string PictureTypePart = "PT04"; public const string PictureTypeSignature = "PT05"; public const string PictureTypeInspectionDocument = "PT06"; public const string TaskTypeK4KId = "K4K"; public const string TaskTypeNAId = "NA"; public const string TaskTypeISPId = "ISP"; public const int ComTypeIdInsure = 1001; public static string[] ConsumerTypeGroup = new string[] { TaskTypeISPId, TaskTypeNAId, TaskTypeK4KId }; public const string CpyInsurance = "IN0050"; private string _language = string.Empty; public TaskConsumerLogic(string language = "th") { _language = language; _context = new MyContext(); } public TaskConsumerLogic(MyContext context) { _context = context; } public List<Task> GetTaskList(TaskSearchModel searchModel) { List<Task> TaskList = new List<Task>(); var req = new Repository<Task>(_context); List<Task> result = new List<Task>(); var query = req.GetQuery(); TaskList = query.ToList(); return TaskList; } public Task GetTaskById(string taskId) { var req = new Repository<Task>(_context); var query = req.GetQuery(); return query.Where(t => t.TaskId == taskId).SingleOrDefault(); } public Task GetTaskByIdSubscribeIns(string taskId, List<string> subscribeInsurer) { var req = new Repository<Task>(_context); var query = req.GetQuery(); if (subscribeInsurer.Count > 0) { query = query.Where(t => subscribeInsurer.Contains(t.InsId)); } return query.Where(t => t.TaskId == taskId).FirstOrDefault(); } public Task GetTaskPartyByToken(Guid? k4KPartyRefId) { var req = new Repository<Task>(_context); var query = req.GetQuery(); return query.Where(t => t.K4KOwnerRefId == k4KPartyRefId.Value).FirstOrDefault(); } public Task GetTaskById(Guid accId, string taskId) { var req = new Repository<Task>(_context); var query = req.GetQuery(); return query.Where(t => t.TaskId == taskId && t.AccId == accId).SingleOrDefault(); } public Task GetTaskByK4KOwner(Guid k4kOwnerRefId) { var req = new Repository<Task>(_context); var query = req.GetQuery(); return query.Where(t => t.K4KOwnerRefId == k4kOwnerRefId).SingleOrDefault(); } public BaseResult<bool?> UpdateIsUploadPicture(APIUpdateIsUploadPicture request) { BaseResult<bool?> response = new BaseResult<bool?>(); var validationResult = DataAnnotation.ValidateEntity<APIUpdateIsUploadPicture>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { var task = this.GetTaskById(Guid.Parse(request.AccId), request.TaskId); if (task != null) { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; task.IsUpload = true; task.UpdateBy = actionBy; this.SaveTask(task); } else { response.DataNotFound(); } } return response; } #region NA public BaseResult<APIAddTaskNaResponse> UpdateTaskNa(APIUpdateTaskNaRequest request) { BaseResult<APIAddTaskNaResponse> response = new BaseResult<APIAddTaskNaResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIUpdateTaskNaRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var carInfo = new CarInfoLogic(_context).GetCarInfoById(request.AccId, (int)request.CarId); var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == request.TaskId).SingleOrDefault(); if (task != null) { task.AccidentDate = DateExtension.ConvertStringToDateTime(request.AccidentDateTime, Constant.Format.ApiDateFormat); task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.AccidentPlace = request.AccidentPlace; task.AccidentProvince = request.AccidentProvice; task.AccidentDesc = request.AccidentDesc; task.CarId = request.CarId; task.DriverFirstName = request.DriverFirstName; task.DriverLastName = request.DriverLastName; task.DriverPhoneNumber = request.DriverNumber; task.TaskProcessId = TaskConsumerLogic.StatusWaitApprove; task.PolicyCode = (carInfo.CarPolicy != null ? carInfo.CarPolicy.PolicyCode : ""); task.PolicyStartdate = (carInfo.CarPolicy != null ? carInfo.CarPolicy.PolicyStartdate : null); task.PolicyEnddate = (carInfo.CarPolicy != null ? carInfo.CarPolicy.PolicyEnddate : null); task.PolicyFirstName = (carInfo.CarPolicy != null ? carInfo.CarPolicy.OwnerFirstName : ""); task.PolicyLastName = (carInfo.CarPolicy != null ? carInfo.CarPolicy.OwnerLastName : ""); task.PolicyPhoneNumber = (carInfo.CarPolicy != null ? carInfo.CarPolicy.OwnerPhoneNumber : ""); task.CarRegisFront = carInfo.CarRegisFront; task.CarRegisBack = carInfo.CarRegisBack; task.CarRegisProvinceCode = carInfo.CarRegisProvinceCode; // remove when user uncheck if (task.ClaimCauseOfLosses != null) { var tempClaimCauseOfLosses = task.ClaimCauseOfLosses.ToList(); foreach (var item in tempClaimCauseOfLosses) { if (!(request.ClaimCauseOfLosses != null && request.ClaimCauseOfLosses.Where(t => t.Id == item.Id).Count() > 0)) { //task.ClaimCauseOfLosses.Remove(item); this.RemoveClaimCauseOfLosses(item); } } } // add if (request.ClaimCauseOfLosses != null) { if (task.ClaimCauseOfLosses == null) { task.ClaimCauseOfLosses = new List<ClaimCauseOfLoss>(); } foreach (var item in request.ClaimCauseOfLosses) { if (item.Id == 0) { task.ClaimCauseOfLosses.Add(new ClaimCauseOfLoss { CauseId = item.CauseId, TaskId = task.TaskId, CreateDate = DateTime.Now, CreateBy = actionBy, UpdateDate = DateTime.Now, UpdateBy = actionBy }); } } } task.UpdateDate = DateTime.Now; req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskNaResponse(); response.Result.TaskId = task.TaskId; } else { response.DataNotFound(); } } catch (DbEntityValidationException ex) { foreach (var eve in ex.EntityValidationErrors) { logger.Error(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State)); foreach (var ve in eve.ValidationErrors) { logger.Error(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage)); } } logger.Error(string.Format("Method = {0}", "UpdateTaskNa"), ex); response.SystemError(ex); } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public BaseResult<APIAddTaskNaResponse> AddTaskNa(APIAddTaskNaRequest request) { BaseResult<APIAddTaskNaResponse> response = new BaseResult<APIAddTaskNaResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIAddTaskNaRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var carInfo = new CarInfoLogic(_context).GetCarInfoById(request.AccId, (int)request.CarId); var req = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); Task task = new Task(); task.AccId = Guid.Parse(request.AccId); task.TaskTypeId = TaskConsumerLogic.TaskTypeNAId; task.InsId = carInfo.CarPolicy.PolicyInsId; task.AccidentDate = DateExtension.ConvertStringToDateTime(request.AccidentDateTime, Constant.Format.ApiDateFormat); task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.AccidentPlace = request.AccidentPlace; task.AccidentProvince = request.AccidentProvice; task.AccidentDesc = request.AccidentDesc; task.CarId = request.CarId; task.DriverFirstName = request.DriverFirstName; task.DriverLastName = request.DriverLastName; task.DriverPhoneNumber = request.DriverNumber; task.TaskProcessId = TaskConsumerLogic.StatusWaitApprove; task.PolicyCode = (carInfo.CarPolicy != null ? carInfo.CarPolicy.PolicyCode : ""); task.PolicyStartdate = (carInfo.CarPolicy != null ? carInfo.CarPolicy.PolicyStartdate : null); task.PolicyEnddate = (carInfo.CarPolicy != null ? carInfo.CarPolicy.PolicyEnddate : null); task.PolicyFirstName = (carInfo.CarPolicy != null ? carInfo.CarPolicy.OwnerFirstName : ""); task.PolicyLastName = (carInfo.CarPolicy != null ? carInfo.CarPolicy.OwnerLastName : ""); task.PolicyPhoneNumber = (carInfo.CarPolicy != null ? carInfo.CarPolicy.OwnerPhoneNumber : ""); task.CarRegisFront = carInfo.CarRegisFront; task.CarRegisBack = carInfo.CarRegisBack; task.CarRegisProvinceCode = carInfo.CarRegisProvinceCode; task.CarBrandId = carInfo.CarBrandId; task.CarModelId = carInfo.CarModelId; task.TaskId = genID.GetNewID(1, "", task.TaskTypeId); if (request.ClaimCauseOfLosses != null) { task.ClaimCauseOfLosses = new List<ClaimCauseOfLoss>(); foreach (var item in request.ClaimCauseOfLosses) { task.ClaimCauseOfLosses.Add(new ClaimCauseOfLoss { CauseId = item.CauseId, TaskId = task.TaskId, CreateDate = DateTime.Now, CreateBy = actionBy, UpdateDate = DateTime.Now, UpdateBy = actionBy }); } } task.CreateDate = DateTime.Now; task.CreateBy = actionBy; task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; req.Add(task); req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskNaResponse(); response.Result.TaskId = task.TaskId; } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public BaseResult<long> saveTaskPicture(TaskPicture obj, Authentication authen, string updateBy = "") { BaseResult<long> res = new BaseResult<long>(); string acc_id = authen != null ? authen.acc_id : ""; string user = authen != null ? authen.first_name + " " + authen.last_name : ""; user = user == "" ? updateBy : user; try { var req = new Repository<TaskPicture>(_context); var reqTask = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); if (obj.PictureId == 0) // insert { obj.CreateBy = user; obj.CreateDate = DateTime.Now; obj.UpdateBy = user; obj.UpdateDate = DateTime.Now; obj.PictureParentId = (obj.PictureParentId == 0 ? null : obj.PictureParentId); obj.PictureParent = null; req.Add(obj); req.SaveChanges(); } else // update { var picture = req.Find(t => t.PictureId == obj.PictureId).FirstOrDefault(); if (picture != null) { if (obj.PictureApprove != null) { picture.PictureApprove = obj.PictureApprove; } if (!string.IsNullOrEmpty(obj.PictureNotApprove)) { picture.PictureNotApprove = obj.PictureNotApprove; } if (!string.IsNullOrEmpty(obj.PicturePath)) { picture.PicturePath = obj.PicturePath; } if (!string.IsNullOrEmpty(obj.PictureDesc)) { picture.PictureDesc = obj.PictureDesc; } if (!string.IsNullOrEmpty(obj.DamageLevelCode)) { picture.DamageLevelCode = obj.DamageLevelCode; } if (!string.IsNullOrEmpty(obj.PictureName)) { //for Reject Insurer Again // picture.PictureInsurerApprove = obj.PictureInsurerApprove; picture.PictureName = obj.PictureName; } if (!string.IsNullOrEmpty(obj.PictureTypeId)) { picture.PictureTypeId = obj.PictureTypeId; } picture.UpdateBy = user; picture.UpdateDate = DateTime.Now; picture.IsActive = obj.IsActive; req.SaveChanges(); } var task = reqTask.Find(t => t.TaskId == obj.TaskId).FirstOrDefault(); if (task != null) { task.UpdateBy = user; task.UpdateDate = DateTime.Now; reqTask.SaveChanges(); } } res.Result = obj.PictureId; } catch (Exception ex) { res.Result = 0; res.StatusCode = Constant.ErrorCode.SystemError; res.Message = ex.Message; logger.Error(string.Format("Method = {0},User = {1}", "saveTaskPicture", user), ex); } return res; } public BaseResult<APITaskNaDetailResponse> GetTaskNaDetail(string accId, string taskId) { BaseResult<APITaskNaDetailResponse> response = new BaseResult<APITaskNaDetailResponse>(); try { TaskConsumerLogic taskLogic = new TaskConsumerLogic(_context); var task = taskLogic.GetTaskById(Guid.Parse(accId), taskId); if (task != null) { response.Result = ConvertTaskToAPITaskNaDetail(task); } else { response.DataNotFound(); } } catch (Exception ex) { response.SystemError(ex); } return response; } #endregion #region INSPECTION public BaseResult<APIAddTaskInspectionResponse> AddTaskInspection(APIAddTaskInspectionRequest request) { BaseResult<APIAddTaskInspectionResponse> response = new BaseResult<APIAddTaskInspectionResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIAddTaskInspectionRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); Task task = new Task(); task.AccId = Guid.Parse(request.AccId); task.TaskTypeId = TaskConsumerLogic.TaskTypeISPId; task.TaskId = genID.GetNewID(1, "", task.TaskTypeId); task.InsId = request.PolicyInsId; task.CarRegisFront = request.CarRegisFront; task.CarRegisBack = request.CarRegisBack; task.CarRegisProvinceCode = request.CarRegisProvinceCode; task.CarModelId = request.CarModelId; task.CarBrandId = request.CarBrandId; task.CarMile = request.CarMile; task.PolicyFirstName = request.PolicyFirstName; task.PolicyLastName = request.PolicyLastName; task.PolicyPhoneNumber = request.PolicyPhoneNumber; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.Ref1 = request.Ref1; task.Ref2 = request.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(request.Ref2); task.CreateDate = DateTime.Now; task.CreateBy = actionBy; task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; req.Add(task); req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskInspectionResponse(); response.Result.TaskId = task.TaskId; } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public BaseResult<APIAddTaskInspectionResponse> UpdateTaskInspection(APIUpdateTaskInspectionRequest request) { BaseResult<APIAddTaskInspectionResponse> response = new BaseResult<APIAddTaskInspectionResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIUpdateTaskInspectionRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == request.TaskId).SingleOrDefault(); if (task != null) { task.InsId = request.PolicyInsId; task.CarRegisFront = request.CarRegisFront; task.CarRegisBack = request.CarRegisBack; task.CarRegisProvinceCode = request.CarRegisProvinceCode; task.CarModelId = request.CarModelId; task.CarBrandId = request.CarBrandId; task.CarMile = request.CarMile; task.PolicyFirstName = request.PolicyFirstName; task.PolicyLastName = request.PolicyLastName; task.PolicyPhoneNumber = request.PolicyPhoneNumber; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.Ref1 = request.Ref1; task.Ref2 = request.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(request.Ref2); task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskInspectionResponse(); response.Result.TaskId = task.TaskId; } else { response.DataNotFound(); } } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public string SubStringPrefixCodeFromRef2(string ref2) { string prefixCode = ""; if (!string.IsNullOrEmpty(ref2) && ref2.Length >= 3) { prefixCode = ref2.Substring(0, 3); } return prefixCode; } public BaseResult<bool?> UpdateStatusWaitApprove(APIUpdateStatusWaitApproveRequest request, HttpContext httpContext) { BaseResult<bool?> response = new BaseResult<bool?>(); var validationResult = DataAnnotation.ValidateEntity<APIUpdateStatusWaitApproveRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == request.TaskId).SingleOrDefault(); if (task != null) { task.TaskProcessId = TaskConsumerLogic.StatusWaitApprove; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; TaskProcessLogic taskprocess = new TaskProcessLogic(_context); var resProcessLog = taskprocess.CreateTaskProcessLog(taskprocess.ConvertTaskToTaskProvessLog(task)); req.SaveChanges(); con.Commit(); if (task.TaskTypeId == TaskTypeNAId) { response.Message = GetMessageResponseNa(task.InsId); RequestK4KLogLogic requestLogic = new RequestK4KLogLogic(_context); requestLogic.SendEmailWhenNARequest(task.TaskId, httpContext); } else if (task.TaskTypeId == TaskTypeISPId) { TaskBikeLogic taskBikeLogic = new TaskBikeLogic(_context); this.SendEmailWhenInspectionRequest(task.TaskId, httpContext); } } else { response.DataNotFound(); } } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public BaseResult<APITaskInspectionDetailResponse> GetTaskInspectionDetail(string accId, string taskId) { BaseResult<APITaskInspectionDetailResponse> response = new BaseResult<APITaskInspectionDetailResponse>(); try { TaskConsumerLogic taskLogic = new TaskConsumerLogic(_context); var task = taskLogic.GetTaskById(Guid.Parse(accId), taskId); if (task != null) { response.Result = ConvertTaskToAPITaskInspectionDetail(task); } else { response.DataNotFound(); } } catch (Exception ex) { response.SystemError(ex); } return response; } public string GetMessageResponseNa(string insId) { string messageResponseNa = ""; TemplateESlipLogic templateESlipLogic = new TemplateESlipLogic(); var templateESlip = templateESlipLogic.GetTemplateESlipByInsIdIfNullDefaultInsurerClaimdi(insId, TaskTypeNAId); messageResponseNa = (_language.ToUpper() == Constant.Language.DefaultLanguage ? templateESlip.MessageResponse : templateESlip.MessageResponseEn); return messageResponseNa; } #endregion public BaseResult<APITasksResponse> GetTasks(APITaskSearch request, SortingCriteria sorting = null) { BaseResult<APITasksResponse> response = new BaseResult<APITasksResponse>(); var validationResult = DataAnnotation.ValidateEntity<APITaskSearch>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { response.Result = new APITasksResponse(); if (sorting == null) { sorting = new SortingCriteria(); sorting.Add(new SortBy { Name = "CreateDate", Direction = SortDirection.DESC }); } if (request.PageIndex == 0) { request.PageIndex = 1; } if (request.PageSize == 0) { request.PageSize = 20; } response.Result.ThisPage = request.PageIndex; response.Result.PageSize = request.PageSize; if (response.Result.ThisPage <= 1) { response.Result.PreviousPage = 1; } else { response.Result.PreviousPage = request.PageIndex - 1; } PagingCriteria page = new PagingCriteria { PageIndex = request.PageIndex - 1, PageSize = request.PageSize }; var req = new Repository<Task>(_context); List<Task> result = new List<Task>(); var query = req.GetQuery(); var exp = ExpressionBuilder.True<Task>(); exp = exp.And(t => t.TaskProcessId != 0); if (!string.IsNullOrEmpty(request.AccId)) { var guidAccId = Guid.Parse(request.AccId); exp = exp.And(t => (t.AccId == guidAccId)); } if (!string.IsNullOrEmpty(request.TaskTypeId)) { exp = exp.And(t => t.TaskTypeId == request.TaskTypeId); } if (!string.IsNullOrEmpty(request.Criteria)) { DateTime criteria = DateTime.Parse(request.Criteria); exp = exp.And(t => (t.UpdateDate ?? t.CreateDate) > criteria); } response.Result.TotalRecord = query.Where(exp).Count(); var tasks = query.Where(exp).OrderBy(sorting).Skip(response.Result.ThisPage - 1).Take(response.Result.PageSize).ToList(); response.Result.Tasks = this.ConvertTasksToAPITaskInfo(tasks); if ((request.PageSize * request.PageIndex) > response.Result.TotalRecord) { response.Result.NextPage = request.PageIndex; } else { response.Result.NextPage = request.PageIndex + 1; } } return response; } public Func<Task, Object> GetTaskConsumerByConditionOrder(DTParameters param) { Func<Task, Object> orderByFunc = null; if (param.SortOrder == "TaskTypeName") { orderByFunc = item => item.TaskType.TaskTypeName; } else if (param.SortOrder == "InsName") { orderByFunc = item => item.Insurer.InsName; } else if (param.SortOrder == "CarRegisFront") { orderByFunc = item => item.CarRegisFront + " " + item.CarRegisBack; } else if (param.SortOrder == "TaskProcessName") { orderByFunc = item => item.TaskProcess.TaskProcessName; } else if (param.SortOrder == "FirstName") { orderByFunc = item => (item.AccountProfile.FirstName + ' ' + item.AccountProfile.LastName); } else if (param.SortOrder == "PolicyCode") { orderByFunc = item => item.PolicyCode; } else if (param.SortOrder == "Ref1") { orderByFunc = item => item.Ref1; } else if (param.SortOrder == "Ref2") { orderByFunc = item => item.Ref2; } else if (param.SortOrder == "TaskId") { orderByFunc = item => item.TaskId; } return orderByFunc; } public DTResult<TaskConsumerDataTables> GetTaskConsumerByCondition(DTParameters param, Authentication auth, List<string> subscribeInsurer, string notInBranchConsumer) { var req = new Repository<Task>(_context); var query = req.GetQuery(); var exp = ExpressionBuilder.True<Task>(); var expCount = ExpressionBuilder.True<Task>(); List<string> columnFilters = new List<string>(); if (subscribeInsurer.Count > 0 && (!(auth.Role.roleId == Constant.Permission.SystemAdmin))) { exp = exp.And(t => subscribeInsurer.Contains(t.InsId)); } exp = exp.And(p => p.TaskTypeId == Constant.TaskType.K4K || p.TaskTypeId == Constant.TaskType.NA || p.TaskTypeId == Constant.TaskType.ISP); exp = exp.And(p => p.TaskProcessId > 0); //count condition var startDate = param.GetSearchValueByColumnName("StartDate"); var endDate = param.GetSearchValueByColumnName("EndDate"); if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate)) { DateTime sDate = DateTime.ParseExact(startDate, "dd/MM/yyyy", CultureInfo.CurrentCulture); DateTime eDate = DateTime.ParseExact(endDate + " 23:59", "dd/MM/yyyy HH:mm", CultureInfo.CurrentCulture); exp = exp.And(t => (t.CreateDate >= sDate && t.CreateDate <= eDate)); } var typeId = param.GetSearchValueByColumnName("TaskTypeId"); if (!string.IsNullOrEmpty(typeId)) { exp = exp.And(p => p.TaskTypeId == typeId); } string insId = param.GetSearchValueByColumnName("InsId"); //ค้นหาบริษัทประกัน if (insId != "0" && insId != "") { //if (typeId == Constant.TaskType.ISP) //{ // exp = exp.And(p => p.InsId != null && p.InsId == insId); //} //else if (typeId == Constant.TaskType.NA || typeId == Constant.TaskType.K4K) //{ // exp = exp.And(p => p.CarInfo.CarPolicy.PolicyInsId != null && p.CarInfo.CarPolicy.PolicyInsId == insId); //} //else //{ exp = exp.And(p => (p.InsId != null && p.InsId == insId)); //} } //else //{ // string claimdiTraningId = "IN0066"; // exp = exp.And(p => p.InsId != claimdiTraningId); //} var taskProcessId = param.GetSearchValueByColumnName("TaskProcessId"); if (!string.IsNullOrEmpty(taskProcessId)) { int processId = int.Parse(taskProcessId); exp = exp.And(p => p.TaskProcessId == processId); } #region KeyTextSearch var taskid = param.GetSearchValueByColumnName("taskId"); if (!string.IsNullOrEmpty(taskid)) { exp = exp.And(p => p.TaskId.ToLower().Contains(taskid.ToLower())); //ค้นหารหัสงาน } //switch ($("#ddTextSearch").val()) { // case "1": //task id // data.columns[5].search.value = data.search.value; // break; // case "2": //car regis // data.columns[7].search.value = data.search.value; // break; // case "3": //Reference 1 // data.columns[9].search.value = data.search.value; // break; // case "4": //Reference 2 // data.columns[10].search.value = data.search.value; // break; // case "5": //FirstName // data.columns[13].search.value = data.search.value; // break; var carRegis = param.GetSearchValueByColumnName("CarRegisFront"); if (!string.IsNullOrEmpty(carRegis)) { exp = exp.And(p => (p.CarRegisFront.ToLower() + " " + p.CarRegisBack.ToLower() + (p.CarRegisProvince != null ? " " + p.CarRegisProvince.ProvinceName.ToLower() : "")).Contains(carRegis.ToLower())); //carRegis } var ref1 = param.GetSearchValueByColumnName("ref1"); if (!string.IsNullOrEmpty(ref1)) { exp = exp.And(p => p.Ref1.ToLower().Contains(ref1.ToLower())); //ref1 } var ref2 = param.GetSearchValueByColumnName("ref2"); if (!string.IsNullOrEmpty(ref2)) { exp = exp.And(p => p.Ref2.ToLower().Contains(ref2.ToLower())); //ref2 } var firstName = param.GetSearchValueByColumnName("firstName"); if (!string.IsNullOrEmpty(firstName)) { exp = exp.And(p => (p.AccountProfile.FirstName.ToLower().Contains(firstName.ToLower()) || p.AccountProfile.LastName.ToLower().Contains(firstName.ToLower()))); //ผู้ทำรายการ } var policyCode = param.GetSearchValueByColumnName("policyCode"); if (!string.IsNullOrEmpty(policyCode)) { exp = exp.And(p => p.PolicyCode.ToLower().Contains(policyCode.ToLower())); //ref2 } var prefixRef2 = param.GetSearchValueByColumnName("prefixRef2"); if (!string.IsNullOrEmpty(prefixRef2)) { var prefixRefsSplit = prefixRef2.Split(','); if (prefixRef2 == "999" && !string.IsNullOrEmpty(notInBranchConsumer)) { prefixRefsSplit = notInBranchConsumer.Split(','); exp = exp.And(p => !prefixRefsSplit.Contains(p.PrefixRef2.ToLower())); } else { exp = exp.And(p => prefixRefsSplit.Contains(p.PrefixRef2.ToLower())); } } //else //{ // if(!(auth.Role.roleId == Constant.Permission.SystemAdmin)) // { // exp = exp.And(p => p.PrefixRef2 == ""); // } //} #endregion //if (param != null) //{ // var exp2 = ExpressionBuilder.False<Task>(); // //---> ค้นหา wordding // exp2 = exp2.Or(p => (param.Search.Value == null)); //ถ้าไม่กรอกคำค้นหาให้แสดงทั้งหมด // exp2 = exp2.Or(p => p.TaskId.ToLower().Contains(param.Search.Value.ToString().ToLower())); // //if (!(auth.Role.roleId == Constant.Permission.SystemAdmin)) // // exp2 = exp2.Or(p => p.Insurer.InsName.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.CarRegisFront.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.CarRegisBack.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.PolicyCode.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.Ref1.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.Ref2.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.TaskType.TaskTypeName.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => p.TaskProcess.TaskProcessName.ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => (p.AccountProfile.FirstName + " " + p.AccountProfile.LastName).ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => (p.DriverFirstName + " " + p.DriverLastName).ToLower().Contains(param.Search.Value.ToString().ToLower())); // exp2 = exp2.Or(p => (p.CarRegisFront.ToLower() + " " + p.CarRegisBack.ToLower() + (p.CarRegisProvince != null ? " " + p.CarRegisProvince.ProvinceName.ToLower() : "")).Contains(param.Search.Value.ToString().ToLower())); // exp = exp.And(exp2); //} expCount = exp; var obj = new ResultSet<Task>(); var orderByFunc = GetTaskConsumerByConditionOrder(param); var dataList = obj.GetResultFuncOrderBy(param, query, exp, orderByFunc).Select((t, i) => new TaskConsumerDataTables { TaskId = t.TaskId, InsName = t.InsId != null ? CarInfoLogic.GetInsurerNameByInsurer(t.Insurer) : CarInfoLogic.GetInsurerNameByCarInfo(t.CarInfo, _language), TaskProcessName = t.TaskProcess.TaskProcessName, TaskTypeName = t.TaskType.TaskTypeName, CarRegisFront = t.CarRegisFront + " " + t.CarRegisBack.CheckStringNulltoString() + " " + (t.CarRegisProvinceCode != null ? t.CarRegisProvince.ProvinceName : ""), CreateDate = t.CreateDate.ConvertDateTimeToStringFormatDateTime(), PolicyCode = t.PolicyCode.CheckStringNull(), Ref1 = t.Ref1.CheckStringNull(), Ref2 = t.Ref2.CheckStringNull(), FirstName = (t.AccountProfile.FirstName.CheckStringNulltoString() + " " + t.AccountProfile.LastName.CheckStringNulltoString()).CheckStringNull(), InsId = t.InsId != null ? t.InsId : t.InsId, TaskProcessId = t.TaskProcessId, TaskTypeId = t.TaskTypeId, UpdateDate = t.UpdateDate.ConvertDateTimeToStringFormatDateTime(), IsSendInsurance = t.TaskTypeId == Constant.TaskType.K4K || t.TaskTypeId == Constant.TaskType.NA ? (t.IsSendInsurance.HasValue ? (t.IsSendInsurance.Value ? "ผ่าน" : "ไม่ผ่าน") : "ยังไม่ขอ") : "-", PrefixRef2 = t.PrefixRef2 }).ToList(); var allObj = query.Where(expCount); DTResult<TaskConsumerDataTables> result = new DTResult<TaskConsumerDataTables> { draw = param.Draw, data = dataList, recordsFiltered = obj.rowCount, recordsTotal = obj.rowCount, await = allObj.Count(t => t.TaskProcessId == StatusWaitApprove), editTask = allObj.Count(t => t.TaskProcessId == StatusEdit), preApprove = allObj.Count(t => t.TaskProcessId == StatusPreApprove), imgApprove = allObj.Count(t => t.TaskProcessId == StatusApprovePicture), approved = allObj.Count(t => t.TaskProcessId == StatusPolicyApprove), }; return result; } public void AddTask(Task model) { try { var req = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); model.TaskId = genID.GetNewID(1, "", model.TaskTypeId); model.CreateDate = DateTime.Now; model.UpdateDate = DateTime.Now; req.Add(model); req.SaveChanges(); } catch (Exception ex) { throw ex; } } public void SaveTaskAfterCallNoticeInsurer(Task model) { try { var req = new Repository<Task>(_context); var task = req.GetQuery().Where(t => t.TaskId == model.TaskId).FirstOrDefault(); task.NoticeCode = model.NoticeCode; task.NoticeCodeDate = model.NoticeCodeDate; if (model.IsSendInsurance != null) { task.IsSendInsurance = model.IsSendInsurance; } task.SendInsuranceMessage = model.SendInsuranceMessage; task.SendInsuranceError = model.SendInsuranceError; task.NoticeCodeBy = model.NoticeCodeBy; if (!string.IsNullOrEmpty(model.UpdateBy)) { task.UpdateBy = model.UpdateBy; } else { task.UpdateBy = "system"; } req.SaveChanges(); } catch (Exception ex) { throw ex; } } public void SaveTask(Task model) { try { var req = new Repository<Task>(_context); model.UpdateDate = DateTime.Now; req.SaveChanges(); } catch (Exception ex) { throw ex; } } public void RemoveClaimCauseOfLosses(ClaimCauseOfLoss model) { var req = new Repository<ClaimCauseOfLoss>(_context); req.Remove(model); req.SaveChanges(); } public BaseResult<K4KResult> ValidatePolicyNa(APIValidatePolicyRequest request) { BaseResult<K4KResult> response = new BaseResult<K4KResult>(); try { var validationResult = DataAnnotation.ValidateEntity<APIValidatePolicyRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else if (request.CarId == 0) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = "The CarId field is required."; } else { CarInfoLogic carInfoLogic = new CarInfoLogic(_context); var carInfo = new CarInfoLogic(_context).GetCarInfoById(request.AccId, request.CarId.Value); if (carInfo != null) { ApiHttpProcessor apiProcessor = new ApiHttpProcessor(string.Empty); PolicyRequest policyRequest = new PolicyRequest(); policyRequest.car_license_no = carInfo.CarRegisFront + carInfo.CarRegisBack; policyRequest.car_license_no_front = carInfo.CarRegisFront; policyRequest.car_license_no_back = carInfo.CarRegisBack; policyRequest.car_license_province = carInfo.CarRegisProvince.ProvinceName; policyRequest.car_license_province_short = carInfo.CarRegisProvince.ProvinceTitle; policyRequest.insurer_id = carInfo.CarPolicy.PolicyInsId; policyRequest.driver_first_name = request.DriverName; policyRequest.driver_last_name = request.DriverLastname; policyRequest.driver_mobile_no = request.DriverNumber; policyRequest.policy_no = carInfo.CarPolicy.PolicyCode; string json = new JavaScriptSerializer().Serialize(policyRequest); ApiResponse apiResponse = apiProcessor.ExecutePOST(Configurator.UriValidatePolicyNa, new StringContent(json), ApiHttpProcessor.contentTypeJson); if (apiResponse.StatusCode == HttpStatusCode.OK) { JavaScriptSerializer json_serializer = new JavaScriptSerializer(); if (apiResponse.ResponseContent != "") { response = json_serializer.Deserialize<BaseResult<K4KResult>>(apiResponse.ResponseContent); if (response.Result.policy != null) { //ถ้ามีข้อมูล กรมธรรม์ จะเอาข้อมูลเจ้าของ กรมธรรม์ บันทึกในรถคันนั้นด้วย var resultPolicy = response.Result.policy; if (!string.IsNullOrEmpty(resultPolicy.owner_first_name)) { carInfo.CarPolicy.OwnerFirstName = resultPolicy.owner_first_name; } if (!string.IsNullOrEmpty(resultPolicy.owner_last_name)) { carInfo.CarPolicy.OwnerLastName = resultPolicy.owner_last_name; } if (!string.IsNullOrEmpty(resultPolicy.owner_mobile_no)) { carInfo.CarPolicy.OwnerPhoneNumber = resultPolicy.owner_mobile_no; } if (!string.IsNullOrEmpty(resultPolicy.policy_no)) { carInfo.CarPolicy.PolicyCode = resultPolicy.policy_no; } carInfoLogic.UpdateCar(carInfo); } } else { response.DataNotFound(); response.Result.result = new Result { success = "false", message = "not data" }; } } else { response.Result = new K4KResult(); response.Result.result = new Result { success = "false", message = apiResponse.ResponseContent }; response.ThirdPartyError(); } if (response.Result.result != null) { response.Result.result.GetSuccessBool(); } } else { response.DataNotFound(); } } } catch (Exception ex) { response.SystemError(ex); } return response; } public List<APITaskInfo> ConvertTasksToAPITaskInfo(List<Task> model) { List<APITaskInfo> response = null; if (model != null) { response = new List<APITaskInfo>(); var insurerLogic = new InsurerLogic(_language); foreach (var item in model) { if (item.TaskTypeId == TaskConsumerLogic.TaskTypeISPId) { response.Add(ConvertTaskInspectionToAPITaskInfo(item)); } else { response.Add(new APITaskInfo { AccidentDate = DateExtension.ConvertDateTimeToString(item.AccidentDate, Constant.Format.ApiDateMonthFormat, _language), AccidentDateTime = DateExtension.ConvertDateTimeToString(item.AccidentDate, Constant.Format.ApiDateFormat, _language), AccidentTime = DateExtension.ConvertDateTimeToString(item.AccidentDate, Constant.Format.ApiTimeOnlyFormat, _language), CarBrandName = CarInfoLogic.GetCarBrandNameByCarBrand(item.CarBrand), CarModelName = CarInfoLogic.GetCarModelNameByCarModel(item.CarModel), CarRegisProvinceName = (item.CarInfo != null ? CarInfoLogic.GetCarRegisProvinceNameByCarRegisProvince(item.CarRegisProvince, _language) : ""), CarRegisBack = item.CarRegisBack, CarRegisFront = item.CarRegisFront, InsurerName = CarInfoLogic.GetInsurerNameByInsurer(item.Insurer, _language), TaskId = item.TaskId, TaskProcessId = item.TaskProcessId.ToString(), TaskProcessName = TaskConsumerLogic.GetTaskProcessNameByTaskProcess(item.TaskProcess, _language), TaskTypeId = item.TaskTypeId, CreateDate = DateExtension.ConvertDateTimeToString(item.CreateDate, Constant.Format.ApiDateMonthFormat, _language), CreateDateTime = DateExtension.ConvertDateTimeToString(item.CreateDate, Constant.Format.ApiDateFormat, _language), CreateTime = DateExtension.ConvertDateTimeToString(item.CreateDate, Constant.Format.ApiTimeOnlyFormat, _language), }); } } } return response; } public APITaskInfo ConvertTaskInspectionToAPITaskInfo(Task model) { APITaskInfo taskInfo = new APITaskInfo(); taskInfo.CarBrandName = CarInfoLogic.GetCarBrandNameByCarBrand(model.CarBrand); taskInfo.CarModelName = CarInfoLogic.GetCarModelNameByCarModel(model.CarModel); taskInfo.CarRegisBack = model.CarRegisBack; taskInfo.CarRegisFront = model.CarRegisFront; taskInfo.CarRegisProvinceName = CarInfoLogic.GetCarRegisProvinceNameByCarRegisProvince(model.CarRegisProvince, _language); taskInfo.InsurerName = CarInfoLogic.GetInsurerNameByInsurer(model.Insurer, _language); taskInfo.TaskId = model.TaskId; taskInfo.TaskProcessId = model.TaskProcessId.ToString(); taskInfo.TaskProcessName = TaskConsumerLogic.GetTaskProcessNameByTaskProcessInspection(model.TaskProcess, _language); taskInfo.TaskTypeId = model.TaskTypeId; taskInfo.CreateDate = DateExtension.ConvertDateTimeToString(model.CreateDate, Constant.Format.ApiDateMonthFormat, _language); taskInfo.CreateDateTime = DateExtension.ConvertDateTimeToString(model.CreateDate, Constant.Format.ApiDateFormat, _language); taskInfo.CreateTime = DateExtension.ConvertDateTimeToString(model.CreateDate, Constant.Format.ApiTimeOnlyFormat, _language); return taskInfo; } public static string GetTaskProcessNameByTaskProcessInspection(TaskProcess model, string language) { if (model != null) { // Requirement ถ้าสถานะงานเป็น อนุมัติเบื้องต้น ให้แสดงเป็น รออนุมัติ if (model.TaskProcessId == TaskConsumerLogic.StatusPreApprove) { TaskProcessLogic taskProcessLogic = new TaskProcessLogic(); var taskProcessDefault = taskProcessLogic.GetTaskProcessById(TaskConsumerLogic.StatusWaitApprove); return (language.ToUpper() == Constant.Language.DefaultLanguage ? taskProcessDefault.TaskProcessName : taskProcessDefault.TaskProcessNameEn); } else { return (language.ToUpper() == Constant.Language.DefaultLanguage ? model.TaskProcessName : model.TaskProcessNameEn); } } return ""; } public static string GetTaskProcessNameByTaskProcess(TaskProcess model, string language) { if (model != null) { return (language.ToUpper() == Constant.Language.DefaultLanguage ? model.TaskProcessName : model.TaskProcessNameEn); } return ""; } public APITaskNaDetailResponse ConvertTaskToAPITaskNaDetail(Task model) { APITaskNaDetailResponse response = null; if (model != null) { CarInfoLogic carInfoLogic = new CarInfoLogic(_language); PartyAtFaultLogic partyAtFault = new PartyAtFaultLogic(); TemplateESlipLogic templateESlip = new TemplateESlipLogic(); RequestK4KLogLogic requestK4KLogLogic = new RequestK4KLogLogic(_language); response = new APITaskNaDetailResponse(); response.AccidentDate = DateExtension.ConvertDateTimeToString(model.AccidentDate, Constant.Format.ApiDateNAOnlyFormat, "EN"); response.AccidentDateTime = DateExtension.ConvertDateTimeToStringEn(model.AccidentDate, Constant.Format.ApiDateFormat); response.AccidentTime = DateExtension.ConvertDateTimeToString(model.AccidentDate, Constant.Format.ApiTimeOnlyFormat); response.CarInfo = requestK4KLogLogic.ConvertTaskToAPICarInfo(model); response.ClaimCauseOfLosses = this.ConvertClaimCauseOfLossToAPIClaimCauseOfLoss(model.ClaimCauseOfLosses); response.DriverFirstName = model.DriverFirstName; response.DriverLastName = model.DriverLastName; response.DriverNumber = model.DriverPhoneNumber; response.TemplateESlip = this.ConvertTemplateESlipToAPITemplateESlip(templateESlip.GetTemplateESlipByInsIdIfNullDefaultInsurerClaimdi(model.InsId, TaskConsumerLogic.TaskTypeNAId)); response.TaskId = model.TaskId; response.ClaimItems = this.ConvertClaimItemsToAPIClaimItems(model.ClaimItems); response.TaskProcess = this.ConvertTaskProcessToAPITaskProcess(model.TaskProcess); response.PictureSignature = requestK4KLogLogic.ConvertTaskPictureToAPITaskPicture(model.TaskPictures.Where(t => t.PictureTypeId == TaskConsumerLogic.PictureTypeSignature).FirstOrDefault()); response.Pictures = requestK4KLogLogic.ConvertTaskPictureToAPITaskPictures(model.TaskPictures.Where(t => t.PictureTypeId != TaskConsumerLogic.PictureTypeSignature).ToList()); response.Latitude = model.Latitude; response.Longitude = model.Longitude; response.AccidentPlace = model.AccidentPlace; response.AccidentProvince = model.AccidentProvince; response.AccidentDesc = model.AccidentDesc; response.DeductExcessMessage = model.DeductExcessMessage; response.NoticeCode = model.NoticeCode; response.NoticeDate = DateExtension.ConvertDateTimeToString(model.NoticeCodeDate, Constant.Format.ApiDateNAOnlyFormat, "EN"); response.NoticeDateTime = DateExtension.ConvertDateTimeToStringEn(model.NoticeCodeDate, Constant.Format.ApiDateFormat); response.NoticeTime = DateExtension.ConvertDateTimeToString(model.NoticeCodeDate, Constant.Format.ApiTimeOnlyFormat); response.NoticeCodeBy = model.NoticeCodeBy; } return response; } public APITaskInspectionDetailResponse ConvertTaskToAPITaskInspectionDetail(Task model) { APITaskInspectionDetailResponse response = null; if (model != null) { CarInfoLogic carInfoLogic = new CarInfoLogic(_language); RequestK4KLogLogic requestK4KLogLogic = new RequestK4KLogLogic(_language); response = new APITaskInspectionDetailResponse(); response.AccId = model.AccId.ToString(); response.CarBrand = carInfoLogic.ConvertCarBrandToSyncCarBrand(model.CarBrand); response.CarBrandId = model.CarBrandId; response.CarMile = model.CarMile; response.CarModel = carInfoLogic.ConvertCarModelToSyncCarModel(model.CarModel); response.CarModelId = model.CarModelId; response.CarRegisBack = model.CarRegisBack; response.CarRegisFront = model.CarRegisFront; response.CarRegisProvinceCode = model.CarRegisProvinceCode; response.CarRegisProvince = carInfoLogic.ConvertProvinceToSyncProvince(model.CarRegisProvince); response.Latitude = model.Latitude; response.Longitude = model.Longitude; response.PolicyFirstName = model.PolicyFirstName; response.PolicyLastName = model.PolicyLastName; response.PolicyPhoneNumber = model.PolicyPhoneNumber; response.PolicyInsId = model.InsId; response.PolicyInsurer = new InsurerLogic(_language).ConvertInsurerToSyncInsurer(model.Insurer); response.TaskId = model.TaskId; response.Ref1 = model.Ref1; response.Ref2 = model.Ref2; response.TaskProcess = this.ConvertTaskProcessToAPITaskProcessInspection(model.TaskProcess); response.PictureSignature = requestK4KLogLogic.ConvertTaskPictureToAPITaskPicture(model.TaskPictures.Where(t => t.PictureTypeId == TaskConsumerLogic.PictureTypeSignature).FirstOrDefault()); response.Pictures = requestK4KLogLogic.ConvertTaskPictureToAPITaskPictures(model.TaskPictures.Where(t => t.PictureTypeId != TaskConsumerLogic.PictureTypeSignature).ToList()); } return response; } public APITaskProcess ConvertTaskProcessToAPITaskProcessInspection(TaskProcess taskProcess) { APITaskProcess response = null; if (taskProcess != null) { response = new APITaskProcess(); response.TaskProcessId = taskProcess.TaskProcessId.ToString(); response.TaskProcessName = TaskConsumerLogic.GetTaskProcessNameByTaskProcessInspection(taskProcess, _language); } return response; } public APITaskProcess ConvertTaskProcessToAPITaskProcess(TaskProcess taskProcess) { APITaskProcess response = null; if (taskProcess != null) { response = new APITaskProcess(); response.TaskProcessId = taskProcess.TaskProcessId.ToString(); response.TaskProcessName = (_language.ToUpper() == Constant.Language.DefaultLanguage ? taskProcess.TaskProcessName : taskProcess.TaskProcessName); } return response; } public List<APIClaimCauseOfLoss> ConvertClaimCauseOfLossToAPIClaimCauseOfLoss(List<ClaimCauseOfLoss> claimCauseOfLoss) { List<APIClaimCauseOfLoss> response = null; if (claimCauseOfLoss != null) { response = new List<APIClaimCauseOfLoss>(); foreach (var item in claimCauseOfLoss) { response.Add(new APIClaimCauseOfLoss { Id = item.Id, CauseId = item.CauseId, CauseOfLoss = this.ConvertCauseOfLossToSyncCauseOfLoss(item.CauseOfLoss) }); } } return response; } public SyncCauseOfLoss ConvertCauseOfLossToSyncCauseOfLoss(CauseOfLoss causeOfLoss) { SyncCauseOfLoss response = null; if (causeOfLoss != null) { response = new SyncCauseOfLoss(); response.CauseGroup = causeOfLoss.CauseGroup; response.CauseId = causeOfLoss.CauseId; response.CauseName = (_language.ToUpper() == Constant.Language.DefaultLanguage ? causeOfLoss.CauseName : causeOfLoss.CauseNameEn); response.isActive = causeOfLoss.IsActive; response.Sort = causeOfLoss.Sort; } return response; } public List<APIClaimItem> ConvertClaimItemsToAPIClaimItems(List<ClaimItem> claimItems) { List<APIClaimItem> response = null; if (claimItems != null) { response = new List<APIClaimItem>(); foreach (var item in claimItems) { response.Add(new APIClaimItem { Id = item.Id, ItemDesc = item.ItemDesc, ItemName = item.ItemName }); } } return response; } public APITemplateESlip ConvertTemplateESlipToAPITemplateESlip(TemplateESlip model) { APITemplateESlip response = null; if (model != null) { response = new APITemplateESlip(); response.DeductTitle = (_language.ToUpper() == Constant.Language.DefaultLanguage ? model.DeDuctTitle : model.DeDuctTitleEn); response.DriverTitle = (_language.ToUpper() == Constant.Language.DefaultLanguage ? model.DriverTitle : model.DriverTitleEn); response.Footer = (_language.ToUpper() == Constant.Language.DefaultLanguage ? model.Footer : model.FooterEn); response.NoticeTitle = (_language.ToUpper() == Constant.Language.DefaultLanguage ? model.NoticeTitle : model.NoticeTitleEn); response.InsuranceApprover = (_language.ToUpper() == Constant.Language.DefaultLanguage ? model.InsuranceApprover : model.InsuranceApproverEn); } return response; } public BaseResult<TaskActionModel> SaveTaskConsumer(Task model, Authentication auth) { BaseResult<TaskActionModel> res = new BaseResult<TaskActionModel>(); var user = auth.first_name + " " + auth.last_name; try { model.UpdateBy = user; if (model.TaskTypeId == Constant.TaskType.NA) { res = UpdateTaskNaBackEnd(model, auth); } else if (model.TaskTypeId == Constant.TaskType.ISP) { res = UpdateTaskISPBackEnd(model, auth); } if (model.TaskTypeId == Constant.TaskType.K4K) { res = UpdateTaskK4kBackEnd(model, auth); } if (res.Result.IsSendPush) { try { FCMNotification gcm = new FCMNotification(); gcm.Push(res.Result.Task, res.Result.PushType); } catch (Exception ex) { logger.Error(string.Format("Method = {0},User = {1}", "PushNotification", user), ex); } } } catch (Exception ex) { res.Result.Success = false; res.Message = ex.Message; logger.Error(string.Format("Method = {0},User = {1}", "SaveTaskConsumer", user), ex); throw ex; } return res; } public void RemoveClaimItem(ClaimItem model) { var req = new Repository<ClaimItem>(_context); req.Remove(model); req.SaveChanges(); } public BaseResult<TaskActionModel> UpdateTaskNaBackEnd(Task model, Authentication auth) { BaseResult<TaskActionModel> response = new BaseResult<TaskActionModel>(); using (var con = _context.Database.BeginTransaction()) { try { var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == model.TaskId).SingleOrDefault(); response.Result = new TaskActionModel(); if (task != null) { if (model.TaskTypeId != Constant.TaskType.K4K) { task.NoticeCodeDate = model.NoticeCodeDate; task.NoticeCode = model.NoticeCode; task.NoticeCodeBy = model.UpdateBy; task.DeductExcessMessage = model.DeductExcessMessage; } if (model.IsSendInsurance.HasValue) { task.IsSendInsurance = model.IsSendInsurance; } if (model.TaskProcessId != 0 && task.TaskProcessId != model.TaskProcessId) { task.TaskProcessId = model.TaskProcessId; if (model.TaskProcessId != StatusPreApprove) { if (model.TaskProcessId == StatusPolicyApprove) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.ApprovePolicy; } else if (model.TaskProcessId == StatusEdit) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.EditTask; } else if (model.TaskProcessId == StatusCancel) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.CancelTask; } else if (model.TaskProcessId == StatusPolicyNotApprove) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.InApprovePolicy; } else if (model.TaskProcessId == StatusSurveyCallBack) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.SurveyCallBack; } } TaskProcessLog taskProcessLog = new TaskProcessLog(); taskProcessLog.TaskId = model.TaskId; taskProcessLog.Latitude = "0"; taskProcessLog.Longitude = "0"; taskProcessLog.CreateDate = DateTime.Now; taskProcessLog.CreateBy = model.UpdateBy; taskProcessLog.TaskProcessId = model.TaskProcessId; TaskProcessLogic taskprocess = new TaskProcessLogic(_context); var resProcessLog = taskprocess.CreateTaskProcessLog(taskProcessLog); } if (model.ClaimItems != null) { if (task.ClaimItems == null) { task.ClaimItems = new List<ClaimItem>(); } foreach (var item in model.ClaimItems) { if (item.Id == 0) { if (!string.IsNullOrEmpty(item.ItemName) || !string.IsNullOrEmpty(item.ItemDesc)) { task.ClaimItems.Add(new ClaimItem { TaskId = task.TaskId, ItemName = item.ItemName, ItemDesc = item.ItemDesc, CreateDate = DateTime.Now, CreateBy = model.UpdateBy, UpdateDate = DateTime.Now, UpdateBy = model.UpdateBy, }); } } else { var reqitem = new Repository<ClaimItem>(_context); ClaimItem claimItem = reqitem.GetQuery().Where(t => t.Id == item.Id).SingleOrDefault(); claimItem.UpdateBy = item.UpdateBy; claimItem.UpdateDate = DateTime.Now; claimItem.ItemName = item.ItemName; claimItem.ItemDesc = item.ItemDesc; reqitem.SaveChanges(); if (string.IsNullOrEmpty(item.ItemName) && string.IsNullOrEmpty(item.ItemDesc)) { this.RemoveClaimItem(claimItem); } } } } // เกี่ยวกับ Approve or Reject รูปภาพ if (model.TaskTypeId != Constant.TaskType.K4K && model.TaskPictures != null && model.TaskPictures.Count > 0) { foreach (var picture in model.TaskPictures) { var taskPicture = task.TaskPictures.Where(t => t.PictureId == picture.PictureId).SingleOrDefault(); taskPicture.PictureApprove = picture.PictureApprove; taskPicture.PictureNotApprove = picture.PictureNotApprove; } } task.PrefixRef2 = SubStringPrefixCodeFromRef2(model.Ref2); task.UpdateDate = DateTime.Now; task.UpdateBy = model.UpdateBy; req.SaveChanges(); con.Commit(); var taskData = GetTaskById(task.TaskId); response.Result.Success = true; response.Result.TaskId = task.TaskId; response.Result.Task = taskData; } else { response.DataNotFound(); } } catch (DbEntityValidationException ex) { foreach (var eve in ex.EntityValidationErrors) { logger.Error(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State)); foreach (var ve in eve.ValidationErrors) { logger.Error(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage)); } } logger.Error(string.Format("Method = {0}", "UpdateTaskNaBackEnd"), ex); response.SystemError(ex); } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } return response; } public BaseResult<TaskActionModel> UpdateTaskK4kBackEnd(Task model, Authentication auth) { BaseResult<TaskActionModel> response = new BaseResult<TaskActionModel>(); using (var con = _context.Database.BeginTransaction()) { try { var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == model.TaskId).SingleOrDefault(); response.Result = new TaskActionModel(); if (task != null) { if (model.IsSendInsurance.HasValue) { if (!task.IsSendInsurance.HasValue || !task.IsSendInsurance.Value) { task.IsSendInsurance = model.IsSendInsurance; } } task.PrefixRef2 = SubStringPrefixCodeFromRef2(model.Ref2); task.UpdateDate = DateTime.Now; task.UpdateBy = model.UpdateBy; req.SaveChanges(); con.Commit(); var taskData = GetTaskById(task.TaskId); response.Result.Success = true; response.Result.TaskId = task.TaskId; response.Result.Task = taskData; } else { response.DataNotFound(); } } catch (DbEntityValidationException ex) { foreach (var eve in ex.EntityValidationErrors) { logger.Error(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State)); foreach (var ve in eve.ValidationErrors) { logger.Error(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage)); } } logger.Error(string.Format("Method = {0}", "UpdateTaskK4kBackEnd"), ex); response.SystemError(ex); } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } return response; } public BaseResult<TaskActionModel> UpdateTaskISPBackEnd(Task model, Authentication auth) { BaseResult<TaskActionModel> response = new BaseResult<TaskActionModel>(); using (var con = _context.Database.BeginTransaction()) { try { var req = new Repository<Task>(_context); response.Result = new TaskActionModel(); Task task = req.GetQuery().Where(t => t.TaskId == model.TaskId).SingleOrDefault(); if (task != null) { task.Ref1 = model.Ref1; task.Ref2 = model.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(model.Ref2); task.Note = model.Note; task.InsureRemark = model.InsureRemark; task.DamageConclusion = model.DamageConclusion; if (model.TaskProcessId != 0 && task.TaskProcessId != model.TaskProcessId) { task.TaskProcessId = model.TaskProcessId; if (model.TaskProcessId != StatusPreApprove) { if (model.TaskProcessId == StatusApprovePicture) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.ApproveImage; } if (model.TaskProcessId == StatusPolicyApprove) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.ApprovePolicy; } else if (model.TaskProcessId == StatusEdit) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.EditTask; } else if (model.TaskProcessId == StatusCancel) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.CancelTask; } else if (model.TaskProcessId == StatusPolicyNotApprove) { response.Result.IsSendPush = true; response.Result.PushType = FCMNotification.EPushType.InApprovePolicy; } } TaskProcessLog taskProcessLog = new TaskProcessLog(); // taskProcessLog.AccId = model.AssignAccId; taskProcessLog.TaskId = model.TaskId; taskProcessLog.Latitude = "0"; taskProcessLog.Longitude = "0"; taskProcessLog.CreateDate = DateTime.Now; taskProcessLog.CreateBy = model.UpdateBy; taskProcessLog.TaskProcessId = model.TaskProcessId; TaskProcessLogic taskprocess = new TaskProcessLogic(_context); var resProcessLog = taskprocess.CreateTaskProcessLog(taskProcessLog); } // เกี่ยวกับ Approve or Reject รูปภาพ if (model.TaskPictures != null && model.TaskPictures.Count > 0) { foreach (var picture in model.TaskPictures) { var taskPicture = task.TaskPictures.Where(t => t.PictureId == picture.PictureId).SingleOrDefault(); //ประกัน Approve //if (auth.com_type_id == ComTypeIdInsure) //if (auth.com_type_id == ComTypeIdInsure) //{ // //ถ้ายังไม่ถูก Approve รูปภาพจาก ClaimDi // if (taskPicture.PictureApprove == null) // { // taskPicture.PictureApprove = picture.PictureApprove; // // taskPicture.PictureNotApprove = picture.PictureNotApprove; // } // taskPicture.PictureInsurerApprove = picture.PictureInsurerApprove; // if (!string.IsNullOrEmpty(picture.PictureInsurerRemark)) // { // taskPicture.PictureInsurerRemark = picture.PictureInsurerRemark; // } //} //else //{ taskPicture.PictureApprove = picture.PictureApprove; if (!string.IsNullOrEmpty(picture.PictureNotApprove)) { taskPicture.PictureNotApprove = picture.PictureNotApprove; } // } } } task.UpdateDate = DateTime.Now; task.UpdateBy = model.UpdateBy; req.SaveChanges(); con.Commit(); var taskData = GetTaskById(task.TaskId); response.Result.Success = true; response.Result.TaskId = task.TaskId; response.Result.Task = taskData; } else { response.DataNotFound(); } } catch (DbEntityValidationException ex) { foreach (var eve in ex.EntityValidationErrors) { logger.Error(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State)); foreach (var ve in eve.ValidationErrors) { logger.Error(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage)); } } logger.Error(string.Format("Method = {0}", "UpdateTaskNaBackEnd"), ex); response.SystemError(ex); } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } return response; } #region SendInsuranceNotice public NARequestData ConvertTaskToK4KRequest(Task model) { NARequestData response = null; if (model != null) { response = new NARequestData(); response.Location = this.ConvertTaskToLocation(model); response.policyOwner = this.ConvertTasKToPolicyOwner(model.K4KOwner); } return response; } public Location ConvertTaskToLocation(Task model) { Location response = null; if (model != null) { response = new Location(); response.caseNumber = ""; response.latitude = model.Latitude; response.longitude = model.Longitude; response.place = model.AccidentPlace; } return response; } public PolicyOwner ConvertTasKToPolicyOwner(RequestK4KLog K4KOwner) { PolicyOwner response = null; if (K4KOwner != null) { var carPartyInfo = K4KOwner.CarInfo; response = new PolicyOwner(); response.carLicenseNo = carPartyInfo.CarRegisFront + carPartyInfo.CarRegisBack; if (carPartyInfo.CarRegisProvince != null) { response.carLicenseProvince = carPartyInfo.CarRegisProvince.ProvinceName; response.carLicenseProvinceShort = carPartyInfo.CarRegisProvince.ProvinceTitle; } response.caseDatetime = carPartyInfo.CreateDate.Value; response.caseNumber = ""; response.caseResult = ""; response.driverFirstName = K4KOwner.DriverFirstName; response.driverLastName = K4KOwner.DriverLastName; response.driverMobileNo = K4KOwner.DriverNumber; response.insurerCode = carPartyInfo.CarPolicy.PolicyInsId; response.ownerFirstName = carPartyInfo.CarPolicy.OwnerFirstName; response.ownerLastName = carPartyInfo.CarPolicy.OwnerLastName; response.ownerMobileNo = carPartyInfo.CarPolicy.OwnerPhoneNumber; response.policyEffective = carPartyInfo.CarPolicy.PolicyStartdate.Value.ToString(); response.policyNo = carPartyInfo.CarPolicy.PolicyCode; } return response; } public ThirdParty ConvertTasKToThirdParty(RequestK4KLog K4KParty) { ThirdParty response = null; if (K4KParty != null) { var carPartyInfo = K4KParty.CarInfo; response = new ThirdParty(); response.carLicenseNo = carPartyInfo.CarRegisFront + carPartyInfo.CarRegisBack; if (carPartyInfo.CarRegisProvince != null) { response.carLicenseProvince = carPartyInfo.CarRegisProvince.ProvinceName; response.carLicenseProvinceShort = carPartyInfo.CarRegisProvince.ProvinceTitle; } response.caseNumber = ""; response.driverFirstName = K4KParty.DriverFirstName; response.driverLastName = K4KParty.DriverLastName; response.driverMobileNo = K4KParty.DriverNumber; response.insurerCode = carPartyInfo.CarPolicy.PolicyInsId; response.ownerFirstName = carPartyInfo.CarPolicy.OwnerFirstName; response.ownerLastName = carPartyInfo.CarPolicy.OwnerLastName; response.ownerMobileNo = carPartyInfo.CarPolicy.OwnerPhoneNumber; response.policyNo = carPartyInfo.CarPolicy.PolicyCode; if (carPartyInfo.CarPolicy.Insurer != null) { response.insurerName = carPartyInfo.CarPolicy.Insurer.InsName; } } return response; } #endregion #region TaskPicture public List<SyncPictureType> GetPictureTypes(string language, DateTime? lastSyncedDateTime) { var repository = new Repository<PictureType>(_context); if (lastSyncedDateTime == null) { return repository.GetQuery().Where(t => t.IsActive == true) .Select(t => new SyncPictureType { isActive = t.IsActive, PictureType = (language.ToUpper() == Constant.Language.DefaultLanguage ? t.PictureTypeName : t.PictureTypeNameEn), PictureTypeId = t.PictureTypeId, Sort = t.Sort, PictureGroup = t.PictureGroup }) .ToList(); } else { return repository.GetQuery() .Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value) .OrderBy(x => (x.UpdateDate ?? x.CreateDate)) .Select(t => new SyncPictureType { isActive = t.IsActive, PictureType = (language.ToUpper() == Constant.Language.DefaultLanguage ? t.PictureTypeName : t.PictureTypeNameEn), PictureTypeId = t.PictureTypeId, Sort = t.Sort, PictureGroup = t.PictureGroup }) .ToList(); } } public TaskPicture GetTaskPicture(string TaskId, string PictureTypeId) { var req = new Repository<TaskPicture>(_context); var query = req.GetQuery(); return query.Where(t => t.TaskId == TaskId && t.PictureTypeId == PictureTypeId).SingleOrDefault(); } public BaseResult<long> SaveTaskPicture(TaskPicture obj) { BaseResult<long> res = new BaseResult<long>(); try { var req = new Repository<TaskPicture>(_context); var reqTask = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); if (obj.PictureId == 0) // insert { obj.CreateDate = DateTime.Now; obj.UpdateDate = DateTime.Now; obj.PictureParentId = (obj.PictureParentId == 0 ? null : obj.PictureParentId); obj.PictureParent = null; req.Add(obj); req.SaveChanges(); } else // update { var picture = req.Find(t => t.PictureId == obj.PictureId).FirstOrDefault(); if (picture != null) { if (obj.PictureApprove != null) { picture.PictureApprove = obj.PictureApprove; } if (!string.IsNullOrEmpty(obj.PictureNotApprove)) { picture.PictureNotApprove = obj.PictureNotApprove; } if (!string.IsNullOrEmpty(obj.PicturePath)) { picture.PicturePath = obj.PicturePath; } if (!string.IsNullOrEmpty(obj.PictureDesc)) { picture.PictureDesc = obj.PictureDesc; } if (!string.IsNullOrEmpty(obj.DamageLevelCode)) { picture.DamageLevelCode = obj.DamageLevelCode; } if (!string.IsNullOrEmpty(obj.PictureName)) { //for Reject Insurer Again //picture.PictureInsurerApprove = obj.PictureInsurerApprove; picture.PictureName = obj.PictureName; } if (!string.IsNullOrEmpty(obj.PictureTypeId)) { picture.PictureTypeId = obj.PictureTypeId; } picture.UpdateDate = DateTime.Now; picture.IsActive = obj.IsActive; req.SaveChanges(); } var task = reqTask.Find(t => t.TaskId == obj.TaskId).FirstOrDefault(); if (task != null) { task.UpdateDate = DateTime.Now; reqTask.SaveChanges(); } } res.Result = obj.PictureId; } catch (Exception ex) { res.Result = 0; res.StatusCode = Constant.ErrorCode.SystemError; res.Message = ex.Message; logger.Error(string.Format("Method = {0}", "saveTaskPicture"), ex); } return res; } #endregion #region TaskType public List<TaskType> GetTaskTypeList(bool? isActive = null, SortingCriteria sorting = null) { var req = new Repository<TaskType>(_context); List<TaskType> result = new List<TaskType>(); var query = req.GetQuery(); var exp = ExpressionBuilder.True<TaskType>(); if (isActive.HasValue && isActive.Value) { exp = exp.And(t => t.IsActive == isActive.Value); } if (sorting == null) { sorting = new SortingCriteria(); sorting.Add(new SortBy { Name = "Sort", Direction = SortDirection.ASC }); sorting.Add(new SortBy { Name = "TaskTypeName", Direction = SortDirection.ASC }); } query = query.Where(exp).OrderBy(sorting); return query.ToList(); } public List<TaskType> GetTaskTypeListConsumer(bool? isActive = null, SortingCriteria sorting = null) { var req = new Repository<TaskType>(_context); List<TaskType> result = new List<TaskType>(); var query = req.GetQuery(); var exp = ExpressionBuilder.True<TaskType>(); exp = exp.And(t => ConsumerTypeGroup.Contains(t.TaskTypeId)); if (isActive.HasValue && isActive.Value) { exp = exp.And(t => t.IsActive == isActive.Value); } if (sorting == null) { sorting = new SortingCriteria(); sorting.Add(new SortBy { Name = "Sort", Direction = SortDirection.ASC }); sorting.Add(new SortBy { Name = "TaskTypeName", Direction = SortDirection.ASC }); } query = query.Where(exp).OrderBy(sorting); return query.ToList(); } #endregion #region TaskProcess public List<TaskProcess> GetTaskProcessList(bool? isActive = null, string taskTypeId = "", SortingCriteria sorting = null) { var req = new Repository<TaskProcess>(_context); List<TaskProcess> result = new List<TaskProcess>(); var query = req.GetQuery(); var exp = ExpressionBuilder.True<TaskProcess>(); if (isActive.HasValue && isActive.Value) { exp = exp.And(t => t.IsActive == isActive.Value); } if (!string.IsNullOrEmpty(taskTypeId)) { exp = exp.And(t => t.TaskTypeId == taskTypeId || t.TaskTypeId == null); } if (sorting == null) { sorting = new SortingCriteria(); sorting.Add(new SortBy { Name = "Sort", Direction = SortDirection.ASC }); sorting.Add(new SortBy { Name = "TaskProcessName", Direction = SortDirection.ASC }); } query = query.Where(exp).OrderBy(sorting); return query.ToList(); } #endregion public List<Task> GetTaskListById(string taskId) { var req = new Repository<Task>(_context); var query = req.GetQuery(); return query.Where(t => t.TaskId == taskId).ToList(); } #region Viriyah public BaseResult<APIAddTaskInspectionResponse> AddTaskInspectionViriyah(APIAddTaskInspectionViriyahRequest request) { BaseResult<APIAddTaskInspectionResponse> response = new BaseResult<APIAddTaskInspectionResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIAddTaskInspectionViriyahRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); Task task = new Task(); task.AccId = Guid.Parse(request.AccId); task.TaskTypeId = TaskConsumerLogic.TaskTypeISPId; task.TaskId = genID.GetNewID(1, "", task.TaskTypeId); task.InsId = request.PolicyInsId; task.CarRegisFront = request.CarRegisFront; task.CarRegisBack = request.CarRegisBack; task.CarRegisProvinceCode = request.CarRegisProvinceCode; task.CarModelId = request.CarModelId; task.CarBrandId = request.CarBrandId; task.CarMile = request.CarMile; task.PolicyFirstName = request.PolicyFirstName; task.PolicyLastName = request.PolicyLastName; task.PolicyPhoneNumber = request.PolicyPhoneNumber; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.Ref1 = request.Ref1; task.Ref2 = request.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(request.Ref2); task.CreateDate = DateTime.Now; task.CreateBy = actionBy; task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; if (request.AppId != null) { task.AppId = Guid.Parse(request.AppId); } req.Add(task); req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskInspectionResponse(); response.Result.TaskId = task.TaskId; } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public BaseResult<APIAddTaskInspectionResponse> UpdateTaskInspectionViriyah(APIUpdateTaskInspectionViriyahRequest request) { BaseResult<APIAddTaskInspectionResponse> response = new BaseResult<APIAddTaskInspectionResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIUpdateTaskInspectionViriyahRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == request.TaskId).SingleOrDefault(); if (task != null) { task.InsId = request.PolicyInsId; task.CarRegisFront = request.CarRegisFront; task.CarRegisBack = request.CarRegisBack; task.CarRegisProvinceCode = request.CarRegisProvinceCode; task.CarModelId = request.CarModelId; task.CarBrandId = request.CarBrandId; task.CarMile = request.CarMile; task.PolicyFirstName = request.PolicyFirstName; task.PolicyLastName = request.PolicyLastName; task.PolicyPhoneNumber = request.PolicyPhoneNumber; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.Ref1 = request.Ref1; task.Ref2 = request.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(request.Ref2); task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; if (request.AppId != null) { task.AppId = Guid.Parse(request.AppId); } req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskInspectionResponse(); response.Result.TaskId = task.TaskId; } else { response.DataNotFound(); } } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public void SendEmailWhenInspectionRequest(string taskId, HttpContext httpContext) { try { TaskConsumerLogic taskConsumerLogic = new TaskConsumerLogic(_context); Task model = taskConsumerLogic.GetTaskById(taskId); //EmailConfigLogic emailConfigLogic = new EmailConfigLogic(_context); //var emailConfig = emailConfigLogic.GetEmailConfigByInsureIdAndTaskTypeId(model.InsId, model.TaskTypeId); CompanyLogic companyLogic = new CompanyLogic(); var dataCompanies = companyLogic.GetCompanyInsureByInsId(model.InsId); if (dataCompanies == null && dataCompanies.Count == 0) { return; } var dataCompanyOwner = dataCompanies[0]; DepartmentLogic departmentLogic = new DepartmentLogic(); Anywhere2Go.DataAccess.Entity.Department dataDepartmentSendEmail = null; dataDepartmentSendEmail = departmentLogic.GetDepartmentByCompIdAndPrefixCode(dataCompanyOwner.comId.ToString(), model.PrefixRef2); if (dataDepartmentSendEmail == null) { // Default 999 dataDepartmentSendEmail = departmentLogic.GetDepartmentByCompIdAndPrefixCode(dataCompanyOwner.comId.ToString(), "999"); } if (dataDepartmentSendEmail != null && !string.IsNullOrEmpty(dataDepartmentSendEmail.Email)) { SendMail sendEmail = new SendMail(Configurator.MailHost, Configurator.MailUser, Configurator.MailPass, Convert.ToInt32(Configurator.MailPort), Convert.ToBoolean(Configurator.MailSSL)); string urlInspectionDetail = Configurator.UriTaskKnockForKnockDetail + "/" + model.TaskId; string carRegis = model.CarRegisFront + " " + model.CarRegisBack + " " + (model.CarRegisProvince != null ? model.CarRegisProvince.ProvinceName : ""); StringBuilder sb = new StringBuilder(); sb.Append(EmailTemplateLogic.GetEmailTemplateInspection(carRegis, urlInspectionDetail, httpContext)); sendEmail.SenderName = Constant.Email.SenderName; sendEmail.Subject = Constant.Email.SubjectInspection.Replace("[CarRegis]", carRegis); sendEmail.MailToHTML = true; sendEmail.Body = sb.ToString(); sendEmail.mailSendFrom = Configurator.MailUser; var emails = dataDepartmentSendEmail.Email.Split(';'); if (emails.Length > 0) { sendEmail.ToUsers = new System.Net.Mail.MailAddressCollection(); foreach (var item in emails) { sendEmail.ToUsers.Add(item); } sendEmail.SendingManyReceives(); } else { sendEmail.ToUser = dataDepartmentSendEmail.Email; sendEmail.Sending(); } } } catch (Exception ex) { logger.Error("SendEmailWhenInspectionRequest", ex); } } #endregion #region SharePoint public BaseResult<APIAddTaskInspectionResponse> AddTaskInspectionSharePoint(APIAddTaskInspectionSharePointRequest request) { BaseResult<APIAddTaskInspectionResponse> response = new BaseResult<APIAddTaskInspectionResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIAddTaskInspectionSharePointRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); var genID = new Utility.GenerateID(_context); Task task = new Task(); task.AccId = Guid.Parse(request.AccId); task.TaskTypeId = TaskConsumerLogic.TaskTypeISPId; task.TaskId = genID.GetNewID(1, "", task.TaskTypeId); task.InsId = request.PolicyInsId; task.CarRegisFront = request.CarRegisFront; task.CarRegisBack = request.CarRegisBack; task.CarRegisProvinceCode = request.CarRegisProvinceCode; task.CarModelId = request.CarModelId; task.CarBrandId = request.CarBrandId; task.CarMile = request.CarMile; task.PolicyFirstName = request.PolicyFirstName; task.PolicyLastName = request.PolicyLastName; task.PolicyPhoneNumber = request.PolicyPhoneNumber; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.Ref1 = request.Ref1; task.Ref2 = request.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(request.Ref2); task.CreateDate = DateTime.Now; task.CreateBy = actionBy; task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; if (request.AppId != null) { task.AppId = Guid.Parse(request.AppId); } req.Add(task); req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskInspectionResponse(); response.Result.TaskId = task.TaskId; } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } public BaseResult<APIAddTaskInspectionResponse> UpdateTaskInspectionSharePoint(APIUpdateTaskInspectionSharePointRequest request) { BaseResult<APIAddTaskInspectionResponse> response = new BaseResult<APIAddTaskInspectionResponse>(); var validationResult = DataAnnotation.ValidateEntity<APIUpdateTaskInspectionSharePointRequest>(request); if (validationResult.HasError) { response.StatusCode = Constant.ErrorCode.RequiredData; response.Message = validationResult.HasErrorMessage; } else { using (var con = _context.Database.BeginTransaction()) { try { var account = new AccountProfileLogic(_context).GetAccountProfileById(request.AccId); string actionBy = account.FirstName + " " + account.LastName; var req = new Repository<Task>(_context); Task task = req.GetQuery().Where(t => t.TaskId == request.TaskId).SingleOrDefault(); if (task != null) { task.InsId = request.PolicyInsId; task.CarRegisFront = request.CarRegisFront; task.CarRegisBack = request.CarRegisBack; task.CarRegisProvinceCode = request.CarRegisProvinceCode; task.CarModelId = request.CarModelId; task.CarBrandId = request.CarBrandId; task.CarMile = request.CarMile; task.PolicyFirstName = request.PolicyFirstName; task.PolicyLastName = request.PolicyLastName; task.PolicyPhoneNumber = request.PolicyPhoneNumber; task.Latitude = request.Latitude; task.Longitude = request.Longitude; task.Ref1 = request.Ref1; task.Ref2 = request.Ref2; task.PrefixRef2 = SubStringPrefixCodeFromRef2(request.Ref2); task.UpdateDate = DateTime.Now; task.UpdateBy = actionBy; if (request.AppId != null) { task.AppId = Guid.Parse(request.AppId); } req.SaveChanges(); con.Commit(); response.Result = new APIAddTaskInspectionResponse(); response.Result.TaskId = task.TaskId; } else { response.DataNotFound(); } } catch (Exception ex) { con.Rollback(); response.SystemError(ex); } } } return response; } #endregion } public class TaskActionModel { public bool Success { get; set; } public Task Task { get; set; } public Guid? OldAssignAccId { get; set; } public bool IsSendPush { get; set; } public int TotalAssign { get; set; } public string TaskId { get; set; } public FCMNotification.EPushType PushType { get; set; } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using SimpleRESTChat.Entities; using SimpleRESTChat.Services.BusinessObjects; using SimpleRESTChat.Services.Enumerations; namespace SimpleRESTChat.Services.Services.Interfaces { public interface IUserService { Task<UserAction> RegisterUser(User user); Task<UserAction> DeleteUser(User user); Task<UserBo> UserLogIn(User user); Task<UserAction> UserLogOut(User user); Task<List<User>> FindUsersByCondition(Expression<Func<User, bool>> expression); Task<User> FindFirstUserByCondition(Expression<Func<User, bool>> expression); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TYNMU.manger { public partial class Redister_User : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void BtnReg_Click(object sender, EventArgs e) { string UserName = TxtUser.Text.ToString(); string PassWD = TxtUserPassWD.Text.ToString(); //加密 PassWD = Data.DAO.GetMD5(PassWD); string Reason = TxtReason.Text.ToString(); string sSql = "insert into T_Apply(UserName,UserPassWD,ApplyReason) values ('" + UserName + "','" + PassWD + "','" + Reason + "')"; Data.DAO.NonQuery(sSql); } } }
namespace TaskNF.Migrations { using System; using System.Data.Entity.Migrations; public partial class createschema : DbMigration { public override void Up() { CreateTable( "dbo.Autors", c => new { idAutor = c.Int(nullable: false, identity: true), FirstName = c.String(), LastName = c.String(), }) .PrimaryKey(t => t.idAutor); CreateTable( "dbo.Books", c => new { IdBook = c.Int(nullable: false, identity: true), Title = c.String(), Language = c.String(), PublisherDate = c.DateTimeOffset(nullable: false, precision: 7), PublisherName_PublishedId = c.Int(), }) .PrimaryKey(t => t.IdBook) .ForeignKey("dbo.Publisher", t => t.PublisherName_PublishedId) .Index(t => t.PublisherName_PublishedId); CreateTable( "dbo.Genres", c => new { IdGenre = c.Int(nullable: false, identity: true), GenreName = c.String(), }) .PrimaryKey(t => t.IdGenre); CreateTable( "dbo.Publisher", c => new { PublishedId = c.Int(nullable: false, identity: true), PublisherName = c.String(), CountryId = c.Int(nullable: false), Country_IdCountry = c.Int(), }) .PrimaryKey(t => t.PublishedId) .ForeignKey("dbo.Countries", t => t.Country_IdCountry) .Index(t => t.Country_IdCountry); CreateTable( "dbo.Countries", c => new { IdCountry = c.Int(nullable: false, identity: true), CountryName = c.String(), }) .PrimaryKey(t => t.IdCountry); CreateTable( "dbo.EmailAddresses", c => new { IdAdress = c.Int(nullable: false, identity: true), Email = c.String(), IdAutor = c.Int(nullable: false), idPublisher = c.Int(nullable: false), Publisher_PublishedId = c.Int(), }) .PrimaryKey(t => t.IdAdress) .ForeignKey("dbo.Autors", t => t.IdAutor, cascadeDelete: true) .ForeignKey("dbo.Publisher", t => t.Publisher_PublishedId) .Index(t => t.IdAutor) .Index(t => t.Publisher_PublishedId); CreateTable( "dbo.BookAutors", c => new { Book_IdBook = c.Int(nullable: false), Autor_idAutor = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Book_IdBook, t.Autor_idAutor }) .ForeignKey("dbo.Books", t => t.Book_IdBook, cascadeDelete: true) .ForeignKey("dbo.Autors", t => t.Autor_idAutor, cascadeDelete: true) .Index(t => t.Book_IdBook) .Index(t => t.Autor_idAutor); CreateTable( "dbo.GenreBooks", c => new { Genre_IdGenre = c.Int(nullable: false), Book_IdBook = c.Int(nullable: false), }) .PrimaryKey(t => new { t.Genre_IdGenre, t.Book_IdBook }) .ForeignKey("dbo.Genres", t => t.Genre_IdGenre, cascadeDelete: true) .ForeignKey("dbo.Books", t => t.Book_IdBook, cascadeDelete: true) .Index(t => t.Genre_IdGenre) .Index(t => t.Book_IdBook); } public override void Down() { DropForeignKey("dbo.EmailAddresses", "Publisher_PublishedId", "dbo.Publisher"); DropForeignKey("dbo.EmailAddresses", "IdAutor", "dbo.Autors"); DropForeignKey("dbo.Publisher", "Country_IdCountry", "dbo.Countries"); DropForeignKey("dbo.Books", "PublisherName_PublishedId", "dbo.Publisher"); DropForeignKey("dbo.GenreBooks", "Book_IdBook", "dbo.Books"); DropForeignKey("dbo.GenreBooks", "Genre_IdGenre", "dbo.Genres"); DropForeignKey("dbo.BookAutors", "Autor_idAutor", "dbo.Autors"); DropForeignKey("dbo.BookAutors", "Book_IdBook", "dbo.Books"); DropIndex("dbo.GenreBooks", new[] { "Book_IdBook" }); DropIndex("dbo.GenreBooks", new[] { "Genre_IdGenre" }); DropIndex("dbo.BookAutors", new[] { "Autor_idAutor" }); DropIndex("dbo.BookAutors", new[] { "Book_IdBook" }); DropIndex("dbo.EmailAddresses", new[] { "Publisher_PublishedId" }); DropIndex("dbo.EmailAddresses", new[] { "IdAutor" }); DropIndex("dbo.Publisher", new[] { "Country_IdCountry" }); DropIndex("dbo.Books", new[] { "PublisherName_PublishedId" }); DropTable("dbo.GenreBooks"); DropTable("dbo.BookAutors"); DropTable("dbo.EmailAddresses"); DropTable("dbo.Countries"); DropTable("dbo.Publisher"); DropTable("dbo.Genres"); DropTable("dbo.Books"); DropTable("dbo.Autors"); } } }
using System; using System.Collections.Generic; using SpringHeroBank.entity; using SpringHeroBank.model; using SpringHeroBank.utility; using SpringHeroBank.view; namespace SpringHeroBank { class Program { static void Main(string[] args) { MainView.GenerateMenu(); // HashMap // Dictionary<string, string> dictionary = new Dictionary<string, string>(); // // dictionary.Add("username", "Username can not be null or empty."); // dictionary.Add("password", "Password is too weak."); // // Console.WriteLine(dictionary.Count); // if (dictionary.ContainsKey("username")) // { // Console.WriteLine(dictionary["username"]); // } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using VendingMachine.Domain.Business.Contracts.Repository; using VendingMachine.Domain.Models; namespace VendingMachine.Repository.Repositories { public class GeldRepository : BaseRepository<Geld>, IGeldRepository { public Geld GetGeldByHoeveelheid(double hoeveelheid) { using (var context = CreateContext()) { return context.Set<Geld>() .AsNoTracking() .Where(n => n.Valuta == hoeveelheid) .FirstOrDefault(); } } public List<Geld> GetVoorraadGeld() { List<Geld> result = new List<Geld>(); using (var context = CreateContext()) { result = context.Set<Geld>() .AsNoTracking() .OrderByDescending(n => n.Kwantiteit) .ToList(); } return result; } public void ChangeGeld(double hoeveelheid, int amount) { Geld geldObj = GetGeldByHoeveelheid(hoeveelheid); geldObj.Kwantiteit += amount; using (var context = CreateContext()) { if (geldObj.Id > 0) { // Update context.Set<Geld>().Attach(geldObj); context.Entry(geldObj).State = EntityState.Modified; } context.SaveChanges(); } } } }
using UnityAtoms.BaseAtoms; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Set variable value Action of type `Vector3`. Inherits from `SetVariableValue&lt;Vector3, Vector3Pair, Vector3Variable, Vector3Constant, Vector3Reference, Vector3Event, Vector3PairEvent, Vector3VariableInstancer&gt;`. /// </summary> [EditorIcon("atom-icon-purple")] [CreateAssetMenu(menuName = "Unity Atoms/Actions/Set Variable Value/Vector3", fileName = "SetVector3VariableValue")] public sealed class SetVector3VariableValue : SetVariableValue< Vector3, Vector3Pair, Vector3Variable, Vector3Constant, Vector3Reference, Vector3Event, Vector3PairEvent, Vector3Vector3Function, Vector3VariableInstancer> { } }
using System; namespace GatewayEDI.Logging { /// <summary> A very simple implementation of <see cref="ILog" /> that outputs all messages to the system console. </summary> public class ConsoleLog : FormattableLogBase { /// <summary> Creates a named logger. </summary> /// <param name="name"> The logger name. </param> public ConsoleLog(string name) : base(name) { } /// <summary> Creates an un-named logger. </summary> public ConsoleLog() { } /// <summary> Logs a given item to the console. </summary> /// <param name="item"> The item to be logged. </param> /// <exception cref="ArgumentNullException"> If <paramref name="item" /> is a null reference. </exception> public override void Write(LogItem item) { if (item == null) throw new ArgumentNullException("item"); Console.Out.WriteLine(FormatItem(item)); } #region NDC /// <summary> Pushes a new context message on to the stack implementation of the underlying logger. </summary> /// <param name="message"> The new context message. </param> /// <returns> An IDisposable reference to the stack. </returns> public override IDisposable Push(string message) { //TODO: This needs to be added to the Console.WriteLine call in Write. throw new NotImplementedException(); } /// <summary> Pops a context message off of the stack implementation of the underlying logger. </summary> /// <returns> The context message that was on the top of the stack. </returns> public override string Pop() { //TODO: This needs to be added to the Console Logger. throw new NotImplementedException(); } /// <summary> Clears all the contextual information held on the stack implementation of the underlying logger. </summary> public override void ClearNdc() { //TODO: This needs to be added to the Console Logger. throw new NotImplementedException(); } #endregion #region MDC /// <summary> Add an entry to the contextual properties of the underlying logger. </summary> /// <param name="key"> The key to store the value under. </param> /// <param name="value"> The value to store. </param> public override void Set(string key, string value) { //TODO: This needs to be added to the Console Logger. throw new NotImplementedException(); } /// <summary> Gets the context value identified by the <paramref name="key" /> parameter. </summary> /// <param name="key"> The key to lookup in the underlying logger. </param> /// <returns> The value of the named context property. </returns> public override string Get(string key) { //TODO: This needs to be added to the Console Logger. throw new NotImplementedException(); } /// <summary> Removes the key value mapping for the key specified. </summary> /// <param name="key"> The key to remove. </param> public override void Remove(string key) { //TODO: This needs to be added to the Console Logger. throw new NotImplementedException(); } /// <summary> Clear all entries in the underlying logger. </summary> public override void ClearMdc() { //TODO: This needs to be added to the Console Logger. throw new NotImplementedException(); } #endregion } }
namespace BettingSystem.Application.Games.Matches.Commands.Create { using Common; using FluentValidation; public class CreateMatchCommandValidator : AbstractValidator<CreateMatchCommand> { public CreateMatchCommandValidator() => this.Include(new MatchCommandValidator<CreateMatchCommand>()); } }
using System; namespace practice { public class Node { Node link = null; //link to the next node in the link list int value; // value of each individual node public Node (int v) { value = v; } /*Returns the address of the next node in the list*/ public Node getLink() { return link; } public int getValue(){ return value; } public void setLink(Node n){ link = n; } public void setValue(int v){ value = v; } } }
using System; using System.Collections.Generic; using System.Text; namespace EasyConsoleNG { public static class Validators { public static Func<int, string> IsIntInRange(int min, int max) { return (value) => { var checkMin = min != int.MinValue; var checkMax = max != int.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<int?, string> IsNullableIntInRange(int min, int max) { return (value) => { var checkMin = min != int.MinValue; var checkMax = max != int.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<long, string> IsLongInRange(long min, long max) { return (value) => { var checkMin = min != long.MinValue; var checkMax = max != long.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<long?, string> IsNullableLongInRange(long min, long max) { return (value) => { var checkMin = min != long.MinValue; var checkMax = max != long.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<float, string> IsFloatInRange(float min, float max) { return (value) => { var checkMin = min != float.MinValue; var checkMax = max != float.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<float?, string> IsNullableFloatInRange(float min, float max) { return (value) => { var checkMin = min != float.MinValue; var checkMax = max != float.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<double, string> IsDoubleInRange(double min, double max) { return (value) => { var checkMin = min != double.MinValue; var checkMax = max != double.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } public static Func<double?, string> IsNullableDoubleInRange(double min, double max) { return (value) => { var checkMin = min != double.MinValue; var checkMax = max != double.MaxValue; var tooSmall = checkMin && value < min; var tooLarge = checkMax && value > max; return ValidateRange(checkMin, checkMax, min, max, tooSmall, tooLarge); }; } private static string ValidateRange(bool checkMin, bool checkMax, double min, double max, bool tooSmall, bool tooLarge) { if (checkMin && checkMax && (tooSmall || tooLarge)) { return $"Value must be between {min} and {max} (inclusive)."; } else if (checkMin && tooSmall) { return $"Value must not be greater than or equal to {min}."; } else if (checkMax && tooLarge) { return $"Value must not be less than or equal to {max}."; } return null; } } }
using LiveDemo_MVC.App_Start; using LiveDemo_MVC.Data; using LiveDemo_MVC.Data.Models; using LiveDemo_MVC.DataServices.Contracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ninject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiveDemo_MVC.IntegrationTests.LiveDemo_MVC.DataServices.CategoryServiceTests { [TestClass] public class GetAllCategoriesSortedById_Should { private static List<Category> dbCategories = new List<Data.Models.Category>() { new Category() { Id = Guid.NewGuid(), Name = "category 1" }, new Category() { Id = Guid.NewGuid(), Name = "category 2" }, new Category() { Id = Guid.NewGuid(), Name = "category 3" } }; private static Book dbBook = new Book() { Id = Guid.NewGuid(), Author = "author", Description = "description", ISBN = "ISBN", Title = "title", WebSite = "website" }; private static IKernel kernel; [TestInitialize] public void TestInit() { kernel = NinjectWebCommon.CreateKernel(); LiveDemoEfDbContext dbContext = kernel.Get<LiveDemoEfDbContext>(); foreach (Category dbCategory in dbCategories) { dbContext.Categories.Add(dbCategory); } dbContext.SaveChanges(); var category = dbContext.Categories.First(); dbBook.CategoryId = category.Id; dbBook.Category = category; dbContext.Books.Add(dbBook); dbContext.SaveChanges(); } [TestCleanup] public void TestCleanup() { LiveDemoEfDbContext dbContext = kernel.Get<LiveDemoEfDbContext>(); foreach (Category dbCategory in dbCategories) { dbContext.Categories.Attach(dbCategory); dbContext.Categories.Remove(dbCategory); } dbContext.SaveChanges(); } [TestMethod] public void ReturnAllCategoriesSortedById() { // Arrange ICategoryService categoryService = kernel.Get<ICategoryService>(); var expectedOrder = dbCategories.OrderBy(c => c.Id).ToList(); // Act var result = categoryService.GetAllCategoriesSortedById().ToList(); // Assert for (int i = 0; i < expectedOrder.Count; i++) { Assert.AreEqual(expectedOrder[i].Id, result[i].Id); } } } }
using BikeDistributor.Data.Common; namespace BikeDistributor.Data.Entities { public class Product: BaseEntity<int> { public virtual string Brand { get; set; } public virtual string Model { get; set; } public virtual string Make { get; set; } public virtual string Sku { get; set; } public double Msrp { get; set; } public double TaxedPrice { get; set; } public double DiscountedPrice { get; set; } } }
using EddiConfigService; using EddiConfigService.Configurations; using JetBrains.Annotations; using Newtonsoft.Json; using RestSharp; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Utilities; namespace EddiInaraService { public partial class InaraService : IInaraService { // API Documentation: https://inara.cz/inara-api-docs/ // Constants private const string readonlyAPIkey = "9efrgisivgw8kksoosowo48kwkkw04skwcgo840"; private const int startupDelayMilliSeconds = 1000 * 10; // 10 seconds private const int syncIntervalMilliSeconds = 1000 * 60 * 5; // 5 minutes private const int delayedSyncIntervalMilliSeconds = 1000 * 60 * 60; // 60 minutes // Variables private static bool tooManyRequests; // This must be static so that it is visible to child threads and tasks private static readonly BlockingCollection<InaraAPIEvent> queuedAPIEvents = new BlockingCollection<InaraAPIEvent>(); private readonly List<string> invalidAPIEvents = new List<string>(); private static CancellationTokenSource syncCancellationTS; // This must be static so that it is visible to child threads and tasks private bool eddiIsBeta; public static EventHandler invalidAPIkey; // This API only accepts and only returns data for the "live" galaxy, game version 4.0 or later. private static readonly System.Version minGameVersion = new System.Version(4, 0); private static System.Version currentGameVersion { get; set; } public void Start ( bool _eddiIsBeta = false ) { if ( syncCancellationTS is null || syncCancellationTS.IsCancellationRequested ) { Logging.Debug( "Starting Inara service background sync." ); eddiIsBeta = _eddiIsBeta; Task.Run( BackgroundSync ).ConfigureAwait( false ); } } public void Stop () { if ( syncCancellationTS != null && !syncCancellationTS.IsCancellationRequested ) { Logging.Debug( "Stopping Inara service background sync." ); syncCancellationTS.Cancel(); // Clean up by sending anything left in the queue. SendAPIEvents( queuedAPIEvents.ToList() ); } } private async void BackgroundSync() { using (syncCancellationTS = new CancellationTokenSource()) { try { // Pause a short time to allow any initial events to build in the queue before our first sync await Task.Delay(startupDelayMilliSeconds, syncCancellationTS.Token).ConfigureAwait(false); await Task.Run(async () => { // The `GetConsumingEnumerable` method blocks the thread while the underlying collection is empty // If we haven't extracted events to send to Inara, this will wait / pause background sync until `queuedAPIEvents` is no longer empty. List<InaraAPIEvent> holdingQueue = new List<InaraAPIEvent>(); try { foreach (var pendingEvent in queuedAPIEvents.GetConsumingEnumerable(syncCancellationTS.Token)) { holdingQueue.Add(pendingEvent); if (queuedAPIEvents.Count == 0) { // Once we hit zero queued events, wait a couple more seconds for any concurrent events to register await Task.Delay(2000, syncCancellationTS.Token).ConfigureAwait(false); if (queuedAPIEvents.Count > 0) { continue; } // No additional events registered, send any events we have in our holding queue if (holdingQueue.Count > 0) { var sendingQueue = holdingQueue.ToList(); holdingQueue = new List<InaraAPIEvent>(); await Task.Run(() => SendAPIEvents(sendingQueue), syncCancellationTS.Token).ConfigureAwait(false); await Task.Delay(!tooManyRequests ? syncIntervalMilliSeconds : delayedSyncIntervalMilliSeconds, syncCancellationTS.Token).ConfigureAwait(false); } } } } catch (OperationCanceledException) { // Operation was cancelled. Return any events we've extracted back to the primary queue. foreach (var pendingEvent in holdingQueue) { queuedAPIEvents.Add(pendingEvent); } } }).ConfigureAwait(false); } catch (TaskCanceledException) { // Task cancelled. Nothing to do here. } } tooManyRequests = false; } // If you need to do some testing on Inara's API, please set the `isDeveloped` boolean header property to true. public List<InaraResponse> SendEventBatch ( List<InaraAPIEvent> events, InaraConfiguration inaraConfiguration ) { // We always want to return a list from this method (even if it's an empty list) rather than a null value. var inaraResponses = new List<InaraResponse>(); if ( events is null ) { return inaraResponses; } if ( inaraConfiguration is null ) { inaraConfiguration = ConfigService.Instance.inaraConfiguration; } if ( inaraConfiguration != null && checkAPIcredentialsOk( inaraConfiguration ) ) { try { var indexedEvents = IndexAndFilterAPIEvents( events, inaraConfiguration ); if ( indexedEvents.Count > 0 ) { var client = new RestClient( "https://inara.cz/inapi/v1/" ); var request = new RestRequest( Method.POST ); var inaraRequest = new InaraSendJson() { header = new Dictionary<string, object>() { { "appName", "EDDI" }, { "appVersion", Constants.EDDI_VERSION.ToString() }, { "isBeingDeveloped", eddiIsBeta }, { "APIkey", !string.IsNullOrEmpty(inaraConfiguration.apiKey) ? inaraConfiguration.apiKey : readonlyAPIkey } }, events = indexedEvents }; if ( !string.IsNullOrEmpty(inaraConfiguration.commanderName) ) { inaraRequest.header.Add( "commanderName", inaraConfiguration.commanderName ); } if ( !string.IsNullOrEmpty( inaraConfiguration.commanderFrontierID ) ) { inaraRequest.header.Add( "commanderFrontierID", inaraConfiguration.commanderFrontierID ); } request.RequestFormat = DataFormat.Json; request.AddJsonBody( inaraRequest ); // uses JsonSerializer Logging.Debug( "Sending to Inara: " + client.BuildUri( request ).AbsoluteUri, request ); var clientResponse = client.Execute<InaraResponses>( request ); if ( clientResponse.IsSuccessful ) { Logging.Debug( "Inara responded with: ", clientResponse.Content ); var response = clientResponse.Data; if ( validateResponse( response.header, indexedEvents, true ) ) { foreach ( var inaraResponse in response.events ) { if ( validateResponse( inaraResponse, indexedEvents ) ) { inaraResponses.Add( inaraResponse ); } } } } else { // Inara may return null as it undergoes a nightly maintenance cycle where the servers go offline temporarily. Logging.Warn( "Unable to connect to the Inara server.", clientResponse.ErrorMessage ); ReEnqueueAPIEvents( events ); } } } catch ( Exception ex ) { Logging.Error( "Sending data to the Inara server failed.", ex ); ReEnqueueAPIEvents( events ); } } else { ReEnqueueAPIEvents( events ); return inaraResponses; } return inaraResponses; } private List<InaraAPIEvent> IndexAndFilterAPIEvents(List<InaraAPIEvent> events, InaraConfiguration inaraConfiguration) { // If we don't have a commander name then only use `get` events and re-enqueue the rest. if (string.IsNullOrEmpty(inaraConfiguration.commanderName)) { var commanderUpdateEvents = events.Where(e => !e.eventName.StartsWith("get")).ToList(); ReEnqueueAPIEvents(commanderUpdateEvents); events = events.Except(commanderUpdateEvents).ToList(); } // Flag each event with a unique ID we can use when processing responses List<InaraAPIEvent> indexedEvents = new List<InaraAPIEvent>(); for (int i = 0; i < events.Count; i++) { InaraAPIEvent indexedEvent = events[i]; indexedEvent.eventCustomID = i; // Exclude and discard events with issues that have returned a code 400 error in this instance. if (invalidAPIEvents.Contains(indexedEvent.eventName)) { continue; } // Exclude and discard old / stale events if (inaraConfiguration.lastSync > indexedEvent.eventTimestamp) { continue; } // Inara will ignore the "setCommunityGoal" event while EDDI is in development mode (i.e. beta). if (indexedEvent.eventName == "setCommunityGoal" && eddiIsBeta) { continue; } // Note: the Inara Responder does not queue events while the game is in beta. indexedEvents.Add(indexedEvent); } return indexedEvents; } private bool validateResponse(InaraResponse inaraResponse, List<InaraAPIEvent> indexedEvents, bool header = false) { // 200 - Ok if (inaraResponse.eventStatus == 200) { return true; } // Anything else - something is wrong. Dictionary<string, object> data = new Dictionary<string, object>() { { "InaraAPIEvent", indexedEvents.Find(e => e.eventCustomID == inaraResponse.eventCustomID) }, { "InaraResponse", inaraResponse }, { "Stacktrace", new StackTrace() } }; try { // 202 - Warning (everything is OK, but there may be multiple results for the input properties, etc.) // 204 - 'Soft' error (everything was formally OK, but there are no results for the properties set, etc.) if (inaraResponse.eventStatus == 202 || inaraResponse.eventStatus == 204) { Logging.Warn("Inara warning or soft error reported: " + (inaraResponse.eventStatusText ?? "(No response)"), JsonConvert.SerializeObject(data)); } // Other errors else if (!string.IsNullOrEmpty(inaraResponse.eventStatusText)) { if (header) { Logging.Warn("Inara sending error: " + (inaraResponse.eventStatusText ?? "(No response)"), JsonConvert.SerializeObject(data)); if (inaraResponse.eventStatusText.Contains("Invalid API key")) { ReEnqueueAPIEvents(indexedEvents); // The Inara API key has been rejected. We'll note and remember that. var inaraConfiguration = ConfigService.Instance.inaraConfiguration; inaraConfiguration.isAPIkeyValid = false; ConfigService.Instance.inaraConfiguration = inaraConfiguration; // Send internal events to the Inara Responder and the UI to handle the invalid API key appropriately invalidAPIkey?.Invoke(inaraConfiguration, EventArgs.Empty); } else if (inaraResponse.eventStatusText.Contains("access to API was temporarily revoked")) { // Note: This can be thrown by over-use of the readonly API key. ReEnqueueAPIEvents(indexedEvents); tooManyRequests = true; } } else { // There may be an issue with a specific API event. // We'll add that API event to a list and omit sending that event again in this instance. Logging.Error("Inara event error: " + inaraResponse.eventStatusText, data); var eventName = indexedEvents.Find(e => e.eventCustomID == inaraResponse.eventCustomID)?.eventName; if ( !string.IsNullOrEmpty( eventName ) ) { invalidAPIEvents.Add( eventName ); } } } return false; } catch (Exception e) { Logging.Error("Failed to handle Inara server response", e); return false; } } private bool checkAPIcredentialsOk(InaraConfiguration inaraConfiguration) { // Check for a valid API key // Note that we don't check for a valid Inara commander name here - // we will apply a filter later to remove inelligible events if no commander name is present. if ( !inaraConfiguration.isAPIkeyValid ) { Logging.Warn( "Background sync skipped: API key is invalid." ); invalidAPIkey?.Invoke( inaraConfiguration, EventArgs.Empty ); return false; } if ( string.IsNullOrEmpty( inaraConfiguration.apiKey ) ) { Logging.Info( "Background sync skipped: API key not set." ); return false; } return true; } private void SendAPIEvents ( List<InaraAPIEvent> queue ) { var inaraConfiguration = ConfigService.Instance.inaraConfiguration; var responses = SendEventBatch( queue, inaraConfiguration ); if ( responses != null && responses.Count > 0 ) { inaraConfiguration.lastSync = queue.Max( e => e.eventTimestamp ); ConfigService.Instance.inaraConfiguration = inaraConfiguration; } } public void EnqueueAPIEvent(InaraAPIEvent inaraAPIEvent) { if (currentGameVersion != null && currentGameVersion < minGameVersion) { return; } if (inaraAPIEvent.eventName.StartsWith("get")) { Logging.Error("Cannot enqueue 'get' Inara API events as these require an immediate response. Send these directly."); return; } queuedAPIEvents.Add(inaraAPIEvent); } private void ReEnqueueAPIEvents(IEnumerable<InaraAPIEvent> inaraAPIEvents) { // Re-enqueue the data so we can send it again later. foreach (var inaraAPIEvent in inaraAPIEvents) { // Do not re-enqueue 'get' Inara API events if (inaraAPIEvent.eventName.StartsWith("get")) { continue; } // Clear any ID / index value assigned to the data inaraAPIEvent.eventCustomID = null; EnqueueAPIEvent(inaraAPIEvent); } } public static void SetGameVersion(System.Version version) { currentGameVersion = version; if (currentGameVersion != null && currentGameVersion < minGameVersion) { Logging.Warn($"Service disabled. Game version is {currentGameVersion}, service may only send and receive data for version {minGameVersion} or later."); } } } internal class InaraSendJson { [UsedImplicitly] public Dictionary<string, object> header; [UsedImplicitly] public List<InaraAPIEvent> events; } internal class InaraResponses { [UsedImplicitly] public InaraResponse header { get; set; } [UsedImplicitly] public List<InaraResponse> events { get; set; } } public class InaraResponse { [UsedImplicitly] public int eventStatus { get; set; } [UsedImplicitly] public string eventStatusText { get; set; } // Optional status text. Typically not set unless there was a problem. [UsedImplicitly] public object eventData { get; set; } [UsedImplicitly] public int eventCustomID { get; set; } // Optional index. Used to match outgoing API events to responses. } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static damdrempe_zadaca_2.Podaci.Enumeracije; namespace damdrempe_zadaca_2.Podaci.Modeli { public enum Kategorija { Mali, Srednji, Veliki } class Korisnik { public int ID { get; set; } public Kategorija Kategorija { get; set; } public Dictionary<VrstaOtpada, float> Otpad { get; set; } public Korisnik() { Otpad = new Dictionary<VrstaOtpada, float>(); } } }
using TheMartian.Enums; using TheMartian.Interfaces; namespace TheMartian.Conrete { public class VoucherBase : IVoucher { public VoucherBase(Position position) { Position = position; } public Position Position { get; set; } public Position Move(string codes) { IMoveable moveable; foreach (char code in codes) { if (code == 'L') { moveable = new MoveLeft(); Position = moveable.Move(this); } else if (code == 'R') { moveable = new MoveRight(); Position = moveable.Move(this); } else if (code == 'M') { moveable = new MoveOneStep(); Position = moveable.Move(this); } } return Position; } } }
using System; namespace PL.Integritas.Domain.Entities { public abstract class EntityBase { #region Properties public Int64 Id { get; set; } public Boolean Active { get; set; } public DateTime? DateRegistered { get; set; } public DateTime? DateUpdated { get; set; } #endregion } }
using UnityEngine; public class PlayerMovement : MonoBehaviour { private Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } private void Update() { float horizontal = Input.GetAxisRaw("Horizontal"); float vertical = Input.GetAxisRaw("Vertical"); Vector3 rotationAxis = new Vector3(vertical, 0, -horizontal).normalized; rb.AddTorque(rotationAxis); } }
namespace Condor { public static class MediaTypes { public const string Atom = "application/atom+xml"; public const string Json = "application/json"; } }
using System.Threading; using System.Threading.Tasks; using Ardalis.ApiEndpoints; using AutoMapper; using BlazorShared.Models.Doctor; using ClinicManagement.Core.Aggregates; using Microsoft.AspNetCore.Mvc; using PluralsightDdd.SharedKernel.Interfaces; using Swashbuckle.AspNetCore.Annotations; namespace ClinicManagement.Api.DoctorEndpoints { public class Create : BaseAsyncEndpoint .WithRequest<CreateDoctorRequest> .WithResponse<CreateDoctorResponse> { private readonly IRepository _repository; private readonly IMapper _mapper; public Create(IRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } [HttpPost("api/doctors")] [SwaggerOperation( Summary = "Creates a new Doctor", Description = "Creates a new Doctor", OperationId = "doctors.create", Tags = new[] { "DoctorEndpoints" }) ] public override async Task<ActionResult<CreateDoctorResponse>> HandleAsync(CreateDoctorRequest request, CancellationToken cancellationToken) { var response = new CreateDoctorResponse(request.CorrelationId()); var toAdd = _mapper.Map<Doctor>(request); toAdd = await _repository.AddAsync<Doctor, int>(toAdd); var dto = _mapper.Map<DoctorDto>(toAdd); response.Doctor = dto; return Ok(response); } } }
using Alabo.Domains.Enums; using Alabo.Domains.Query.Dto; using Alabo.Framework.Core.Enums.Enum; using Alabo.Regexs; using Alabo.Validations; using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Basic.Address.Dtos { /// <summary> /// 地址输入 /// </summary> public class AddressInput : EntityDto { /// <summary> /// 地址ID /// </summary> public string Id { get; set; } /// <summary> /// 收货人名称 /// </summary> [Display(Name = "姓名")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [Field(ControlsType = ControlsType.TextBox, IsShowBaseSerach = true, Width = "100", ListShow = true, SortOrder = 2)] public string Name { get; set; } /// <summary> /// 用户Id /// </summary> [Display(Name = "用户Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public long UserId { get; set; } /// <summary> /// 区域Id /// </summary> [Display(Name = "区域Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public long RegionId { get; set; } /// <summary> /// 是否默认地址 /// </summary> [Display(Name = "是否默认")] [Field(ControlsType = ControlsType.TextBox, ListShow = false, EditShow = true, SortOrder = 7)] public bool IsDefault { get; set; } = false; /// <summary> /// 地址方式 /// </summary> [Display(Name = "地址类型")] [Field(EditShow = false, Width = "100", ListShow = true, SortOrder = 5)] public AddressLockType Type { get; set; } = AddressLockType.OrderAddress; /// <summary> /// 详细街道地址,不需要重复填写省/市/区 /// </summary> [Display(Name = "详细地址")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [StringLength(30, ErrorMessage = ErrorMessage.MaxStringLength)] [Field(ControlsType = ControlsType.TextBox, IsShowAdvancedSerach = true, Width = "150", ListShow = false, SortOrder = 3)] public string Address { get; set; } /// <summary> /// 手机号码 /// </summary> [Display(Name = "手机号码")] [RegularExpression(RegularExpressionHelper.ChinaMobile, ErrorMessage = ErrorMessage.NotMatchFormat)] [Field(ControlsType = ControlsType.TextBox, IsShowBaseSerach = true, IsShowAdvancedSerach = true, Width = "90", ListShow = true, SortOrder = 7)] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public string Mobile { get; set; } } /// <summary> /// 用户备案地址修改 /// </summary> public class UserInfoAddressInput : EntityDto { /// <summary> /// 地址ID /// </summary> public string Id { get; set; } /// <summary> /// 用户Id /// </summary> [Display(Name = "用户Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public long UserId { get; set; } /// <summary> /// 区域Id /// </summary> [Display(Name = "区域Id")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public long RegionId { get; set; } /// <summary> /// 详细街道地址,不需要重复填写省/市/区 /// </summary> [Display(Name = "详细地址")] [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] [StringLength(40, ErrorMessage = ErrorMessage.MaxStringLength)] [Field(ControlsType = ControlsType.TextBox, IsShowAdvancedSerach = true, Width = "150", ListShow = false, SortOrder = 3)] public string Address { get; set; } /// <summary> /// 地址方式 /// </summary> public AddressLockType Type { get; set; } = AddressLockType.OrderAddress; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MedAllWebApplication.Models { public class RoleDTO { public RoleDTO() { this.Users = new HashSet<UserDTO>(); } public int Id { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<UserDTO> Users { get; set; } } }
using StackExchange.Redis; using System.Threading.Tasks; namespace Microsoft.UnifiedRedisPlatform.Core.Database { public partial class UnifiedRedisDatabase { public bool HyperLogLogAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.HyperLogLogAdd(CreateAppKey(key), value, flags)); public bool HyperLogLogAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.HyperLogLogAdd(CreateAppKey(key), values, flags)); public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.HyperLogLogAddAsync(CreateAppKey(key), value, flags)); public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.HyperLogLogAddAsync(CreateAppKey(key), values, flags)); public long HyperLogLogLength(RedisKey key, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.HyperLogLogLength(CreateAppKey(key), flags)); public long HyperLogLogLength(RedisKey[] keys, CommandFlags flags = CommandFlags.None) => Execute(() => _baseDatabase.HyperLogLogLength(CreateAppKeys(keys), flags)); public Task<long> HyperLogLogLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.HyperLogLogLengthAsync(CreateAppKey(key), flags)); public Task<long> HyperLogLogLengthAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => _baseDatabase.HyperLogLogLengthAsync(CreateAppKeys(keys), flags)); public void HyperLogLogMerge(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) => Execute(() => { _baseDatabase.HyperLogLogMerge(CreateAppKey(destination), CreateAppKey(first), CreateAppKey(second), flags); return true; }); public void HyperLogLogMerge(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None) => Execute(() => { _baseDatabase.HyperLogLogMerge(CreateAppKey(destination), CreateAppKeys(sourceKeys), flags); return true; }); public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => { _baseDatabase.HyperLogLogMergeAsync(CreateAppKey(destination), CreateAppKey(first), CreateAppKey(second), flags); return Task.FromResult(true); }); public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None) => ExecuteAsync(() => { _baseDatabase.HyperLogLogMergeAsync(CreateAppKey(destination), CreateAppKeys(sourceKeys), flags); return Task.FromResult(true); }); } }
using System; using System.Linq; using System.Xml.Linq; using TeamCityChangeNotifier.Models; namespace TeamCityChangeNotifier.XmlParsers { public class ChangeDataParser { public ChangeData ReadXml(string changeXml) { var changeDoc = XDocument.Parse(changeXml); var root = changeDoc.Root; var id = ReadId(root); var comment = ReadComment(root); var userName = ReadUserName(root); var date = ReadDate(root); return new ChangeData { Id = id, Author = userName, Message = comment, Date = date }; } private DateTime ReadDate(XElement root) { var dateAttr = root.Attribute("date").Value; return DateParser.Parse(dateAttr); } private static int ReadId(XElement root) { var idAttr = root.Attribute("id").Value; return int.Parse(idAttr); } private static string ReadComment(XElement root) { var commentNode = root.Descendants("comment").First(); var comment = commentNode.Value; if (!string.IsNullOrEmpty(comment)) { comment = comment.Trim(); } return comment; } private static string ReadUserName(XElement root) { var userNode = root.Descendants("user").FirstOrDefault(); if (userNode != null) { return userNode.Attribute("name").Value; } return root.Attribute("username").Value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EmploeeSalary { class SalaryEmployee : EmployeeBase { public int MonthSalary; public SalaryEmployee(string firstName, string lastName, string position, int monthsalary) : base(firstName, lastName, position) { MonthSalary = monthsalary; } public override double GetSalaryPerMonth() { return MonthSalary; } } }
using System; using System.Collections.Generic; using System.Linq; using DAL.Entity; using System.Text; using System.Threading.Tasks; using System.Linq.Expressions; namespace DAL.Repository { public class PersonRepository { public IEnumerable<Person> GetAll() { try { using (CensusDataContext context = new CensusDataContext()) { IEnumerable<Person> persons = (from p in context.Persons select p).ToList(); return persons; } } catch { return null; } } public bool Create(Person person) { using (CensusDataContext context = new CensusDataContext()) { try { var result= (from h in context.House where h.HouseId==person.CensusHouseNumber select h).Single(); if (result == null) throw new Exception(); context.Persons.Add(person); context.SaveChanges(); return true; } catch(Exception ex) { Console.WriteLine(ex.Message); return false; } } } public IEnumerable<Person> Find(Expression<Func<Person, bool>> predicate) { CensusDataContext context = new CensusDataContext(); return context.Persons.Where(predicate); } //public bool DeleteById(int id) // { // try // { // using (CensusDataContext context = new CensusDataContext()) // { // var result = (from p in context.Persons // where p.PersonId == id // select p).ToList().First(); // context.Persons.Remove(result); // context.SaveChanges(); // return true; // } // } // catch // { // return false; // } // } //public Person GetById(int id) // { // using (CensusDataContext context = new CensusDataContext()) // { // try // { // Person person = (from p in context.Persons // where p.PersonId== id // select p).Single(); // return person; // } // catch // { // return null; // } // } // } } }
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Zovi_Fashion.Models { public class Product { [Key] //Primary key used for products public int ProductID { get; set; } [Required] [StringLength(200)] //string length is 200 public string ProductName { get; set; } [StringLength(400)] public string Fabric { get; set; } //Fabric name [StringLength(400)] public string ManufacturingYear { get; set; } //what year is manufacturing [StringLength(400)] public string Description { get; set; } [StringLength(400)] public string Color { get; set; } //Colour of cloth [StringLength(400)] public string Fit { get; set; } //Men or women [StringLength(400)] public string SleveLength { get; set; } [StringLength(400)] public string Occasion { get; set; } //What occasion [StringLength(400)] public string PatternType { get; set; } [StringLength(400)] public string Size { get; set; } //Size of clothes [StringLength(400)] public string Neck { get; set; } [StringLength(400)] public string WashCare { get; set; } [StringLength(400)] public string SoldBy { get; set; } [StringLength(400)] public string Price { get; set; } //Price of cloth [Required] [StringLength(20)] public string Extension { get; set; } [Required] public int BrandID { get; set; } [ForeignKey("BrandID")] [InverseProperty("BrandProducts")] public virtual Brand Brand { get; set; } public virtual ICollection<ProductReview> ProductReviews { get; set; } [NotMapped] public SingleFileUpload File { get; set; } //Upload file } public class SingleFileUpload { [Required] [Display(Name = "File")] public IFormFile FormFile { get; set; } } }
using Common.Business; using Common.Data; using Common.Exceptions; using Common.Extensions; using LFP.Common.DataAccess; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Runtime.Serialization; using System.Text; namespace Entity { [DataContract] public class XmlReady : IMappable { #region Constructors public XmlReady() { } #endregion #region Public Properties public string TableName { get { return "XML_Ready"; } } [DataMember] public Int32? Index_CTR { get; set; } [DataMember] public Int32? ID { get; set; } [DataMember] public string Channel { get; set; } [DataMember] public DateTime? Sched_Date { get; set; } [DataMember] public Int32? XML_Ready { get; set; } [DataMember] public DateTime? Ready_On { get; set; } [DataMember] public string Ready_Username { get; set; } #endregion #region Public Methods public int GetCountChannelDate(string connectionString, string channel, DateTime date) { int result = default(int); string sql = "select count(*) from xml_ready where channel = '" + channel + "' and sched_date = " + "'" + date.ToString(Constants.DateFormat) + "'"; using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectInt(sql).GetValueOrDefault(); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public List<XmlReady> GetList(string connectionString, string sql, SqlParameter[] parameters = null) { List<XmlReady> result = new List<XmlReady>(); Database database = new Database(connectionString); try { CommandType commandType = CommandType.Text; if (parameters != null) commandType = CommandType.StoredProcedure; using (DataTable table = database.ExecuteSelect(sql, commandType, parameters)) { if (table.HasRows()) { Mapper<XmlReady> m = new Mapper<XmlReady>(); result = m.MapListSelect(table); } } } catch (Exception e) { throw new EntityException(sql, e); } finally { database = null; } return result; } public XmlReady GetItem(string connectionString, int id, string channel, DateTime date) { string sql = "select * from xml_ready where channel = '" + channel + "' " + "and sched_date = '" + date.ToString(Constants.DateFormat) + "' and id = " + id.ToString(); return GetRecord(connectionString, sql); } public XmlReady GetRecord(string connectionString, string sql, SqlParameter[] parameters = null) { XmlReady result = null; Database database = new Database(connectionString); try { CommandType commandType = CommandType.Text; if (parameters != null) commandType = CommandType.StoredProcedure; using (DataTable table = database.ExecuteSelect(sql, commandType, parameters)) { if (table.HasRows()) { Mapper<XmlReady> m = new Mapper<XmlReady>(); result = m.MapSingleSelect(table); } } } catch (Exception e) { throw new EntityException(sql, e); } finally { database = null; } return result; } public string GetReleaseSchedules(string connectionString, int id, string userName) { string result = String.Empty; //select * from xml_ready where id = @ID and xml_ready = 1 order by sched_date, channel string sql = "P_Get_XML_Ready"; SqlParameter parameter = new SqlParameter("@ID", id); List<XmlReady> list = GetList(connectionString, sql, new SqlParameter[] { parameter }); if (list.Count == 0) return result; DataAccess da = new DataAccess(connectionString, userName); StringBuilder sb = new StringBuilder(); try { foreach (XmlReady data in list) { sb.AppendLine(data.Sched_Date.Value.ToString(Constants.DateFormat)); sb.AppendLine(data.Channel); sb.AppendLine("Marked Ready on: " + data.Ready_On.Value.ToString(Constants.DateFormat)); string fullName = da.GetUserFullName(data.Ready_Username); sb.AppendLine("Marked Ready by: " + fullName); sb.AppendLine("------"); } } finally { da = null; } result = sb.ToString(); return result; } public bool IsXmlReady(string connectionString, int id, string channel, DateTime scheduleDate) { bool result = false; //select count(*) from xml_ready where id = @ID and channel = @Channel and sched_date = @SchedDate //and xml_ready = 1 string sql = "P_Reports_VODProd_GetXMLReady"; List<SqlParameter> parameters = new List<SqlParameter>(); parameters.Add(new SqlParameter("@ID", id)); parameters.Add(new SqlParameter("@Channel", channel)); parameters.Add(new SqlParameter("@SchedDate", scheduleDate.ToString(Constants.DateFormat))); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectInt(sql, parameters: parameters.ToArray()).GetValueOrDefault() > 0; } catch (Exception e) { throw new EntityException(sql, e); } finally { parameters.Clear(); } } return result; } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace GenericCountMethodDouble { public class Box<T> where T : IComparable<T> { public Box(List<T> items) { this.Items = items; } public List<T> Items { get; set; } public int Compare(T element) { int counter = 0; foreach (var item in this.Items) { if (item.CompareTo(element) > 0) { counter++; } } return counter; } } }
using ChatBot.Domain.Core; using ChatBot.Entities; using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; namespace ChatBot.Domain.Services { public class UnexFacilitiesService : IUnexFacilitiesService { #region Consts private const string UNEX_FACILITIES_PATH = "https://www.unex.es/organizacion/servicios-universitarios"; #endregion public async Task<List<UnexFacilitieModel>> GetUnexFacilities() { List<UnexFacilitieModel> unexFacilitiesModels = new List<UnexFacilitieModel>(); var httpClient = new HttpClient(); try { var html = await httpClient.GetStringAsync(UNEX_FACILITIES_PATH); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var categoriesFacilitiesService = htmlDocument.DocumentNode.SelectSingleNode("//div[@id='content-core']"); var categoryName = "Servicio"; foreach (var servicesTypeNode in categoriesFacilitiesService?.ChildNodes) { if (servicesTypeNode.OriginalName.Equals("h2")) categoryName = servicesTypeNode.SelectSingleNode("span/a").InnerHtml; if (servicesTypeNode.OriginalName.Equals("dl")) { var facilitie = servicesTypeNode.SelectSingleNode("dt/span/a"); unexFacilitiesModels.Add(new UnexFacilitieModel { Category = categoryName, Name = HttpUtility.HtmlDecode(facilitie.InnerHtml), Url = facilitie.GetAttributeValue("href", string.Empty) }); } } } catch (Exception) { return unexFacilitiesModels; } return unexFacilitiesModels; } public async Task<List<string>> GetUnexFacilitiesCategories() { var categories = new List<string>(); var httpClient = new HttpClient(); try { var html = await httpClient.GetStringAsync(UNEX_FACILITIES_PATH); var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var categoriesFacilities = htmlDocument.DocumentNode.SelectNodes("//div[@id='content-core']/h2/span/a").ToList(); foreach (var category in categoriesFacilities) categories.Add(category.InnerHtml); } catch (Exception) { return categories; } return categories; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using AutoMapper; using MediatR; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Razor; using Microsoft.Framework.OptionsModel; using Microsoft.Net.Http.Headers; using SciVacancies.Domain.DataModels; using SciVacancies.Domain.Enums; using SciVacancies.ReadModel.Core; using SciVacancies.WebApp.Commands; using SciVacancies.WebApp.Queries; using SciVacancies.WebApp.ViewModels; using Microsoft.Framework.Logging; namespace SciVacancies.WebApp.Controllers { [ResponseCache(NoStore = true)] [Authorize] public class ApplicationsController : Controller { private readonly IMediator _mediator; private readonly IHostingEnvironment _hostingEnvironment; private readonly IOptions<AttachmentSettings> _attachmentSettings; private readonly ILogger _logger; public ApplicationsController(IMediator mediator, IHostingEnvironment hostingEnvironment, IOptions<AttachmentSettings> attachmentSettings, ILoggerFactory loggerFactory) { _mediator = mediator; _hostingEnvironment = hostingEnvironment; _attachmentSettings = attachmentSettings; _logger = loggerFactory.CreateLogger<ApplicationsController>(); } #region private VacancyApplicationCreateViewModelHelper private VacancyApplicationCreateViewModel VacancyApplicationCreateViewModelHelper(Guid researcherGuid, Vacancy vacancy, VacancyApplicationCreateViewModel model) { var researcher = _mediator.Send(new SingleResearcherQuery { ResearcherGuid = researcherGuid }); model = model ?? new VacancyApplicationCreateViewModel(); model.ResearcherGuid = researcherGuid; model.VacancyGuid = vacancy.guid; model.PositionName = vacancy.name; model.BirthDate = researcher.birthdate; model.ImageUrl = researcher.image_url; model.Email = researcher.email; model.Phone = researcher.phone; model.ResearcherFullName = $"{researcher.secondname} {researcher.firstname} {researcher.patronymic}"; model.ResearcherFullNameEng = $"{researcher.firstname_eng} {researcher.patronymic_eng} {researcher.secondname_eng}"; IEnumerable<Education> educations = _mediator.Send(new SelectResearcherEducationsQuery { ResearcherGuid = researcherGuid }); if (educations != null && educations.Count() > 0) { model.Educations = Mapper.Map<List<EducationEditViewModel>>(educations); } IEnumerable<Publication> publications = _mediator.Send(new SelectResearcherPublicationsQuery { ResearcherGuid = researcherGuid }); if (publications != null && publications.Count() > 0) { model.Publications = Mapper.Map<List<PublicationEditViewModel>>(publications); } model.ResearchActivity = researcher.research_activity; model.TeachingActivity = researcher.teaching_activity; model.OtherActivity = researcher.other_activity; model.ScienceDegree = researcher.science_degree; model.ScienceRank = researcher.science_rank; model.Rewards = researcher.rewards; model.Memberships = researcher.memberships; model.Conferences = researcher.conferences; model.Interests = researcher.interests; model.ReadId = vacancy.read_id; return model; } #endregion [Authorize(Roles = ConstTerms.RequireRoleResearcher)] [PageTitle("Новая заявка")] [BindResearcherIdFromClaims] public ViewResult Create(Guid researcherGuid, Guid vacancyGuid) { if (researcherGuid == Guid.Empty) throw new ArgumentNullException(nameof(researcherGuid)); if (vacancyGuid == Guid.Empty) throw new ArgumentNullException(nameof(vacancyGuid)); var vacancy = _mediator.Send(new SingleVacancyQuery { VacancyGuid = vacancyGuid }); if (vacancy.status != VacancyStatus.Published) return View("Error", $"Вы не можете подать Заявку на Вакансию в статусе: {vacancy.status.GetDescriptionByResearcher()}"); var appliedVacancyApplications = _mediator.Send(new SelectVacancyApplicationsByResearcherQuery { ResearcherGuid = researcherGuid }); if (appliedVacancyApplications != null && appliedVacancyApplications.Any() && appliedVacancyApplications.Where(c => c.vacancy_guid == vacancyGuid && c.status == VacancyApplicationStatus.Applied).Select(c => c.researcher_guid).Distinct().ToList().Any(c => c == researcherGuid)) return View("Error", "Вы не можете подать повторную Заявку на Вакансию"); var model = VacancyApplicationCreateViewModelHelper(researcherGuid, vacancy, null); //TODO: Applications -> Create : вернуть добавление дополнительнительных публикаций return View(model); } [PageTitle("Новая заявка")] [Authorize(Roles = ConstTerms.RequireRoleResearcher)] [HttpPost] [BindResearcherIdFromClaims] public IActionResult Create(VacancyApplicationCreateViewModel model, Guid researcherGuid) { if (model.VacancyGuid == Guid.Empty) throw new ArgumentNullException(nameof(model.VacancyGuid), "Не указан идентификатор Вакансии"); var vacancy = _mediator.Send(new SingleVacancyQuery { VacancyGuid = model.VacancyGuid }); if (vacancy.status != VacancyStatus.Published) return View("Error", $"Вы не можете подать Заявку на Вакансию в статусе: {vacancy.status.GetDescriptionByResearcher()}"); var appliedVacancyApplications = _mediator.Send(new SelectVacancyApplicationsByResearcherQuery { ResearcherGuid = researcherGuid }); if (appliedVacancyApplications!=null && appliedVacancyApplications.Any() && appliedVacancyApplications.Where(c => c.vacancy_guid == model.VacancyGuid && c.status == VacancyApplicationStatus.Applied).Select(c => c.researcher_guid).Distinct().ToList().Any(c => c == researcherGuid)) return View("Error", "Вы не можете подать повторную Заявку на Вакансию"); //TODO: Application -> Attachments : как проверять безопасность, прикрепляемых файлов //todo: повторяющийся код if (model.Attachments != null && model.Attachments.Any()) { //проверяем размеры файлов if (model.Attachments.Any(c => c.Length > _attachmentSettings.Value.VacancyApplication.MaxItemSize)) ModelState.AddModelError("Attachments", $"Размер одного из прикрепленных файлов превышает допустимый размер ({_attachmentSettings.Value.VacancyApplication.MaxItemSize / 1000}КБ)."); //проверяем расширения файлов, если они указаны if (!string.IsNullOrWhiteSpace(_attachmentSettings.Value.VacancyApplication.AllowExtensions)) { var fileNames = model.Attachments.Select( c => System.IO.Path.GetFileName( ContentDispositionHeaderValue.Parse(c.ContentDisposition).FileName.Trim('"'))); var fileExtensionsInUpper = fileNames.Select(c => c.Split('.') .Last() .ToUpper() ); var allowedExtenionsInUpper = _attachmentSettings.Value.VacancyApplication.AllowExtensions.ToUpper(); if (fileExtensionsInUpper.Any(c => !allowedExtenionsInUpper.Contains(c))) ModelState.AddModelError("Attachments", $"Расширение одного из прикрепленных файлов имеет недопустимое расширение. Допустимые типы файлов: {allowedExtenionsInUpper}"); } } //с формы мы не получаем практически никаких данных, поэтому заново наполняем ViewModel model = VacancyApplicationCreateViewModelHelper(researcherGuid, vacancy, model); if (!ModelState.IsValid) return View(model); #region attachments var attachmentsList = new List<SciVacancies.Domain.Core.VacancyApplicationAttachment>(); var newFolderName = Guid.NewGuid(); //save attachments var fullDirectoryPath = $"{_hostingEnvironment.WebRootPath}{_attachmentSettings.Value.VacancyApplication.PhisicalPathPart}/{newFolderName}/"; if (model.Attachments != null && model.Attachments.Any()) { foreach (var file in model.Attachments) { var fileName = System.IO.Path.GetFileName(ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"')); var isExists = Directory.Exists(fullDirectoryPath); //сценарий-А: сохранить файл на диск try { //TODO: Application -> Attachments : как искать Текущую директорию при повторном добавлении(изменении текущего списка) файлов //TODO: Application -> Attachments : можно ли редактировать список файлов, или Заявки создаются разово и для каждой создаётся новая папка с вложениями if (!isExists) Directory.CreateDirectory(fullDirectoryPath); var filePath = $"{_hostingEnvironment.WebRootPath}{_attachmentSettings.Value.VacancyApplication.PhisicalPathPart}/{newFolderName}/{fileName}"; file.SaveAs(filePath); attachmentsList.Add(new SciVacancies.Domain.Core.VacancyApplicationAttachment { Size = file.Length, Extension = fileName.Split('.').Last(), Name = fileName, UploadDate = DateTime.Now, Url = $"/{newFolderName}/{fileName}" }); } catch (Exception) { if (!isExists) RemoveAttachmentDirectory(fullDirectoryPath); return View("Error", "Ошибка при сохранении прикреплённых файлов"); } //TODO: сохранение файл в БД (сделать) //using (var memoryStream = new MemoryStream()) //{ // файл в byte // byte[] byteData; // //сценарий-Б: сохранить файл в БД // //var openReadStream = file.OpenReadStream(); // //var scale = (int)(500000 / file.Length); // //var resizedImage = new Bitmap(image, new Size(image.Width * scale, image.Height * scale)); // //((Image)resizedImage).Save(memoryStream, ImageFormat.Jpeg); // //byteData = memoryStream.ToArray(); // //memoryStream.SetLength(0); // //сценарий-В: сохранить файл в БД // //var openReadStream = file.OpenReadStream(); // //openReadStream.CopyTo(memoryStream); // //byteData = memoryStream.ToArray(); // //memoryStream.SetLength(0); //} } //присваиваем прикреплённым файлам тип "Резюме" (для соответствущей выборки) attachmentsList.ForEach(c => c.TypeId = 2); } #endregion Guid vacancyApplicationGuid; try { var data = Mapper.Map<VacancyApplicationDataModel>(model); data.Attachments = attachmentsList; vacancyApplicationGuid = _mediator.Send(new CreateAndApplyVacancyApplicationCommand { ResearcherGuid = model.ResearcherGuid, VacancyGuid = model.VacancyGuid, Data = data }); } catch (Exception e) { RemoveAttachmentDirectory(fullDirectoryPath); return View("Error", $"Что-то пошло не так при сохранении Заявки: {e.Message}"); } return RedirectToAction("details", "applications", new { id = vacancyApplicationGuid }); } private void RemoveAttachmentDirectory(string fullpath) { if (Directory.Exists(fullpath)) Directory.Delete(fullpath); } [Authorize(Roles = ConstTerms.RequireRoleResearcher)] [PageTitle("Детали заявки")] [BindResearcherIdFromClaims] public IActionResult Details(Guid id, Guid researcherGuid) { if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); var preModel = _mediator.Send(new SingleVacancyApplicationQuery { VacancyApplicationGuid = id }); if (preModel == null) return HttpNotFound(); //throw new ObjectNotFoundException($"Не найдена Заявка c идентификатором: {id}"); if (researcherGuid != Guid.Empty && User.IsInRole(ConstTerms.RequireRoleResearcher) && preModel.researcher_guid != researcherGuid) return View("Error", "Вы не можете просматривать Заявки других соискателей."); var model = Mapper.Map<VacancyApplicationDetailsViewModel>(preModel); model.Vacancy = Mapper.Map<VacancyDetailsViewModel>(_mediator.Send(new SingleVacancyQuery { VacancyGuid = preModel.vacancy_guid })); model.Attachments = _mediator.Send(new SelectAllVacancyApplicationAttachmentsQuery { VacancyApplicationGuid = id }); model.FolderApplicationsAttachmentsUrl = _attachmentSettings.Value.VacancyApplication.UrlPathPart; return View(model); } /// <summary> /// организации рпосматривают присланные Заявки /// </summary> /// <param name="id"></param> /// <param name="organizationGuid"></param> /// <returns></returns> [Authorize(Roles = ConstTerms.RequireRoleOrganizationAdmin)] [PageTitle("Детали заявки")] [BindOrganizationIdFromClaims] public IActionResult Preview(Guid id, Guid organizationGuid) { if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); var preModel = _mediator.Send(new SingleVacancyApplicationQuery { VacancyApplicationGuid = id }); if (preModel == null) return HttpNotFound(); //throw new ObjectNotFoundException($"Не найдена Заявка c идентификатором: {id}"); if (preModel.status == VacancyApplicationStatus.InProcess || preModel.status == VacancyApplicationStatus.Cancelled || preModel.status == VacancyApplicationStatus.Lost || preModel.status == VacancyApplicationStatus.Removed) return View("Error", $"Вы не можете просматривать Заявку со статусом: {preModel.status.GetDescription()}"); var vacancy = _mediator.Send(new SingleVacancyQuery { VacancyGuid = preModel.vacancy_guid }); if (vacancy.organization_guid != organizationGuid) return View("Error", "Вы не можете просматривать Заявки, поданные на вакансии других организаций."); var model = Mapper.Map<VacancyApplicationDetailsViewModel>(preModel); model.Vacancy = Mapper.Map<VacancyDetailsViewModel>(vacancy); model.Attachments = _mediator.Send(new SelectAllVacancyApplicationAttachmentsQuery { VacancyApplicationGuid = id }); model.FolderApplicationsAttachmentsUrl = _attachmentSettings.Value.VacancyApplication.UrlPathPart; return View(model); } private object OfferAcceptionPreValidation(Guid vacancyApplicationGuid, Guid researcherGuid, bool isWinner) { var vacancyApplicaiton = _mediator.Send(new SingleVacancyApplicationQuery { VacancyApplicationGuid = vacancyApplicationGuid }); if (vacancyApplicaiton == null) return HttpNotFound(); //throw new ObjectNotFoundException($"Не найдена Заявка c идентификатором: {vacancyApplicationGuid}"); if (isWinner && vacancyApplicaiton.status != VacancyApplicationStatus.Won) return View("Error", "Вы не можете принять предложение если Вы не Победитель"); if (!isWinner && vacancyApplicaiton.status != VacancyApplicationStatus.Pretended) return View("Error", "Вы не можете принять предложение если Вы не Победитель"); var vacancy = _mediator.Send(new SingleVacancyQuery { VacancyGuid = vacancyApplicaiton.vacancy_guid }); if (vacancy == null) return HttpNotFound(); //throw new ObjectNotFoundException($"Не найдена Вакансия c идентификатором: {vacancyApplicaiton.vacancy_guid}"); if (isWinner) { if (vacancy.status != VacancyStatus.OfferResponseAwaitingFromWinner) return View("Error", $"Вы не можете принять предложение или отказаться от него если Вакансия имеет статус: {vacancy.status.GetDescriptionByResearcher()}"); if (vacancy.winner_researcher_guid != researcherGuid) return View("Error", "Вы не можете принять или отказаться от предложения, сделанного для другого заявителя."); } if (!isWinner) { if (vacancy.status != VacancyStatus.OfferResponseAwaitingFromPretender) return View("Error", $"Вы не можете принять предложение или отказаться от него если Вакансия имеет статус: {vacancy.status.GetDescriptionByResearcher()}"); if (vacancy.pretender_researcher_guid != researcherGuid) return View("Error", "Вы не можете принять или отказаться от предложения, сделанного для другого заявителя."); } return vacancy; } [Authorize(Roles = ConstTerms.RequireRoleOrganizationAdmin)] [PageTitle("Детали заявки")] [BindOrganizationIdFromClaims] public IActionResult Print(Guid id, Guid organizationGuid) { if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); var preModel = _mediator.Send(new SingleVacancyApplicationQuery { VacancyApplicationGuid = id }); if (preModel == null) return HttpNotFound(); //throw new ObjectNotFoundException($"Не найдена Заявка c идентификатором: {id}"); if (preModel.status == VacancyApplicationStatus.InProcess || preModel.status == VacancyApplicationStatus.Cancelled || preModel.status == VacancyApplicationStatus.Lost || preModel.status == VacancyApplicationStatus.Removed) return View("Error", $"Вы не можете просматривать Заявку со статусом: {preModel.status.GetDescription()}"); var vacancy = _mediator.Send(new SingleVacancyQuery { VacancyGuid = preModel.vacancy_guid }); if (vacancy.organization_guid != organizationGuid) return View("Error", "Вы не можете изменять Заявки, поданные на вакансии других организаций."); var model = Mapper.Map<VacancyApplicationDetailsViewModel>(preModel); model.Vacancy = Mapper.Map<VacancyDetailsViewModel>(vacancy); model.Attachments = _mediator.Send(new SelectAllVacancyApplicationAttachmentsQuery { VacancyApplicationGuid = id }); model.FolderApplicationsAttachmentsUrl = _attachmentSettings.Value.VacancyApplication.UrlPathPart; return View(model); } [Authorize(Roles = ConstTerms.RequireRoleResearcher)] [BindResearcherIdFromClaims] public IActionResult OfferAcception(Guid id, Guid researcherGuid, bool isWinner, bool hasAccepted) { if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); if (researcherGuid == Guid.Empty) throw new ArgumentNullException(nameof(researcherGuid)); var result = OfferAcceptionPreValidation(id, researcherGuid, isWinner); if (result is HttpNotFoundResult) return (HttpNotFoundResult)result; var vacancy = (Vacancy)result; if (isWinner) if (hasAccepted) _mediator.Send(new SetWinnerAcceptOfferCommand { VacancyGuid = vacancy.guid }); else _mediator.Send(new SetWinnerRejectOfferCommand { VacancyGuid = vacancy.guid }); else if (hasAccepted) _mediator.Send(new SetPretenderAcceptOfferCommand { VacancyGuid = vacancy.guid }); else _mediator.Send(new SetPretenderRejectOfferCommand { VacancyGuid = vacancy.guid }); return RedirectToAction("details", "applications", new { id }); } } }
using TripLog.ViewModels; using Xamarin.Forms; namespace TripLog.Views { public class ViewFactory { public ContentPage BuildNewPage(NewEntryPageViewModel vm) { return new NewEntryPage(vm); } public ContentPage BuildDetailPage(DetailPageViewModel vm) { var page = new DetailPage(vm); return page; } } }
/* * Created by SharpDevelop. * User: admin * Date: 09.07.2012 * Time: 1:21 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Drawing; using System.Windows.Forms; namespace sudoku { /// <summary> /// Description of butun. /// </summary> public partial class butun : Form { private string figure; public butun() { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // } private void strn(string str) { figure=str; this.DialogResult = DialogResult.OK; } void Button1Click(object sender, EventArgs e) { strn("1"); } void Button2Click(object sender, EventArgs e) { strn("2"); } void Button3Click(object sender, EventArgs e) { strn("3"); } void Button4Click(object sender, EventArgs e) { strn("4"); } void Button5Click(object sender, EventArgs e) { strn("5"); } void Button6Click(object sender, EventArgs e) { strn("6"); } void Button7Click(object sender, EventArgs e) { strn("7"); } void Button8Click(object sender, EventArgs e) { strn("8"); } void Button9Click(object sender, EventArgs e) { strn("9"); } public string STR() { return figure; } void ButunLoad(object sender, EventArgs e) { } void ButunFormClosing(object sender, FormClosingEventArgs e) { this.DialogResult= DialogResult.No; strn(""); } } }